You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ko...@apache.org on 2015/05/19 18:20:47 UTC

[01/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Repository: cloudstack
Updated Branches:
  refs/heads/CLOUDSTACK-8301 e5cee452b -> 8ff90008b


Refactoring the LibvirtComputingResource
  - Adding LibvirtAttachIsoCommandWrapper, LibvirtAttachIsoCommandWrapper and LibvirtAttachIsoCommandWrapper
  - 7 unit tests added
  - KVM hypervisor plugin with 11.5% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4d216f1a
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4d216f1a
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4d216f1a

Branch: refs/heads/CLOUDSTACK-8301
Commit: 4d216f1a6382c42cf94a947aa5432f4d18782811
Parents: be1e517
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Apr 23 14:24:53 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:20:42 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  53 +----
 .../wrapper/LibvirtAttachIsoCommandWrapper.java |  52 +++++
 ...ibvirtCheckVirtualMachineCommandWrapper.java |  51 +++++
 .../wrapper/LibvirtReadyCommandWrapper.java     |  34 ++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   6 +
 .../resource/LibvirtComputingResourceTest.java  | 196 +++++++++++++++++++
 6 files changed, 343 insertions(+), 49 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 1c7aa24..0fb20ee 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -87,7 +87,6 @@ import com.ceph.rbd.Rbd;
 import com.ceph.rbd.RbdException;
 import com.ceph.rbd.RbdImage;
 import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeAnswer;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.BackupSnapshotAnswer;
@@ -95,8 +94,6 @@ import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.CheckNetworkAnswer;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
-import com.cloud.agent.api.CheckVirtualMachineAnswer;
-import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
@@ -138,8 +135,6 @@ import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
 import com.cloud.agent.api.PlugNicAnswer;
 import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PvlanSetupCommand;
-import com.cloud.agent.api.ReadyAnswer;
-import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.SecurityGroupRuleAnswer;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
@@ -1314,13 +1309,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof CheckVirtualMachineCommand) {
-                return execute((CheckVirtualMachineCommand)cmd);
-            } else if (cmd instanceof ReadyCommand) {
-                return execute((ReadyCommand)cmd);
-            } else if (cmd instanceof AttachIsoCommand) {
-                return execute((AttachIsoCommand)cmd);
-            } else if (cmd instanceof AttachVolumeCommand) {
+            if (cmd instanceof AttachVolumeCommand) {
                 return execute((AttachVolumeCommand)cmd);
             } else if (cmd instanceof CheckConsoleProxyLoadCommand) {
                 return execute((CheckConsoleProxyLoadCommand)cmd);
@@ -2951,21 +2940,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result);
     }
 
-    private Answer execute(final AttachIsoCommand cmd) {
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
-            attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(), cmd.isAttach());
-        } catch (final LibvirtException e) {
-            return new Answer(cmd, false, e.toString());
-        } catch (final URISyntaxException e) {
-            return new Answer(cmd, false, e.toString());
-        } catch (final InternalErrorException e) {
-            return new Answer(cmd, false, e.toString());
-        }
-
-        return new Answer(cmd);
-    }
-
     private AttachVolumeAnswer execute(final AttachVolumeCommand cmd) {
         try {
             final Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
@@ -2983,16 +2957,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new AttachVolumeAnswer(cmd, cmd.getDeviceId(), cmd.getVolumePath());
     }
 
-    private Answer execute(final ReadyCommand cmd) {
-        return new ReadyAnswer(cmd);
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;
     }
 
-    protected PowerState getVmState(final Connect conn, final String vmName) {
+    public PowerState getVmState(final Connect conn, final String vmName) {
         int retry = 3;
         Domain vms = null;
         while (retry-- > 0) {
@@ -3015,21 +2985,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return PowerState.PowerOff;
     }
 
-    private Answer execute(final CheckVirtualMachineCommand cmd) {
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
-            final PowerState state = getVmState(conn, cmd.getVmName());
-            Integer vncPort = null;
-            if (state == PowerState.PowerOn) {
-                vncPort = getVncPort(conn, cmd.getVmName());
-            }
-
-            return new CheckVirtualMachineAnswer(cmd, state, vncPort);
-        } catch (final LibvirtException e) {
-            return new CheckVirtualMachineAnswer(cmd, e.getMessage());
-        }
-    }
-
     public String networkUsage(final String privateIpAddress, final String option, final String vif) {
         final Script getUsage = new Script(_routerProxyPath, s_logger);
         getUsage.add("netusage.sh");
@@ -3719,7 +3674,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _storagePoolMgr;
     }
 
-    protected synchronized String attachOrDetachISO(final Connect conn, final String vmName, String isoPath, final boolean isAttach) throws LibvirtException, URISyntaxException,
+    public synchronized String attachOrDetachISO(final Connect conn, final String vmName, String isoPath, final boolean isAttach) throws LibvirtException, URISyntaxException,
     InternalErrorException {
         String isoXml = null;
         if (isoPath != null && isAttach) {
@@ -4948,4 +4903,4 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
         return device;
     }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
new file mode 100644
index 0000000..4380b66
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
@@ -0,0 +1,52 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.net.URISyntaxException;
+
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.AttachIsoCommand;
+import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtAttachIsoCommandWrapper extends CommandWrapper<AttachIsoCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final AttachIsoCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            libvirtComputingResource.attachOrDetachISO(conn, command.getVmName(), command.getIsoPath(), command.isAttach());
+        } catch (final LibvirtException e) {
+            return new Answer(command, false, e.toString());
+        } catch (final URISyntaxException e) {
+            return new Answer(command, false, e.toString());
+        } catch (final InternalErrorException e) {
+            return new Answer(command, false, e.toString());
+        }
+
+        return new Answer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
new file mode 100644
index 0000000..3ad3300
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
@@ -0,0 +1,51 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CheckVirtualMachineAnswer;
+import com.cloud.agent.api.CheckVirtualMachineCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.vm.VirtualMachine.PowerState;
+
+public final class LibvirtCheckVirtualMachineCommandWrapper extends CommandWrapper<CheckVirtualMachineCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CheckVirtualMachineCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final PowerState state = libvirtComputingResource.getVmState(conn, command.getVmName());
+            Integer vncPort = null;
+            if (state == PowerState.PowerOn) {
+                vncPort = libvirtComputingResource.getVncPort(conn, command.getVmName());
+            }
+
+            return new CheckVirtualMachineAnswer(command, state, vncPort);
+        } catch (final LibvirtException e) {
+            return new CheckVirtualMachineAnswer(command, e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java
new file mode 100644
index 0000000..7fce909
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtReadyCommandWrapper.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ReadyAnswer;
+import com.cloud.agent.api.ReadyCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtReadyCommandWrapper extends CommandWrapper<ReadyCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final ReadyCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        return new ReadyAnswer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index aeac43c..ff0a8a5 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -21,7 +21,9 @@ package com.cloud.hypervisor.kvm.resource.wrapper;
 import java.util.Hashtable;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
@@ -29,6 +31,7 @@ import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
+import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
@@ -64,6 +67,9 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(PrepareForMigrationCommand.class, new LibvirtPrepareForMigrationCommandWrapper());
         linbvirtCommands.put(MigrateCommand.class, new LibvirtMigrateCommandWrapper());
         linbvirtCommands.put(PingTestCommand.class, new LibvirtPingTestCommandWrapper());
+        linbvirtCommands.put(CheckVirtualMachineCommand.class, new LibvirtCheckVirtualMachineCommandWrapper());
+        linbvirtCommands.put(ReadyCommand.class, new LibvirtReadyCommandWrapper());
+        linbvirtCommands.put(AttachIsoCommand.class, new LibvirtAttachIsoCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4d216f1a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 50c8ca6..f122a2a 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -30,6 +30,7 @@ import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -63,13 +64,16 @@ import org.w3c.dom.Document;
 import org.xml.sax.SAXException;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
+import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
@@ -78,6 +82,7 @@ import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
+import com.cloud.exception.InternalErrorException;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtConnectionWrapper;
@@ -88,6 +93,7 @@ import com.cloud.storage.Volume;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 import com.cloud.utils.Pair;
 import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachine.PowerState;
 
 @RunWith(PowerMockRunner.class)
 public class LibvirtComputingResourceTest {
@@ -774,4 +780,194 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
     }
+
+    @Test
+    public void testCheckVirtualMachineCommand() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(libvirtComputingResource.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testExceptionCheckVirtualMachineCommand() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(libvirtComputingResource.getVmState(conn, command.getVmName())).thenReturn(PowerState.PowerOn);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testReadyCommand() {
+        final ReadyCommand command = new ReadyCommand(1l);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testAttachIsoCommand() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testAttachIsoCommandLibvirtException() {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testAttachIsoCommandURISyntaxException() {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(URISyntaxException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testAttachIsoCommandInternalErrorException() {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
 }
\ No newline at end of file


[42/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
rat: add license header to error.jsp

(cherry picked from commit 9c995f1cab259eb88d802887ee6333e164a6c6f8)
Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4b597ca2
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4b597ca2
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4b597ca2

Branch: refs/heads/CLOUDSTACK-8301
Commit: 4b597ca2b99ff693972b6f8601c204c4478bbbf7
Parents: 98a1059
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Mon May 18 23:21:52 2015 +0100
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon May 18 23:22:26 2015 +0100

----------------------------------------------------------------------
 ui/error.jsp | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4b597ca2/ui/error.jsp
----------------------------------------------------------------------
diff --git a/ui/error.jsp b/ui/error.jsp
index 88fdfa1..9fecfb7 100644
--- a/ui/error.jsp
+++ b/ui/error.jsp
@@ -1,3 +1,21 @@
+<%--
+     Licensed to the Apache Software Foundation (ASF) under one
+     or more contributor license agreements.  See the NOTICE file
+     distributed with this work for additional information
+     regarding copyright ownership.  The ASF licenses this file
+     to you under the Apache License, Version 2.0 (the
+     "License"); you may not use this file except in compliance
+     with the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing,
+     software distributed under the License is distributed on an
+     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+     KIND, either express or implied.  See the License for the
+     specific language governing permissions and limitations
+     under the License.
+--%>
 <!doctype html>
 <html>
     <head>


[41/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
ui: add custom error handling page

This makes sure we don't expose CloudStack stacktrace (if any) on the frontend
instead redirect to show an error handling page.

This closes #256

(cherry picked from commit 112cecc2d4e44d032fb57d9794b02fe694122447)
Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/98a10594
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/98a10594
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/98a10594

Branch: refs/heads/CLOUDSTACK-8301
Commit: 98a1059413a20424351b8169003ec6216a2ce3fb
Parents: 0cdb4b6
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Mon May 18 22:09:11 2015 +0100
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon May 18 23:11:59 2015 +0100

----------------------------------------------------------------------
 client/WEB-INF/web.xml |  6 ++++++
 ui/error.jsp           | 12 ++++++++++++
 2 files changed, 18 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/98a10594/client/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/client/WEB-INF/web.xml b/client/WEB-INF/web.xml
index 7ccfc31..a384f06 100644
--- a/client/WEB-INF/web.xml
+++ b/client/WEB-INF/web.xml
@@ -77,4 +77,10 @@
         <url-pattern>*.html</url-pattern>
         <url-pattern>*.js</url-pattern>
     </servlet-mapping>
+
+    <error-page>
+      <exception-type>java.lang.Exception</exception-type>
+      <location>/error.jsp</location>
+    </error-page>
+
 </web-app>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/98a10594/ui/error.jsp
----------------------------------------------------------------------
diff --git a/ui/error.jsp b/ui/error.jsp
new file mode 100644
index 0000000..88fdfa1
--- /dev/null
+++ b/ui/error.jsp
@@ -0,0 +1,12 @@
+<!doctype html>
+<html>
+    <head>
+        <meta charset="utf-8">
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+        <title>Apache CloudStack</title>
+        <link rel="shortcut icon" href="images/cloud.ico" />
+    </head>
+    <body>
+        <p>Oops, looks like CloudStack hit an error. Ask your CloudStack Administrator to look into it.</p>
+    </body>
+</html>


[29/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Fixing testModifySshKeysCommand in the LibvirtComputingResourceTest class
  - The test was okay, but when running in an environment where a /root/.ssh/id_rsa existed, it would return true then fail
  - We now mock the calls to methods that return the key paths, instead of relying in the static variables


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f575206a
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f575206a
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f575206a

Branch: refs/heads/CLOUDSTACK-8301
Commit: f575206ad4348fb7fc0fe312a1e797bac23d011b
Parents: b284b84
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri May 8 19:53:03 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Fri May 8 19:53:03 2015 +0200

----------------------------------------------------------------------
 .../LibvirtModifySshKeysCommandWrapper.java     | 27 ++++++++++++--------
 .../wrapper/LibvirtUtilitiesHelper.java         | 13 ++++++++++
 .../resource/LibvirtComputingResourceTest.java  |  7 +++++
 3 files changed, 37 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f575206a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
index d5943c5..1295e7d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
@@ -38,21 +38,28 @@ public final class LibvirtModifySshKeysCommandWrapper extends CommandWrapper<Mod
 
     @Override
     public Answer execute(final ModifySshKeysCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final File sshKeysDir = new File(LibvirtComputingResource.SSHKEYSPATH);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+
+        final String sshkeyspath = libvirtUtilitiesHelper.retrieveSshKeysPath();
+        final String sshpubkeypath = libvirtUtilitiesHelper.retrieveSshPubKeyPath();
+        final String sshprvkeypath = libvirtUtilitiesHelper.retrieveSshPrvKeyPath();
+
+        final File sshKeysDir = new File(sshkeyspath);
         String result = null;
         if (!sshKeysDir.exists()) {
             // Change permissions for the 700
             final Script script = new Script("mkdir", libvirtComputingResource.getTimeout(), s_logger);
             script.add("-m", "700");
-            script.add(LibvirtComputingResource.SSHKEYSPATH);
+            script.add(sshkeyspath);
             script.execute();
 
             if (!sshKeysDir.exists()) {
-                s_logger.debug("failed to create directory " + LibvirtComputingResource.SSHKEYSPATH);
+                s_logger.debug("failed to create directory " + sshkeyspath);
             }
         }
 
-        final File pubKeyFile = new File(LibvirtComputingResource.SSHPUBKEYPATH);
+        final File pubKeyFile = new File(sshpubkeypath);
         if (!pubKeyFile.exists()) {
             try {
                 pubKeyFile.createNewFile();
@@ -66,16 +73,16 @@ public final class LibvirtModifySshKeysCommandWrapper extends CommandWrapper<Mod
             try (FileOutputStream pubkStream = new FileOutputStream(pubKeyFile)) {
                 pubkStream.write(command.getPubKey().getBytes());
             } catch (final FileNotFoundException e) {
-                result = "File" + LibvirtComputingResource.SSHPUBKEYPATH + "is not found:"
+                result = "File" + sshpubkeypath + "is not found:"
                         + e.toString();
                 s_logger.debug(result);
             } catch (final IOException e) {
-                result = "Write file " + LibvirtComputingResource.SSHPUBKEYPATH + ":" + e.toString();
+                result = "Write file " + sshpubkeypath + ":" + e.toString();
                 s_logger.debug(result);
             }
         }
 
-        final File prvKeyFile = new File(LibvirtComputingResource.SSHPRVKEYPATH);
+        final File prvKeyFile = new File(sshprvkeypath);
         if (!prvKeyFile.exists()) {
             try {
                 prvKeyFile.createNewFile();
@@ -92,14 +99,14 @@ public final class LibvirtModifySshKeysCommandWrapper extends CommandWrapper<Mod
                     prvKStream.write(prvKey.getBytes());
                 }
             } catch (final FileNotFoundException e) {
-                result = "File" + LibvirtComputingResource.SSHPRVKEYPATH + "is not found:" + e.toString();
+                result = "File" + sshprvkeypath + "is not found:" + e.toString();
                 s_logger.debug(result);
             } catch (final IOException e) {
-                result = "Write file " + LibvirtComputingResource.SSHPRVKEYPATH + ":" + e.toString();
+                result = "Write file " + sshprvkeypath + ":" + e.toString();
                 s_logger.debug(result);
             }
             final Script script = new Script("chmod", libvirtComputingResource.getTimeout(), s_logger);
-            script.add("600", LibvirtComputingResource.SSHPRVKEYPATH);
+            script.add("600", sshprvkeypath);
             script.execute();
         }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f575206a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
index 74a41c6..dfff12d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -25,6 +25,7 @@ import javax.naming.ConfigurationException;
 import org.libvirt.Connect;
 import org.libvirt.LibvirtException;
 
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
 import com.cloud.storage.StorageLayer;
 import com.cloud.storage.template.Processor;
@@ -69,4 +70,16 @@ public class LibvirtUtilitiesHelper {
     public Connect getConnectionByType(final String hvsType) throws LibvirtException {
         return LibvirtConnection.getConnectionByType(hvsType);
     }
+
+    public String retrieveSshKeysPath() {
+        return LibvirtComputingResource.SSHKEYSPATH;
+    }
+
+    public String retrieveSshPubKeyPath() {
+        return LibvirtComputingResource.SSHPUBKEYPATH;
+    }
+
+    public String retrieveSshPrvKeyPath() {
+        return LibvirtComputingResource.SSHPRVKEYPATH;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f575206a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 4a1dcc4..36227a5 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -1711,6 +1711,13 @@ public class LibvirtComputingResourceTest {
     public void testModifySshKeysCommand() {
         final ModifySshKeysCommand command = new ModifySshKeysCommand("", "");
 
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+
+        when(libvirtUtilitiesHelper.retrieveSshKeysPath()).thenReturn("/path/keys");
+        when(libvirtUtilitiesHelper.retrieveSshPubKeyPath()).thenReturn("/path/pub/keys");
+        when(libvirtUtilitiesHelper.retrieveSshPrvKeyPath()).thenReturn("/path/pvt/keys");
+
         when(libvirtComputingResource.getTimeout()).thenReturn(0);
 
         final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();


[06/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCreateCommandWrapper and LibvirtMaintainCommandWrapper
  - 4 unit tests added
  - KVM hypervisor plugin with 12.7% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/cb467027
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/cb467027
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/cb467027

Branch: refs/heads/CLOUDSTACK-8301
Commit: cb4670279f764e1747f6eaaf1e39b1516cce6a5d
Parents: 6f757c6
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed Apr 29 16:05:44 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:10 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  12 +--
 .../wrapper/LibvirtCreateCommandWrapper.java    |  83 +++++++++++++++
 .../wrapper/LibvirtMaintainCommandWrapper.java  |  34 +++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   4 +
 .../resource/LibvirtComputingResourceTest.java  | 102 +++++++++++++++++++
 5 files changed, 225 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cb467027/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 62c7148..3c959ef 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -101,8 +101,6 @@ import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.GetStorageStatsAnswer;
 import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
-import com.cloud.agent.api.MaintainAnswer;
-import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
 import com.cloud.agent.api.ModifyStoragePoolAnswer;
@@ -1305,9 +1303,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof MaintainCommand) {
-                return execute((MaintainCommand)cmd);
-            } else if (cmd instanceof CreateCommand) {
+            if (cmd instanceof CreateCommand) {
                 return execute((CreateCommand)cmd);
             } else if (cmd instanceof DestroyCommand) {
                 return execute((DestroyCommand)cmd);
@@ -1769,7 +1765,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     }
 
     // this is much like PrimaryStorageDownloadCommand, but keeping it separate
-    protected KVMPhysicalDisk templateToPrimaryDownload(final String templateUrl, final KVMStoragePool primaryPool, final String volUuid) {
+    public KVMPhysicalDisk templateToPrimaryDownload(final String templateUrl, final KVMStoragePool primaryPool, final String volUuid) {
         final int index = templateUrl.lastIndexOf("/");
         final String mountpoint = templateUrl.substring(0, index);
         String templateName = null;
@@ -2866,10 +2862,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new Answer(cmd, result, "");
     }
 
-    protected MaintainAnswer execute(final MaintainCommand cmd) {
-        return new MaintainAnswer(cmd);
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cb467027/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateCommandWrapper.java
new file mode 100644
index 0000000..f169e72
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateCommandWrapper.java
@@ -0,0 +1,83 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.CreateAnswer;
+import com.cloud.agent.api.storage.CreateCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.agent.api.to.VolumeTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.DiskProfile;
+
+public final class LibvirtCreateCommandWrapper extends CommandWrapper<CreateCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtCreateCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CreateCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final StorageFilerTO pool = command.getPool();
+        final DiskProfile dskch = command.getDiskCharacteristics();
+        KVMPhysicalDisk baseVol = null;
+        KVMStoragePool primaryPool = null;
+        KVMPhysicalDisk vol = null;
+        long disksize;
+        try {
+            final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            primaryPool = storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
+            disksize = dskch.getSize();
+
+            if (command.getTemplateUrl() != null) {
+                if (primaryPool.getType() == StoragePoolType.CLVM) {
+                    vol = libvirtComputingResource.templateToPrimaryDownload(command.getTemplateUrl(), primaryPool, dskch.getPath());
+                } else {
+                    baseVol = primaryPool.getPhysicalDisk(command.getTemplateUrl());
+                    vol = storagePoolMgr.createDiskFromTemplate(baseVol,
+                            dskch.getPath(), dskch.getProvisioningType(), primaryPool, 0);
+                }
+                if (vol == null) {
+                    return new Answer(command, false, " Can't create storage volume on storage pool");
+                }
+            } else {
+                vol = primaryPool.createPhysicalDisk(dskch.getPath(), dskch.getProvisioningType(), dskch.getSize());
+            }
+            final VolumeTO volume =
+                    new VolumeTO(command.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), pool.getPath(), vol.getName(), vol.getName(), disksize, null);
+
+            volume.setBytesReadRate(dskch.getBytesReadRate());
+            volume.setBytesWriteRate(dskch.getBytesWriteRate());
+            volume.setIopsReadRate(dskch.getIopsReadRate());
+            volume.setIopsWriteRate(dskch.getIopsWriteRate());
+            volume.setCacheMode(dskch.getCacheMode());
+            return new CreateAnswer(command, volume);
+        } catch (final CloudRuntimeException e) {
+            s_logger.debug("Failed to create volume: " + e.toString());
+            return new CreateAnswer(command, e);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cb467027/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMaintainCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMaintainCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMaintainCommandWrapper.java
new file mode 100644
index 0000000..c1aba38
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMaintainCommandWrapper.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.MaintainAnswer;
+import com.cloud.agent.api.MaintainCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtMaintainCommandWrapper extends CommandWrapper<MaintainCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final MaintainCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        return new MaintainAnswer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cb467027/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index c5001c4..bced7f8 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -30,6 +30,7 @@ import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
+import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.PingTestCommand;
@@ -40,6 +41,7 @@ import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.RequestWrapper;
@@ -80,6 +82,8 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
         linbvirtCommands.put(GetVncPortCommand.class, new LibvirtGetVncPortCommandWrapper());
         linbvirtCommands.put(ModifySshKeysCommand.class, new LibvirtModifySshKeysCommandWrapper());
+        linbvirtCommands.put(MaintainCommand.class, new LibvirtMaintainCommandWrapper());
+        linbvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/cb467027/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index a2b3b7f..22fa808 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -72,6 +72,7 @@ import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
+import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.PingTestCommand;
@@ -83,8 +84,10 @@ import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
+import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.exception.InternalErrorException;
@@ -100,6 +103,7 @@ import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.Volume;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 import com.cloud.utils.Pair;
+import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
 
@@ -1217,4 +1221,102 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getTimeout();
     }
+
+    @Test
+    public void testMaintainCommand() {
+        final MaintainCommand command = new MaintainCommand();
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testCreateCommandNoTemplate() {
+        final DiskProfile diskCharacteristics = Mockito.mock(DiskProfile.class);
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final boolean executeInSequence = false;
+
+        final CreateCommand command = new CreateCommand(diskCharacteristics, pool, executeInSequence );
+
+        final KVMStoragePoolManager poolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager);
+        when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+
+        when(primary.createPhysicalDisk(diskCharacteristics.getPath(), diskCharacteristics.getProvisioningType(), diskCharacteristics.getSize())).thenReturn(vol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid());
+    }
+
+    @Test
+    public void testCreateCommand() {
+        final DiskProfile diskCharacteristics = Mockito.mock(DiskProfile.class);
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final String templateUrl = "http://template";
+        final boolean executeInSequence = false;
+
+        final CreateCommand command = new CreateCommand(diskCharacteristics, templateUrl, pool, executeInSequence );
+
+        final KVMStoragePoolManager poolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager);
+        when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+
+        when(primary.getType()).thenReturn(StoragePoolType.CLVM);
+        when(libvirtComputingResource.templateToPrimaryDownload(command.getTemplateUrl(), primary, diskCharacteristics.getPath())).thenReturn(vol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid());
+    }
+
+    @Test
+    public void testCreateCommandCLVM() {
+        final DiskProfile diskCharacteristics = Mockito.mock(DiskProfile.class);
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final String templateUrl = "http://template";
+        final boolean executeInSequence = false;
+
+        final CreateCommand command = new CreateCommand(diskCharacteristics, templateUrl, pool, executeInSequence );
+
+        final KVMStoragePoolManager poolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMPhysicalDisk baseVol = Mockito.mock(KVMPhysicalDisk.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager);
+        when(poolManager.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+
+        when(primary.getPhysicalDisk(command.getTemplateUrl())).thenReturn(baseVol);
+        when(poolManager.createDiskFromTemplate(baseVol,
+                diskCharacteristics.getPath(), diskCharacteristics.getProvisioningType(), primary, 0)).thenReturn(vol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid());
+    }
 }
\ No newline at end of file


[34/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
schema: fix foreign key checks for 3.0.7 to 4.1.0 upgrade path

Without this upgrades from 3.0.7 version fails.

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>
(cherry picked from commit a0cff4ca48bbd2140c35b586d42d997ad5f167b2)
Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/256e227c
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/256e227c
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/256e227c

Branch: refs/heads/CLOUDSTACK-8301
Commit: 256e227cd5be63186a989e2c99ded0da5e7dea71
Parents: b1f2e59
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Wed May 13 14:10:14 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Wed May 13 14:11:56 2015 +0200

----------------------------------------------------------------------
 setup/db/db/schema-307to410.sql | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/256e227c/setup/db/db/schema-307to410.sql
----------------------------------------------------------------------
diff --git a/setup/db/db/schema-307to410.sql b/setup/db/db/schema-307to410.sql
index 7feb53e..5624f00 100644
--- a/setup/db/db/schema-307to410.sql
+++ b/setup/db/db/schema-307to410.sql
@@ -20,6 +20,7 @@
 --;
 
 
+SET foreign_key_checks = 0;
 
 -- DB upgrade steps from 302-40 
 CREATE TABLE `cloud`.`external_nicira_nvp_devices` (
@@ -1508,7 +1509,6 @@ CREATE TABLE `cloud`.`ucs_manager` (
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
 
-SET foreign_key_checks = 1;
 
 UPDATE `cloud`.`configuration` SET value='KVM,XenServer,VMware,Ovm' WHERE name='hypervisor.list';
 
@@ -1585,3 +1585,5 @@ ALTER TABLE `cloud_usage`.`cloud_usage` CHANGE COLUMN `virtual_size` `virtual_si
 
 ALTER TABLE `cloud`.`network_offerings` CHANGE COLUMN `concurrent_connections` `concurrent_connections1` int(10) unsigned COMMENT 'Load Balancer(haproxy) maximum number of concurrent connections(global max)';
 ALTER TABLE `cloud`.`volumes` CHANGE COLUMN `iso_id` `iso_id1` bigint(20) unsigned COMMENT 'The id of the iso from which the volume was created';
+
+SET foreign_key_checks = 1;


[11/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtDestroyCommandWrapper
  - 2 unit tests added
  - KVM hypervisor plugin with 12.9% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4472cade
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4472cade
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4472cade

Branch: refs/heads/CLOUDSTACK-8301
Commit: 4472cade2f1c079d96ed738d32c0e046f76c832e
Parents: cb46702
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed Apr 29 17:19:57 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:11 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 62 +-------------------
 .../wrapper/LibvirtDestroyCommandWrapper.java   | 50 ++++++++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  2 +
 .../resource/LibvirtComputingResourceTest.java  | 59 +++++++++++++++++++
 4 files changed, 112 insertions(+), 61 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4472cade/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 3c959ef..4abc048 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -145,10 +145,7 @@ import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
 import com.cloud.agent.api.storage.CopyVolumeAnswer;
 import com.cloud.agent.api.storage.CopyVolumeCommand;
-import com.cloud.agent.api.storage.CreateAnswer;
-import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
-import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
 import com.cloud.agent.api.storage.ResizeVolumeAnswer;
@@ -161,7 +158,6 @@ import com.cloud.agent.api.to.NfsTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
-import com.cloud.agent.api.to.VolumeTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.dc.Vlan;
@@ -225,7 +221,6 @@ import com.cloud.utils.script.OutputInterpreter;
 import com.cloud.utils.script.OutputInterpreter.AllLinesParser;
 import com.cloud.utils.script.Script;
 import com.cloud.utils.ssh.SshHelper;
-import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
 
@@ -1303,11 +1298,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof CreateCommand) {
-                return execute((CreateCommand)cmd);
-            } else if (cmd instanceof DestroyCommand) {
-                return execute((DestroyCommand)cmd);
-            } else if (cmd instanceof PrimaryStorageDownloadCommand) {
+            if (cmd instanceof PrimaryStorageDownloadCommand) {
                 return execute((PrimaryStorageDownloadCommand)cmd);
             } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
                 return execute((CreatePrivateTemplateFromVolumeCommand)cmd);
@@ -1725,45 +1716,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return Storage.StorageResourceType.STORAGE_POOL;
     }
 
-    protected Answer execute(final CreateCommand cmd) {
-        final StorageFilerTO pool = cmd.getPool();
-        final DiskProfile dskch = cmd.getDiskCharacteristics();
-        KVMPhysicalDisk BaseVol = null;
-        KVMStoragePool primaryPool = null;
-        KVMPhysicalDisk vol = null;
-        long disksize;
-        try {
-            primaryPool = _storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
-            disksize = dskch.getSize();
-
-            if (cmd.getTemplateUrl() != null) {
-                if (primaryPool.getType() == StoragePoolType.CLVM) {
-                    vol = templateToPrimaryDownload(cmd.getTemplateUrl(), primaryPool, dskch.getPath());
-                } else {
-                    BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl());
-                    vol = _storagePoolMgr.createDiskFromTemplate(BaseVol,
-                            dskch.getPath(), dskch.getProvisioningType(), primaryPool, 0);
-                }
-                if (vol == null) {
-                    return new Answer(cmd, false, " Can't create storage volume on storage pool");
-                }
-            } else {
-                vol = primaryPool.createPhysicalDisk(dskch.getPath(), dskch.getProvisioningType(), dskch.getSize());
-            }
-            final VolumeTO volume =
-                    new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), pool.getPath(), vol.getName(), vol.getName(), disksize, null);
-            volume.setBytesReadRate(dskch.getBytesReadRate());
-            volume.setBytesWriteRate(dskch.getBytesWriteRate());
-            volume.setIopsReadRate(dskch.getIopsReadRate());
-            volume.setIopsWriteRate(dskch.getIopsWriteRate());
-            volume.setCacheMode(dskch.getCacheMode());
-            return new CreateAnswer(cmd, volume);
-        } catch (final CloudRuntimeException e) {
-            s_logger.debug("Failed to create volume: " + e.toString());
-            return new CreateAnswer(cmd, e);
-        }
-    }
-
     // this is much like PrimaryStorageDownloadCommand, but keeping it separate
     public KVMPhysicalDisk templateToPrimaryDownload(final String templateUrl, final KVMStoragePool primaryPool, final String volUuid) {
         final int index = templateUrl.lastIndexOf("/");
@@ -1915,18 +1867,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
     }
 
-    public Answer execute(final DestroyCommand cmd) {
-        final VolumeTO vol = cmd.getVolume();
-        try {
-            final KVMStoragePool pool = _storagePoolMgr.getStoragePool(vol.getPoolType(), vol.getPoolUuid());
-            pool.deletePhysicalDisk(vol.getPath(), null);
-            return new Answer(cmd, true, "Success");
-        } catch (final CloudRuntimeException e) {
-            s_logger.debug("Failed to delete volume: " + e.toString());
-            return new Answer(cmd, false, e.toString());
-        }
-    }
-
     private String getBroadcastUriFromBridge(final String brName) {
         final String pif = matchPifFileInDirectory(brName);
         final Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4472cade/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDestroyCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDestroyCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDestroyCommandWrapper.java
new file mode 100644
index 0000000..d879295
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDestroyCommandWrapper.java
@@ -0,0 +1,50 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.DestroyCommand;
+import com.cloud.agent.api.to.VolumeTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtDestroyCommandWrapper extends CommandWrapper<DestroyCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtDestroyCommandWrapper.class);
+
+    @Override
+    public Answer execute(final DestroyCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final VolumeTO vol = command.getVolume();
+        try {
+            KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            final KVMStoragePool pool = storagePoolMgr.getStoragePool(vol.getPoolType(), vol.getPoolUuid());
+            pool.deletePhysicalDisk(vol.getPath(), null);
+            return new Answer(command, true, "Success");
+        } catch (final CloudRuntimeException e) {
+            s_logger.debug("Failed to delete volume: " + e.toString());
+            return new Answer(command, false, e.toString());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4472cade/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index bced7f8..eb8d569 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -42,6 +42,7 @@ import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
+import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.RequestWrapper;
@@ -84,6 +85,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(ModifySshKeysCommand.class, new LibvirtModifySshKeysCommandWrapper());
         linbvirtCommands.put(MaintainCommand.class, new LibvirtMaintainCommandWrapper());
         linbvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
+        linbvirtCommands.put(DestroyCommand.class, new LibvirtDestroyCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4472cade/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 22fa808..0865fb5 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -85,10 +85,12 @@ import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
+import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
+import com.cloud.agent.api.to.VolumeTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.exception.InternalErrorException;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
@@ -100,9 +102,11 @@ import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.network.Networks.TrafficType;
 import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.storage.StoragePool;
 import com.cloud.storage.Volume;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 import com.cloud.utils.Pair;
+import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
@@ -1319,4 +1323,59 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
         verify(poolManager, times(1)).getStoragePool(pool.getType(), pool.getUuid());
     }
+
+    @Test
+    public void testDestroyCommand() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final Volume volume = Mockito.mock(Volume.class);
+        final String vmName = "Test";
+
+        final DestroyCommand command = new DestroyCommand(pool, volume, vmName);
+
+        final KVMStoragePoolManager poolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final VolumeTO vol = command.getVolume();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager);
+        when(poolManager.getStoragePool(vol.getPoolType(), vol.getPoolUuid())).thenReturn(primary);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(poolManager, times(1)).getStoragePool(vol.getPoolType(), vol.getPoolUuid());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testDestroyCommandError() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final Volume volume = Mockito.mock(Volume.class);
+        final String vmName = "Test";
+
+        final DestroyCommand command = new DestroyCommand(pool, volume, vmName);
+
+        final KVMStoragePoolManager poolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final VolumeTO vol = command.getVolume();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(poolManager);
+        when(poolManager.getStoragePool(vol.getPoolType(), vol.getPoolUuid())).thenReturn(primary);
+
+        when(primary.deletePhysicalDisk(vol.getPath(), null)).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(poolManager, times(1)).getStoragePool(vol.getPoolType(), vol.getPoolUuid());
+    }
 }
\ No newline at end of file


[03/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtGetVncPortCommandWrapper
  - 2 unit tests added
  - KVM hypervisor plugin with 12.1% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f14c7c20
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f14c7c20
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f14c7c20

Branch: refs/heads/CLOUDSTACK-8301
Commit: f14c7c207494c1c01d73713f6a2c4ab5452d07e9
Parents: 7319a12
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri Apr 24 13:17:58 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:20:43 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 16 +-----
 .../LibvirtGetVncPortCommandWrapper.java        | 45 ++++++++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  2 +
 .../resource/LibvirtComputingResourceTest.java  | 57 ++++++++++++++++++++
 4 files changed, 105 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f14c7c20/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 07cb4dd..788a3e4 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -100,8 +100,6 @@ import com.cloud.agent.api.FenceAnswer;
 import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.GetStorageStatsAnswer;
 import com.cloud.agent.api.GetStorageStatsCommand;
-import com.cloud.agent.api.GetVncPortAnswer;
-import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.MaintainAnswer;
 import com.cloud.agent.api.MaintainCommand;
@@ -1300,9 +1298,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof GetVncPortCommand) {
-                return execute((GetVncPortCommand)cmd);
-            } else if (cmd instanceof ModifySshKeysCommand) {
+            if (cmd instanceof ModifySshKeysCommand) {
                 return execute((ModifySshKeysCommand)cmd);
             } else if (cmd instanceof MaintainCommand) {
                 return execute((MaintainCommand)cmd);
@@ -2865,16 +2861,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new Answer(cmd, result, "");
     }
 
-    protected GetVncPortAnswer execute(final GetVncPortCommand cmd) {
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getName());
-            final Integer vncPort = getVncPort(conn, cmd.getName());
-            return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
-        } catch (final LibvirtException e) {
-            return new GetVncPortAnswer(cmd, e.toString());
-        }
-    }
-
     protected MaintainAnswer execute(final MaintainCommand cmd) {
         return new MaintainAnswer(cmd);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f14c7c20/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
new file mode 100644
index 0000000..9b76374
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
@@ -0,0 +1,45 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetVncPortAnswer;
+import com.cloud.agent.api.GetVncPortCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtGetVncPortCommandWrapper extends CommandWrapper<GetVncPortCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final GetVncPortCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getName());
+            final Integer vncPort = libvirtComputingResource.getVncPort(conn, command.getName());
+            return new GetVncPortAnswer(command, libvirtComputingResource.getPrivateIp(), 5900 + vncPort);
+        } catch (final LibvirtException e) {
+            return new GetVncPortAnswer(command, e.toString());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f14c7c20/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 72d3a87..daa5a0c 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -29,6 +29,7 @@ import com.cloud.agent.api.Command;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
+import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
@@ -76,6 +77,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(AttachVolumeCommand.class, new LibvirtAttachVolumeCommandWrapper());
         linbvirtCommands.put(WatchConsoleProxyLoadCommand.class, new LibvirtWatchConsoleProxyLoadCommandWrapper());
         linbvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
+        linbvirtCommands.put(GetVncPortCommand.class, new LibvirtGetVncPortCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f14c7c20/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 8f56ee0..09a9e36 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -71,6 +71,7 @@ import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
+import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
@@ -1144,4 +1145,60 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
     }
+
+    @Test
+    public void testGetVncPortCommand() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testGetVncPortCommandLibvirtException() {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
 }
\ No newline at end of file


[24/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 1504f70..c5c1553 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -480,7 +480,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final StopCommand command = new StopCommand(vmName, false, false);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -494,7 +494,7 @@ public class LibvirtComputingResourceTest {
 
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -511,7 +511,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final StopCommand command = new StopCommand(vmName, false, true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
             when(conn.domainLookupByName(command.getVmName())).thenReturn(domain);
@@ -526,7 +526,7 @@ public class LibvirtComputingResourceTest {
 
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -546,7 +546,7 @@ public class LibvirtComputingResourceTest {
 
         final GetVmStatsCommand command = new GetVmStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -559,7 +559,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -579,7 +579,7 @@ public class LibvirtComputingResourceTest {
 
         final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnection()).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -592,7 +592,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnection();
         } catch (final LibvirtException e) {
@@ -613,7 +613,7 @@ public class LibvirtComputingResourceTest {
 
         final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnection()).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -626,7 +626,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnection();
         } catch (final LibvirtException e) {
@@ -642,7 +642,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final RebootCommand command = new RebootCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -655,7 +655,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -673,7 +673,7 @@ public class LibvirtComputingResourceTest {
         final RebootRouterCommand command = new RebootRouterCommand(vmName, "192.168.0.10");
 
         when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource);
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -688,7 +688,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getVirtRouterResource();
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -706,7 +706,7 @@ public class LibvirtComputingResourceTest {
         final RebootRouterCommand command = new RebootRouterCommand(vmName, "192.168.0.10");
 
         when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource);
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(routingResource.connect(command.getPrivateIpAddress())).thenReturn(true);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
@@ -721,7 +721,7 @@ public class LibvirtComputingResourceTest {
         assertTrue(answer.getResult());
 
         verify(libvirtComputingResource, times(1)).getVirtRouterResource();
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -768,7 +768,7 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -790,7 +790,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
@@ -816,7 +816,7 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -839,7 +839,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
@@ -864,7 +864,7 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -883,7 +883,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
@@ -908,7 +908,7 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -937,7 +937,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
@@ -963,7 +963,7 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -989,7 +989,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
@@ -1017,7 +1017,7 @@ public class LibvirtComputingResourceTest {
 
         final MigrateCommand command = new MigrateCommand(vmName, destIp, isWindows, vmTO, executeInSequence );
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -1056,7 +1056,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1114,7 +1114,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -1129,7 +1129,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1146,7 +1146,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -1161,7 +1161,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1188,7 +1188,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -1201,7 +1201,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1217,7 +1217,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -1230,7 +1230,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1246,7 +1246,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(URISyntaxException.class);
         } catch (final LibvirtException e) {
@@ -1259,7 +1259,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1275,7 +1275,7 @@ public class LibvirtComputingResourceTest {
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
         } catch (final LibvirtException e) {
@@ -1288,7 +1288,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1316,7 +1316,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -1333,7 +1333,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1361,7 +1361,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -1378,7 +1378,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1406,7 +1406,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
         } catch (final LibvirtException e) {
@@ -1423,7 +1423,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
@@ -1471,7 +1471,7 @@ public class LibvirtComputingResourceTest {
 
         final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -1484,7 +1484,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName());
         } catch (final LibvirtException e) {
@@ -1499,7 +1499,7 @@ public class LibvirtComputingResourceTest {
 
         final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -1512,7 +1512,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName());
         } catch (final LibvirtException e) {
@@ -2245,7 +2245,7 @@ public class LibvirtComputingResourceTest {
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -2264,7 +2264,7 @@ public class LibvirtComputingResourceTest {
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         verify(libvirtComputingResource, times(1)).configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction());
     }
 
@@ -2280,7 +2280,7 @@ public class LibvirtComputingResourceTest {
 
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -2297,7 +2297,7 @@ public class LibvirtComputingResourceTest {
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
     }
 
     @Test
@@ -2310,7 +2310,7 @@ public class LibvirtComputingResourceTest {
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
@@ -2329,7 +2329,7 @@ public class LibvirtComputingResourceTest {
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         verify(libvirtComputingResource, times(1)).configureDefaultNetworkRulesForSystemVm(conn, command.getVmName());
     }
 
@@ -2343,7 +2343,7 @@ public class LibvirtComputingResourceTest {
 
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
@@ -2361,7 +2361,7 @@ public class LibvirtComputingResourceTest {
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
     }
 
     @Test
@@ -2806,7 +2806,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
@@ -2830,7 +2830,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -2858,7 +2858,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
@@ -2891,7 +2891,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -2920,7 +2920,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
@@ -2934,7 +2934,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -2958,7 +2958,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -2980,7 +2980,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
@@ -3007,7 +3007,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3040,7 +3040,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
@@ -3064,7 +3064,7 @@ public class LibvirtComputingResourceTest {
 
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
@@ -3078,7 +3078,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -3104,7 +3104,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3133,7 +3133,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
@@ -3166,7 +3166,7 @@ public class LibvirtComputingResourceTest {
         final List<VifDriver> drivers = new ArrayList<VifDriver>();
         drivers.add(vifDriver);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3198,7 +3198,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
@@ -3225,7 +3225,7 @@ public class LibvirtComputingResourceTest {
         final List<VifDriver> drivers = new ArrayList<VifDriver>();
         drivers.add(vifDriver);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         try {
@@ -3241,7 +3241,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
@@ -3260,7 +3260,7 @@ public class LibvirtComputingResourceTest {
 
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
@@ -3274,7 +3274,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -3471,7 +3471,7 @@ public class LibvirtComputingResourceTest {
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         //final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
@@ -3485,7 +3485,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -3522,7 +3522,7 @@ public class LibvirtComputingResourceTest {
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         //final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
@@ -3536,7 +3536,7 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
 
-        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
         try {
             verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
@@ -3593,9 +3593,9 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(tmplName);
 
         try {
             when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
@@ -3667,9 +3667,9 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(tmplName);
 
         try {
             when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenThrow(ConfigurationException.class);
@@ -3740,9 +3740,9 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(tmplName);
 
         try {
             when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
@@ -3814,9 +3814,9 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(tmplName);
 
         try {
             when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
@@ -3873,8 +3873,8 @@ public class LibvirtComputingResourceTest {
         final int index = snapshotPath.lastIndexOf("/");
         snapshotPath = snapshotPath.substring(0, index);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
-        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(tmplName);
 
         when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
         when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);


[13/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding 4 new command wrappers
  - 12 unit tests added
  - KVM hypervisor plugin with 15.5% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6748a73b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6748a73b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6748a73b

Branch: refs/heads/CLOUDSTACK-8301
Commit: 6748a73b82bb7d1d45fdde1cbcc02f78b8f7b330
Parents: 5499eec
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri May 1 16:17:09 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:12 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 108 +-----
 .../LibvirtCheckNetworkCommandWrapper.java      |  57 ++++
 .../wrapper/LibvirtCheckSshCommandWrapper.java  |  56 +++
 ...bvirtNetworkRulesSystemVmCommandWrapper.java |  49 +++
 .../LibvirtOvsDestroyTunnelCommandWrapper.java  |  58 ++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   8 +
 .../resource/LibvirtComputingResourceTest.java  | 337 ++++++++++++++++++-
 7 files changed, 573 insertions(+), 100 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 75c9663..9c1a6b4 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -85,8 +85,6 @@ import com.ceph.rbd.RbdImage;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.BackupSnapshotAnswer;
 import com.cloud.agent.api.BackupSnapshotCommand;
-import com.cloud.agent.api.CheckNetworkAnswer;
-import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
@@ -98,12 +96,10 @@ import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
-import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkUsageAnswer;
 import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.OvsCreateTunnelAnswer;
 import com.cloud.agent.api.OvsCreateTunnelCommand;
-import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
@@ -122,8 +118,6 @@ import com.cloud.agent.api.UnPlugNicAnswer;
 import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.VmDiskStatsEntry;
 import com.cloud.agent.api.VmStatsEntry;
-import com.cloud.agent.api.check.CheckSshAnswer;
-import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
@@ -178,7 +172,6 @@ import com.cloud.network.Networks.BroadcastDomainType;
 import com.cloud.network.Networks.IsolationType;
 import com.cloud.network.Networks.RouterPrivateIpStrategy;
 import com.cloud.network.Networks.TrafficType;
-import com.cloud.network.PhysicalNetworkSetupInfo;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.ServerResourceBase;
 import com.cloud.storage.JavaStorageLayer;
@@ -1161,7 +1154,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return "";
     }
 
-    private boolean checkNetwork(final String networkName) {
+    public boolean checkNetwork(final String networkName) {
         if (networkName == null) {
             return true;
         }
@@ -1306,18 +1299,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((UnPlugNicCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
-            } else if (cmd instanceof CheckSshCommand) {
-                return execute((CheckSshCommand)cmd);
             } else if (cmd instanceof NetworkUsageCommand) {
                 return execute((NetworkUsageCommand)cmd);
-            } else if (cmd instanceof NetworkRulesSystemVmCommand) {
-                return execute((NetworkRulesSystemVmCommand)cmd);
             } else if (cmd instanceof CopyVolumeCommand) {
                 return execute((CopyVolumeCommand)cmd);
             } else if (cmd instanceof ResizeVolumeCommand) {
                 return execute((ResizeVolumeCommand)cmd);
-            } else if (cmd instanceof CheckNetworkCommand) {
-                return execute((CheckNetworkCommand)cmd);
             } else if (cmd instanceof StorageSubSystemCommand) {
                 return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
             } else if (cmd instanceof PvlanSetupCommand) {
@@ -1326,8 +1313,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((CheckOnHostCommand)cmd);
             } else if (cmd instanceof OvsCreateTunnelCommand) {
                 return execute((OvsCreateTunnelCommand)cmd);
-            } else if (cmd instanceof OvsDestroyTunnelCommand) {
-                return execute((OvsDestroyTunnelCommand)cmd);
             } else {
                 s_logger.warn("Unsupported command ");
                 return Answer.createUnsupportedCommandAnswer(cmd);
@@ -1367,6 +1352,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             s_logger.debug("### KVM network for tunnels created:" + nwName);
         } catch (final Exception e) {
             s_logger.warn("createTunnelNetwork failed", e);
+            return false;
         }
         return true;
     }
@@ -1374,7 +1360,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     public synchronized boolean configureTunnelNetwork(final long networkId,
             final long hostId, final String nwName) {
         try {
-            findOrCreateTunnelNetwork(nwName);
+            final boolean findResult = findOrCreateTunnelNetwork(nwName);
+            if (!findResult) {
+                s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel.");
+                return false;
+            }
             final String configuredHosts = Script
                     .runSimpleBashScript("ovs-vsctl get bridge " + nwName
                             + " other_config:ovs-host-setup");
@@ -1441,53 +1431,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final OvsDestroyTunnelCommand cmd) {
-        try {
-            if (!findOrCreateTunnelNetwork(cmd.getBridgeName())) {
-                s_logger.warn("Unable to find tunnel network for GRE key:"
-                        + cmd.getBridgeName());
-                return new Answer(cmd, false, "No network found");
-            }
-
-            final Script command = new Script(_ovsTunnelPath, _timeout, s_logger);
-            command.add("destroy_tunnel");
-            command.add("--bridge", cmd.getBridgeName());
-            command.add("--iface_name", cmd.getInPortName());
-            final String result = command.execute();
-            if (result == null) {
-                return new Answer(cmd, true, result);
-            } else {
-                return new Answer(cmd, false, result);
-            }
-        } catch (final Exception e) {
-            s_logger.warn("caught execption when destroy ovs tunnel", e);
-            return new Answer(cmd, false, e.getMessage());
-        }
-    }
-
-    private CheckNetworkAnswer execute(final CheckNetworkCommand cmd) {
-        final List<PhysicalNetworkSetupInfo> phyNics = cmd.getPhysicalNetworkInfoList();
-        String errMsg = null;
-        for (final PhysicalNetworkSetupInfo nic : phyNics) {
-            if (!checkNetwork(nic.getGuestNetworkName())) {
-                errMsg = "Can not find network: " + nic.getGuestNetworkName();
-                break;
-            } else if (!checkNetwork(nic.getPrivateNetworkName())) {
-                errMsg = "Can not find network: " + nic.getPrivateNetworkName();
-                break;
-            } else if (!checkNetwork(nic.getPublicNetworkName())) {
-                errMsg = "Can not find network: " + nic.getPublicNetworkName();
-                break;
-            }
-        }
-
-        if (errMsg != null) {
-            return new CheckNetworkAnswer(cmd, false, errMsg);
-        } else {
-            return new CheckNetworkAnswer(cmd, true, null);
-        }
-    }
-
     private CopyVolumeAnswer execute(final CopyVolumeCommand cmd) {
         /**
              This method is only used for copying files from Primary Storage TO Secondary Storage
@@ -2957,7 +2900,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
             for (final NicTO nic : nics) {
                 if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
                     if (vmSpec.getType() != VirtualMachine.Type.User) {
-                        default_network_rules_for_systemvm(conn, vmName);
+                        configureDefaultNetworkRulesForSystemVm(conn, vmName);
                         break;
                     } else {
                         final List<String> nicSecIps = nic.getNicSecIps();
@@ -3193,26 +3136,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         vm.getDevices().addDevice(getVifDriver(nic.getType()).plug(nic, vm.getPlatformEmulator().toString(), nicAdapter).toString());
     }
 
-    protected CheckSshAnswer execute(final CheckSshCommand cmd) {
-        final String vmName = cmd.getName();
-        final String privateIp = cmd.getIp();
-        final int cmdPort = cmd.getPort();
-
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
-        }
-
-        if (!_virtRouterResource.connect(privateIp, cmdPort)) {
-            return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + " because of a connection failure");
-        }
-
-        if (s_logger.isDebugEnabled()) {
-            s_logger.debug("Ping command port succeeded for vm " + vmName);
-        }
-
-        return new CheckSshAnswer(cmd);
-    }
-
     public boolean cleanupDisk(final DiskDef disk) {
         final String path = disk.getDiskPath();
 
@@ -4240,7 +4163,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    protected boolean default_network_rules_for_systemvm(final Connect conn, final String vmName) {
+    public boolean configureDefaultNetworkRulesForSystemVm(final Connect conn, final String vmName) {
         if (!_canBridgeFirewall) {
             return false;
         }
@@ -4371,19 +4294,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final NetworkRulesSystemVmCommand cmd) {
-        boolean success = false;
-        Connect conn;
-        try {
-            conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
-            success = default_network_rules_for_systemvm(conn, cmd.getVmName());
-        } catch (final LibvirtException e) {
-            s_logger.trace("Ignoring libvirt error.", e);
-        }
-
-        return new Answer(cmd, success, "");
-    }
-
     private String prettyVersion(final long version) {
         final long major = version / 1000000;
         final long minor = version % 1000000 / 1000;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckNetworkCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckNetworkCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckNetworkCommandWrapper.java
new file mode 100644
index 0000000..4cf012d
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckNetworkCommandWrapper.java
@@ -0,0 +1,57 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CheckNetworkAnswer;
+import com.cloud.agent.api.CheckNetworkCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.network.PhysicalNetworkSetupInfo;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtCheckNetworkCommandWrapper extends CommandWrapper<CheckNetworkCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CheckNetworkCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final List<PhysicalNetworkSetupInfo> phyNics = command.getPhysicalNetworkInfoList();
+        String errMsg = null;
+
+        for (final PhysicalNetworkSetupInfo nic : phyNics) {
+            if (!libvirtComputingResource.checkNetwork(nic.getGuestNetworkName())) {
+                errMsg = "Can not find network: " + nic.getGuestNetworkName();
+                break;
+            } else if (!libvirtComputingResource.checkNetwork(nic.getPrivateNetworkName())) {
+                errMsg = "Can not find network: " + nic.getPrivateNetworkName();
+                break;
+            } else if (!libvirtComputingResource.checkNetwork(nic.getPublicNetworkName())) {
+                errMsg = "Can not find network: " + nic.getPublicNetworkName();
+                break;
+            }
+        }
+
+        if (errMsg != null) {
+            return new CheckNetworkAnswer(command, false, errMsg);
+        } else {
+            return new CheckNetworkAnswer(command, true, null);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckSshCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckSshCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckSshCommandWrapper.java
new file mode 100644
index 0000000..d258d6d
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckSshCommandWrapper.java
@@ -0,0 +1,56 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.check.CheckSshAnswer;
+import com.cloud.agent.api.check.CheckSshCommand;
+import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtCheckSshCommandWrapper extends CommandWrapper<CheckSshCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CheckSshCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String vmName = command.getName();
+        final String privateIp = command.getIp();
+        final int cmdPort = command.getPort();
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort);
+        }
+
+        final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
+        if (!virtRouterResource.connect(privateIp, cmdPort)) {
+            return new CheckSshAnswer(command, "Can not ping System vm " + vmName + " because of a connection failure");
+        }
+
+        if (s_logger.isDebugEnabled()) {
+            s_logger.debug("Ping command port succeeded for vm " + vmName);
+        }
+
+        return new CheckSshAnswer(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
new file mode 100644
index 0000000..b8ef8a8
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
@@ -0,0 +1,49 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.NetworkRulesSystemVmCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtNetworkRulesSystemVmCommandWrapper extends CommandWrapper<NetworkRulesSystemVmCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.class);
+
+    @Override
+    public Answer execute(final NetworkRulesSystemVmCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        boolean success = false;
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.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, "");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyTunnelCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyTunnelCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyTunnelCommandWrapper.java
new file mode 100644
index 0000000..ca694f8
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyTunnelCommandWrapper.java
@@ -0,0 +1,58 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsDestroyTunnelCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtOvsDestroyTunnelCommandWrapper extends CommandWrapper<OvsDestroyTunnelCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsDestroyTunnelCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsDestroyTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            if (!libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())) {
+                s_logger.warn("Unable to find tunnel network for GRE key:"
+                        + command.getBridgeName());
+                return new Answer(command, false, "No network found");
+            }
+
+            final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger);
+            scriptCommand.add("destroy_tunnel");
+            scriptCommand.add("--bridge", command.getBridgeName());
+            scriptCommand.add("--iface_name", command.getInPortName());
+            final String result = scriptCommand.execute();
+            if (result == null) {
+                return new Answer(command, true, result);
+            } else {
+                return new Answer(command, false, result);
+            }
+        } catch (final Exception e) {
+            s_logger.warn("caught execption when destroy ovs tunnel", e);
+            return new Answer(command, false, e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 87b4ec2..ca7a7d2 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -24,6 +24,7 @@ import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
@@ -38,8 +39,10 @@ import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
+import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.OvsFetchInterfaceCommand;
 import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
@@ -51,6 +54,7 @@ import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
+import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
@@ -112,6 +116,10 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(ModifyStoragePoolCommand.class, new LibvirtModifyStoragePoolCommandWrapper());
         linbvirtCommands.put(CleanupNetworkRulesCmd.class, new LibvirtCleanupNetworkRulesCommandWrapper());
         linbvirtCommands.put(NetworkRulesVmSecondaryIpCommand.class, new LibvirtNetworkRulesVmSecondaryIpCommandWrapper());
+        linbvirtCommands.put(NetworkRulesSystemVmCommand.class, new LibvirtNetworkRulesSystemVmCommandWrapper());
+        linbvirtCommands.put(CheckSshCommand.class, new LibvirtCheckSshCommandWrapper());
+        linbvirtCommands.put(CheckNetworkCommand.class, new LibvirtCheckNetworkCommandWrapper());
+        linbvirtCommands.put(OvsDestroyTunnelCommand.class, new LibvirtOvsDestroyTunnelCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6748a73b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 8fd1ecf..1551f98 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -67,6 +67,7 @@ import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
+import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.CreateStoragePoolCommand;
@@ -80,8 +81,10 @@ import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
+import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.OvsFetchInterfaceCommand;
 import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
@@ -98,6 +101,7 @@ import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmStatsEntry;
+import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
@@ -119,6 +123,7 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.PhysicalNetworkSetupInfo;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StoragePool;
@@ -129,6 +134,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.vm.DiskProfile;
 import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachine.PowerState;
+import com.cloud.vm.VirtualMachine.Type;
 
 @RunWith(PowerMockRunner.class)
 public class LibvirtComputingResourceTest {
@@ -1944,7 +1950,7 @@ public class LibvirtComputingResourceTest {
     }
 
     @Test
-    public void testOvsSetupBridgeCommandFailure() {
+    public void testOvsSetupBridgeCommandFailure1() {
         final String name = "Test";
         final Long hostId = 1l;
         final Long networkId = 1l;
@@ -1968,6 +1974,30 @@ public class LibvirtComputingResourceTest {
     }
 
     @Test
+    public void testOvsSetupBridgeCommandFailure2() {
+        final String name = "Test";
+        final Long hostId = 1l;
+        final Long networkId = 1l;
+
+        final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName())).thenReturn(true);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+        verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName());
+    }
+
+    @Test
     public void testOvsDestroyBridgeCommand() {
         final String name = "Test";
         final Long hostId = 1l;
@@ -2043,6 +2073,27 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getTimeout();
     }
 
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testOvsVpcPhysicalTopologyConfigCommandFailure() {
+        final Host[] hosts = null;
+        final Tier[] tiers = null;
+        final Vm[] vms = null;
+        final String cidr = null;
+
+        final OvsVpcPhysicalTopologyConfigCommand command = new OvsVpcPhysicalTopologyConfigCommand(hosts, tiers, vms, cidr);
+
+        when(libvirtComputingResource.getOvsTunnelPath()).thenThrow(Exception.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getOvsTunnelPath();
+    }
+
     @Test
     public void testOvsVpcRoutingPolicyConfigCommand() {
         final String id = null;
@@ -2066,6 +2117,27 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getTimeout();
     }
 
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testOvsVpcRoutingPolicyConfigCommandFailure() {
+        final String id = null;
+        final String cidr = null;
+        final Acl[] acls = null;
+        final com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand.Tier[] tiers = null;
+
+        final OvsVpcRoutingPolicyConfigCommand command = new OvsVpcRoutingPolicyConfigCommand(id, cidr, acls, tiers);
+
+        when(libvirtComputingResource.getOvsTunnelPath()).thenThrow(Exception.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getOvsTunnelPath();
+    }
+
     @Test
     public void testCreateStoragePoolCommand() {
         final StoragePool pool = Mockito.mock(StoragePool.class);
@@ -2207,4 +2279,267 @@ public class LibvirtComputingResourceTest {
         }
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
     }
+
+    @Test
+    public void testNetworkRulesSystemVmCommand() {
+        final String vmName = "Test";
+        final Type type = Type.SecondaryStorageVm;
+
+        final NetworkRulesSystemVmCommand command = new NetworkRulesSystemVmCommand(vmName, type);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        when(libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).configureDefaultNetworkRulesForSystemVm(conn, command.getVmName());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testNetworkRulesSystemVmCommandFailure() {
+        final String vmName = "Test";
+        final Type type = Type.SecondaryStorageVm;
+
+        final NetworkRulesSystemVmCommand command = new NetworkRulesSystemVmCommand(vmName, type);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+    }
+
+    @Test
+    public void testCheckSshCommand() {
+        final String instanceName = "Test";
+        final String ip = "172.16.16.16";
+        final int port = 22;
+
+        final CheckSshCommand command = new CheckSshCommand(instanceName, ip, port);
+
+        final VirtualRoutingResource virtRouterResource = Mockito.mock(VirtualRoutingResource.class);
+
+        final String privateIp = command.getIp();
+        final int cmdPort = command.getPort();
+
+        when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
+        when(virtRouterResource.connect(privateIp, cmdPort)).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getVirtRouterResource();
+        verify(virtRouterResource, times(1)).connect(privateIp, cmdPort);
+    }
+
+    @Test
+    public void testCheckSshCommandFailure() {
+        final String instanceName = "Test";
+        final String ip = "172.16.16.16";
+        final int port = 22;
+
+        final CheckSshCommand command = new CheckSshCommand(instanceName, ip, port);
+
+        final VirtualRoutingResource virtRouterResource = Mockito.mock(VirtualRoutingResource.class);
+
+        final String privateIp = command.getIp();
+        final int cmdPort = command.getPort();
+
+        when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
+        when(virtRouterResource.connect(privateIp, cmdPort)).thenReturn(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getVirtRouterResource();
+        verify(virtRouterResource, times(1)).connect(privateIp, cmdPort);
+    }
+
+    @Test
+    public void testCheckNetworkCommand() {
+        final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<PhysicalNetworkSetupInfo>();
+
+        final PhysicalNetworkSetupInfo nic = Mockito.mock(PhysicalNetworkSetupInfo.class);
+        networkInfoList.add(nic);
+
+        final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList);
+
+        when(libvirtComputingResource.checkNetwork(nic.getGuestNetworkName())).thenReturn(true);
+        when(libvirtComputingResource.checkNetwork(nic.getPrivateNetworkName())).thenReturn(true);
+        when(libvirtComputingResource.checkNetwork(nic.getPublicNetworkName())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(3)).checkNetwork(nic.getGuestNetworkName());
+        verify(libvirtComputingResource, times(3)).checkNetwork(nic.getPrivateNetworkName());
+        verify(libvirtComputingResource, times(3)).checkNetwork(nic.getPublicNetworkName());
+    }
+
+    @Test
+    public void testCheckNetworkCommandFail1() {
+        final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<PhysicalNetworkSetupInfo>();
+
+        final PhysicalNetworkSetupInfo networkSetupInfo = Mockito.mock(PhysicalNetworkSetupInfo.class);
+        networkInfoList.add(networkSetupInfo);
+
+        final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList);
+
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getGuestNetworkName())).thenReturn(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).checkNetwork(networkSetupInfo.getGuestNetworkName());
+    }
+
+    @Test
+    public void testCheckNetworkCommandFail2() {
+        final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<PhysicalNetworkSetupInfo>();
+
+        final PhysicalNetworkSetupInfo networkSetupInfo = Mockito.mock(PhysicalNetworkSetupInfo.class);
+        networkInfoList.add(networkSetupInfo);
+
+        final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList);
+
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getGuestNetworkName())).thenReturn(true);
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getPrivateNetworkName())).thenReturn(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).checkNetwork(networkSetupInfo.getGuestNetworkName());
+        verify(libvirtComputingResource, times(1)).checkNetwork(networkSetupInfo.getPrivateNetworkName());
+    }
+
+    @Test
+    public void testCheckNetworkCommandFail3() {
+        final List<PhysicalNetworkSetupInfo> networkInfoList = new ArrayList<PhysicalNetworkSetupInfo>();
+
+        final PhysicalNetworkSetupInfo networkSetupInfo = Mockito.mock(PhysicalNetworkSetupInfo.class);
+        networkInfoList.add(networkSetupInfo);
+
+        final CheckNetworkCommand command = new CheckNetworkCommand(networkInfoList);
+
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getGuestNetworkName())).thenReturn(true);
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getPrivateNetworkName())).thenReturn(true);
+        when(libvirtComputingResource.checkNetwork(networkSetupInfo.getPublicNetworkName())).thenReturn(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).checkNetwork(networkSetupInfo.getGuestNetworkName());
+        verify(libvirtComputingResource, times(1)).checkNetwork(networkSetupInfo.getPrivateNetworkName());
+    }
+
+    @Test
+    public void testOvsDestroyTunnelCommand() {
+        final String networkName = "Test";
+        final Long networkId = 1l;
+        final String inPortName = "eth";
+
+        final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+    }
+
+    @Test
+    public void testOvsDestroyTunnelCommandFailure1() {
+        final String networkName = "Test";
+        final Long networkId = 1l;
+        final String inPortName = "eth";
+
+        final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testOvsDestroyTunnelCommandFailure2() {
+        final String networkName = "Test";
+        final Long networkId = 1l;
+        final String inPortName = "eth";
+
+        final OvsDestroyTunnelCommand command = new OvsDestroyTunnelCommand(networkId, networkName, inPortName);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenThrow(Exception.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+    }
 }
\ No newline at end of file


[38/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Systemvm: Disable services that slow down boot

The console-setup service brings a nice font to the console, but why would we want to use it. In most cases it takes a <10 seconds to set it up. When using nested hypervising, I found this takes much longer time that causes tests to time-out. I'd suggest turning off these services. They are not required for the services the systemvm provides.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/95e7673a
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/95e7673a
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/95e7673a

Branch: refs/heads/CLOUDSTACK-8301
Commit: 95e7673a55455736ae736b029197487ba1acfe62
Parents: f678953
Author: Remi Bergsma <gi...@remi.nl>
Authored: Mon May 18 13:38:46 2015 +0200
Committer: Remi Bergsma <gi...@remi.nl>
Committed: Mon May 18 13:44:09 2015 +0200

----------------------------------------------------------------------
 .../definitions/systemvmtemplate/configure_systemvm_services.sh  | 4 ++++
 1 file changed, 4 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/95e7673a/tools/appliance/definitions/systemvmtemplate/configure_systemvm_services.sh
----------------------------------------------------------------------
diff --git a/tools/appliance/definitions/systemvmtemplate/configure_systemvm_services.sh b/tools/appliance/definitions/systemvmtemplate/configure_systemvm_services.sh
index 69612dc..4f65543 100644
--- a/tools/appliance/definitions/systemvmtemplate/configure_systemvm_services.sh
+++ b/tools/appliance/definitions/systemvmtemplate/configure_systemvm_services.sh
@@ -70,6 +70,10 @@ function configure_services() {
 
   chkconfig xl2tpd off
 
+  # Disable services that slow down boot and are not used anyway
+  chkconfig x11-common off
+  chkconfig console-setup off
+
   # Hyperv kvp daemon - 64bit only
   local arch=`dpkg --print-architecture`
   if [ "${arch}" == "amd64" ]; then


[22/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Addin LibvirtPvlanSetupCommandWrapper
  - 6 unit tests added
  - KVM hypervisor plugin with 21% coverage

>From the 6 tests added, 2 were extra tests to increase the coverage of the LibvirtStopCommandWrapper
  - Increased from 35% to 78.7%


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/ae505e7b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/ae505e7b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/ae505e7b

Branch: refs/heads/CLOUDSTACK-8301
Commit: ae505e7befa28c2ab136ff7a3ce0217cb2da1bfe
Parents: 7fd43f3
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 11:38:00 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:15 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  70 +-----
 .../LibvirtPvlanSetupCommandWrapper.java        | 105 +++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../resource/LibvirtComputingResourceTest.java  | 236 ++++++++++++++++++-
 4 files changed, 352 insertions(+), 61 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ae505e7b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 8b74b1c..31a9ed7 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -68,7 +68,6 @@ import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
-import com.cloud.agent.api.PvlanSetupCommand;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.StartAnswer;
 import com.cloud.agent.api.StartCommand;
@@ -397,6 +396,18 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _manageSnapshotPath;
     }
 
+    public String getGuestBridgeName() {
+        return _guestBridgeName;
+    }
+
+    public String getOvsPvlanDhcpHostPath() {
+        return _ovsPvlanDhcpHostPath;
+    }
+
+    public String getOvsPvlanVmPath() {
+        return _ovsPvlanVmPath;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1252,8 +1263,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((ResizeVolumeCommand)cmd);
             } else if (cmd instanceof StorageSubSystemCommand) {
                 return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
-            } else if (cmd instanceof PvlanSetupCommand) {
-                return execute((PvlanSetupCommand)cmd);
             } else {
                 s_logger.warn("Unsupported command ");
                 return Answer.createUnsupportedCommandAnswer(cmd);
@@ -1519,61 +1528,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final PvlanSetupCommand cmd) {
-        final String primaryPvlan = cmd.getPrimary();
-        final String isolatedPvlan = cmd.getIsolated();
-        final String op = cmd.getOp();
-        final String dhcpName = cmd.getDhcpName();
-        final String dhcpMac = cmd.getDhcpMac();
-        final String dhcpIp = cmd.getDhcpIp();
-        final String vmMac = cmd.getVmMac();
-        boolean add = true;
-
-        String opr = "-A";
-        if (op.equals("delete")) {
-            opr = "-D";
-            add = false;
-        }
-
-        String result = null;
-        Connect conn;
-        try {
-            if (cmd.getType() == PvlanSetupCommand.Type.DHCP) {
-                final Script script = new Script(_ovsPvlanDhcpHostPath, _timeout, s_logger);
-                if (add) {
-                    conn = LibvirtConnection.getConnectionByVmName(dhcpName);
-                    final List<InterfaceDef> ifaces = getInterfaces(conn, dhcpName);
-                    final InterfaceDef guestNic = ifaces.get(0);
-                    script.add(opr, "-b", _guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac, "-I",
-                            guestNic.getDevName());
-                } else {
-                    script.add(opr, "-b", _guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac);
-                }
-                result = script.execute();
-                if (result != null) {
-                    s_logger.warn("Failed to program pvlan for dhcp server with mac " + dhcpMac);
-                    return new Answer(cmd, false, result);
-                } else {
-                    s_logger.info("Programmed pvlan for dhcp server with mac " + dhcpMac);
-                }
-            } else if (cmd.getType() == PvlanSetupCommand.Type.VM) {
-                final Script script = new Script(_ovsPvlanVmPath, _timeout, s_logger);
-                script.add(opr, "-b", _guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-v", vmMac);
-                result = script.execute();
-                if (result != null) {
-                    s_logger.warn("Failed to program pvlan for vm with mac " + vmMac);
-                    return new Answer(cmd, false, result);
-                } else {
-                    s_logger.info("Programmed pvlan for vm with mac " + vmMac);
-                }
-            }
-        } catch (final LibvirtException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return new Answer(cmd, true, result);
-    }
-
     private void VifHotPlug(final Connect conn, final String vmName, final String broadcastUri, final String macAddr) throws InternalErrorException, LibvirtException {
         final NicTO nicTO = new NicTO();
         nicTO.setMac(macAddr);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ae505e7b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPvlanSetupCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPvlanSetupCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPvlanSetupCommandWrapper.java
new file mode 100644
index 0000000..7233723
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPvlanSetupCommandWrapper.java
@@ -0,0 +1,105 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.PvlanSetupCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtPvlanSetupCommandWrapper extends CommandWrapper<PvlanSetupCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtPvlanSetupCommandWrapper.class);
+
+    @Override
+    public Answer execute(final PvlanSetupCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String primaryPvlan = command.getPrimary();
+        final String isolatedPvlan = command.getIsolated();
+        final String op = command.getOp();
+        final String dhcpName = command.getDhcpName();
+        final String dhcpMac = command.getDhcpMac();
+        final String dhcpIp = command.getDhcpIp();
+        final String vmMac = command.getVmMac();
+        boolean add = true;
+
+        String opr = "-A";
+        if (op.equals("delete")) {
+            opr = "-D";
+            add = false;
+        }
+
+        String result = null;
+        try {
+            final String guestBridgeName = libvirtComputingResource.getGuestBridgeName();
+            final int timeout = libvirtComputingResource.getTimeout();
+
+            if (command.getType() == PvlanSetupCommand.Type.DHCP) {
+                final String ovsPvlanDhcpHostPath = libvirtComputingResource.getOvsPvlanDhcpHostPath();
+                final Script script = new Script(ovsPvlanDhcpHostPath, timeout, s_logger);
+
+                if (add) {
+                    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+                    final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(dhcpName);
+
+                    final List<InterfaceDef> ifaces = libvirtComputingResource.getInterfaces(conn, dhcpName);
+                    final InterfaceDef guestNic = ifaces.get(0);
+                    script.add(opr, "-b", guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac, "-I",
+                            guestNic.getDevName());
+                } else {
+                    script.add(opr, "-b", guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-n", dhcpName, "-d", dhcpIp, "-m", dhcpMac);
+                }
+
+                result = script.execute();
+
+                if (result != null) {
+                    s_logger.warn("Failed to program pvlan for dhcp server with mac " + dhcpMac);
+                    return new Answer(command, false, result);
+                } else {
+                    s_logger.info("Programmed pvlan for dhcp server with mac " + dhcpMac);
+                }
+            } else if (command.getType() == PvlanSetupCommand.Type.VM) {
+                final String ovsPvlanVmPath = libvirtComputingResource.getOvsPvlanVmPath();
+
+                final Script script = new Script(ovsPvlanVmPath, timeout, s_logger);
+                script.add(opr, "-b", guestBridgeName, "-p", primaryPvlan, "-i", isolatedPvlan, "-v", vmMac);
+                result = script.execute();
+
+                if (result != null) {
+                    s_logger.warn("Failed to program pvlan for vm with mac " + vmMac);
+                    return new Answer(command, false, result);
+                } else {
+                    s_logger.info("Programmed pvlan for vm with mac " + vmMac);
+                }
+            }
+        } catch (final LibvirtException e) {
+            s_logger.error("Error whislt executing OVS Setup command! ==> " + e.getMessage());
+            return new Answer(command, false, e.getMessage());
+        }
+        return new Answer(command, true, result);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ae505e7b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 1ee14a1..c103ef3 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -59,6 +59,7 @@ import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
+import com.cloud.agent.api.PvlanSetupCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
@@ -146,6 +147,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
         linbvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
         linbvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
+        linbvirtCommands.put(PvlanSetupCommand.class, new LibvirtPvlanSetupCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ae505e7b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 86ff007..ad75b53 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -31,6 +31,7 @@ import static org.mockito.Mockito.when;
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
+import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -54,6 +55,7 @@ import org.libvirt.Connect;
 import org.libvirt.Domain;
 import org.libvirt.DomainBlockStats;
 import org.libvirt.DomainInfo;
+import org.libvirt.DomainInfo.DomainState;
 import org.libvirt.DomainInterfaceStats;
 import org.libvirt.LibvirtException;
 import org.libvirt.NodeInfo;
@@ -107,6 +109,7 @@ import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand.Acl;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
+import com.cloud.agent.api.PvlanSetupCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
@@ -504,10 +507,13 @@ public class LibvirtComputingResourceTest {
     }
 
     @Test
-    public void testStopCommandCheck() {
+    public void testStopCommandCheckVmNOTRunning() {
         final Connect conn = Mockito.mock(Connect.class);
         final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
-        final Domain domain = Mockito.mock(Domain.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final DomainInfo info = Mockito.mock(DomainInfo.class);
+        final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_SHUTDOWN;
+        info.state = state;
 
         final String vmName = "Test";
         final StopCommand command = new StopCommand(vmName, false, true);
@@ -515,7 +521,10 @@ public class LibvirtComputingResourceTest {
         when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
         try {
             when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
-            when(conn.domainLookupByName(command.getVmName())).thenReturn(domain);
+            when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
+
+            when(vm.getInfo()).thenReturn(info);
+
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -535,6 +544,83 @@ public class LibvirtComputingResourceTest {
         }
     }
 
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testStopCommandCheckException1() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final DomainInfo info = Mockito.mock(DomainInfo.class);
+        final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
+        info.state = state;
+
+        final String vmName = "Test";
+        final StopCommand command = new StopCommand(vmName, false, true);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+            when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
+
+            when(vm.getInfo()).thenReturn(info);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testStopCommandCheckVmRunning() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final DomainInfo info = Mockito.mock(DomainInfo.class);
+        final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
+        info.state = state;
+
+        final String vmName = "Test";
+        final StopCommand command = new StopCommand(vmName, false, true);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(conn.domainLookupByName(command.getVmName())).thenReturn(vm);
+
+            when(vm.getInfo()).thenReturn(info);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
     @Test
     public void testGetVmStatsCommand() {
         final Connect conn = Mockito.mock(Connect.class);
@@ -4098,4 +4184,148 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
     }
+
+    @Test
+    public void testPvlanSetupCommandDhcpAdd() {
+        final String op = "add";
+        final URI uri = URI.create("http://localhost");
+        final String networkTag = "/105";
+        final String dhcpName = "dhcp";
+        final String dhcpMac = "00:00:00:00";
+        final String dhcpIp = "172.10.10.10";
+
+        final PvlanSetupCommand command = PvlanSetupCommand.createDhcpSetup(op, uri, networkTag, dhcpName, dhcpMac, dhcpIp);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        final String guestBridgeName = "br0";
+        when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName);
+
+        final int timeout = 0;
+        when(libvirtComputingResource.getTimeout()).thenReturn(timeout);
+        final String ovsPvlanDhcpHostPath = "/pvlan";
+        when(libvirtComputingResource.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+
+        final List<InterfaceDef> ifaces = new ArrayList<InterfaceDef>();
+        final InterfaceDef nic = Mockito.mock(InterfaceDef.class);
+        ifaces.add(nic);
+
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(dhcpName)).thenReturn(conn);
+            when(libvirtComputingResource.getInterfaces(conn, dhcpName)).thenReturn(ifaces);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(dhcpName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testPvlanSetupCommandVm() {
+        final String op = "add";
+        final URI uri = URI.create("http://localhost");
+        final String networkTag = "/105";
+        final String vmMac = "00:00:00:00";
+
+        final PvlanSetupCommand command = PvlanSetupCommand.createVmSetup(op, uri, networkTag, vmMac);
+
+        final String guestBridgeName = "br0";
+        when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName);
+        final int timeout = 0;
+        when(libvirtComputingResource.getTimeout()).thenReturn(timeout);
+
+        final String ovsPvlanVmPath = "/pvlan";
+        when(libvirtComputingResource.getOvsPvlanVmPath()).thenReturn(ovsPvlanVmPath);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPvlanSetupCommandDhcpException() {
+        final String op = "add";
+        final URI uri = URI.create("http://localhost");
+        final String networkTag = "/105";
+        final String dhcpName = "dhcp";
+        final String dhcpMac = "00:00:00:00";
+        final String dhcpIp = "172.10.10.10";
+
+        final PvlanSetupCommand command = PvlanSetupCommand.createDhcpSetup(op, uri, networkTag, dhcpName, dhcpMac, dhcpIp);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final String guestBridgeName = "br0";
+        when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName);
+
+        final int timeout = 0;
+        when(libvirtComputingResource.getTimeout()).thenReturn(timeout);
+        final String ovsPvlanDhcpHostPath = "/pvlan";
+        when(libvirtComputingResource.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(dhcpName)).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(dhcpName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testPvlanSetupCommandDhcpDelete() {
+        final String op = "delete";
+        final URI uri = URI.create("http://localhost");
+        final String networkTag = "/105";
+        final String dhcpName = "dhcp";
+        final String dhcpMac = "00:00:00:00";
+        final String dhcpIp = "172.10.10.10";
+
+        final PvlanSetupCommand command = PvlanSetupCommand.createDhcpSetup(op, uri, networkTag, dhcpName, dhcpMac, dhcpIp);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final String guestBridgeName = "br0";
+        when(libvirtComputingResource.getGuestBridgeName()).thenReturn(guestBridgeName);
+
+        final int timeout = 0;
+        when(libvirtComputingResource.getTimeout()).thenReturn(timeout);
+        final String ovsPvlanDhcpHostPath = "/pvlan";
+        when(libvirtComputingResource.getOvsPvlanDhcpHostPath()).thenReturn(ovsPvlanDhcpHostPath);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
 }
\ No newline at end of file


[08/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtOvsDestroyBridgeCommandWrapper, LibvirtOvsSetupBridgeCommandWrapper
  - 4 unit tests added
  - KVM hypervisor plugin with 13.9% coverage

More tests added to cover LibvirtPrepareForMigrationCommandWrapper
  - Coverage of this wrapper broght from 37% to 90.6%
  - 4 new tests added


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/4887ce72
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/4887ce72
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/4887ce72

Branch: refs/heads/CLOUDSTACK-8301
Commit: 4887ce72544c3a9b9f507a916ec0c3a22e6b25f5
Parents: 0d860af
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri May 1 12:04:16 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:11 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  55 +---
 .../LibvirtOvsDestroyBridgeCommandWrapper.java  |  43 +++
 .../LibvirtOvsSetupBridgeCommandWrapper.java    |  47 +++
 ...ibvirtPrepareForMigrationCommandWrapper.java |   6 +-
 .../resource/wrapper/LibvirtRequestWrapper.java |   4 +
 .../resource/LibvirtComputingResourceTest.java  | 287 +++++++++++++++++++
 6 files changed, 400 insertions(+), 42 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index f72fecf..cc73e65 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -108,11 +108,9 @@ import com.cloud.agent.api.NetworkUsageAnswer;
 import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.OvsCreateTunnelAnswer;
 import com.cloud.agent.api.OvsCreateTunnelCommand;
-import com.cloud.agent.api.OvsDestroyBridgeCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.OvsFetchInterfaceAnswer;
 import com.cloud.agent.api.OvsFetchInterfaceCommand;
-import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
 import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingCommand;
@@ -1342,10 +1340,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((CheckOnHostCommand)cmd);
             } else if (cmd instanceof OvsFetchInterfaceCommand) {
                 return execute((OvsFetchInterfaceCommand)cmd);
-            } else if (cmd instanceof OvsSetupBridgeCommand) {
-                return execute((OvsSetupBridgeCommand)cmd);
-            } else if (cmd instanceof OvsDestroyBridgeCommand) {
-                return execute((OvsDestroyBridgeCommand)cmd);
             } else if (cmd instanceof OvsCreateTunnelCommand) {
                 return execute((OvsCreateTunnelCommand)cmd);
             } else if (cmd instanceof OvsDestroyTunnelCommand) {
@@ -1381,20 +1375,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
     }
 
-    private Answer execute(final OvsSetupBridgeCommand cmd) {
-        findOrCreateTunnelNetwork(cmd.getBridgeName());
-        configureTunnelNetwork(cmd.getNetworkId(), cmd.getHostId(),
-                cmd.getBridgeName());
-        s_logger.debug("OVS Bridge configured");
-        return new Answer(cmd, true, null);
-    }
-
-    private Answer execute(final OvsDestroyBridgeCommand cmd) {
-        destroyTunnelNetwork(cmd.getBridgeName());
-        s_logger.debug("OVS Bridge destroyed");
-        return new Answer(cmd, true, null);
-    }
-
     public Answer execute(final OvsVpcPhysicalTopologyConfigCommand cmd) {
 
         final String bridge = cmd.getBridgeName();
@@ -1436,28 +1416,23 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private synchronized void destroyTunnelNetwork(final String bridge) {
-        try {
-            findOrCreateTunnelNetwork(bridge);
-            final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger);
-            cmd.add("destroy_ovs_bridge");
-            cmd.add("--bridge", bridge);
-            final String result = cmd.execute();
-            if (result != null) {
-                // TODO: Should make this error not fatal?
-                // Can Concurrent VM shutdown/migration/reboot events can cause
-                // this method
-                // to be executed on a bridge which has already been removed?
-                throw new CloudRuntimeException("Unable to remove OVS bridge " + bridge);
-            }
-            return;
-        } catch (final Exception e) {
-            s_logger.warn("destroyTunnelNetwork failed:", e);
-            return;
+    public synchronized boolean destroyTunnelNetwork(final String bridge) {
+        findOrCreateTunnelNetwork(bridge);
+
+        final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger);
+        cmd.add("destroy_ovs_bridge");
+        cmd.add("--bridge", bridge);
+
+        final String result = cmd.execute();
+
+        if (result != null) {
+            s_logger.debug("OVS Bridge could not be destroyed due to error ==> " + result);
+            return false;
         }
+        return true;
     }
 
-    private synchronized boolean findOrCreateTunnelNetwork(final String nwName) {
+    public synchronized boolean findOrCreateTunnelNetwork(final String nwName) {
         try {
             if (checkNetwork(nwName)) {
                 return true;
@@ -1475,7 +1450,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private synchronized boolean configureTunnelNetwork(final long networkId,
+    public synchronized boolean configureTunnelNetwork(final long networkId,
             final long hostId, final String nwName) {
         try {
             findOrCreateTunnelNetwork(nwName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyBridgeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyBridgeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyBridgeCommandWrapper.java
new file mode 100644
index 0000000..ab2b9c4
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsDestroyBridgeCommandWrapper.java
@@ -0,0 +1,43 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtOvsDestroyBridgeCommandWrapper extends CommandWrapper<OvsDestroyBridgeCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsDestroyBridgeCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsDestroyBridgeCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final boolean result = libvirtComputingResource.destroyTunnelNetwork(command.getBridgeName());
+
+        if (!result) {
+            s_logger.debug("Error trying to destroy OVS Bridge!");
+        }
+
+        return new Answer(command, result, null);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsSetupBridgeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsSetupBridgeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsSetupBridgeCommandWrapper.java
new file mode 100644
index 0000000..4c979a7
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsSetupBridgeCommandWrapper.java
@@ -0,0 +1,47 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsSetupBridgeCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtOvsSetupBridgeCommandWrapper extends CommandWrapper<OvsSetupBridgeCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsSetupBridgeCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsSetupBridgeCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final boolean findResult = libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName());
+        final boolean configResult = libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName());
+
+        final boolean finalResult = findResult && configResult;
+
+        if (!finalResult) {
+            s_logger.debug("::FAILURE:: OVS Bridge was NOT configured properly!");
+        }
+
+        return new Answer(command, finalResult, null);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
index 921d5b8..108b0d2 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
@@ -33,6 +33,7 @@ import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.exception.InternalErrorException;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.storage.Volume;
 
@@ -51,6 +52,7 @@ public final class LibvirtPrepareForMigrationCommandWrapper extends CommandWrapp
 
         boolean skipDisconnect = false;
 
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
         try {
             final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
@@ -69,7 +71,7 @@ public final class LibvirtPrepareForMigrationCommandWrapper extends CommandWrapp
 
             skipDisconnect = true;
 
-            if (!libvirtComputingResource.getStoragePoolMgr().connectPhysicalDisksViaVmSpec(vm)) {
+            if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vm)) {
                 return new PrepareForMigrationAnswer(command, "failed to connect physical disks to host");
             }
 
@@ -82,7 +84,7 @@ public final class LibvirtPrepareForMigrationCommandWrapper extends CommandWrapp
             return new PrepareForMigrationAnswer(command, e.toString());
         } finally {
             if (!skipDisconnect) {
-                libvirtComputingResource.getStoragePoolMgr().disconnectPhysicalDisksViaVmSpec(vm);
+                storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vm);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 04aa2ea..05dbe2d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -35,6 +35,8 @@ import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
+import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -94,6 +96,8 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(GetStorageStatsCommand.class, new LibvirtGetStorageStatsCommandWrapper());
         linbvirtCommands.put(UpgradeSnapshotCommand.class, new LibvirtUpgradeSnapshotCommandWrapper());
         linbvirtCommands.put(DeleteStoragePoolCommand.class, new LibvirtDeleteStoragePoolCommandWrapper());
+        linbvirtCommands.put(OvsSetupBridgeCommand.class, new LibvirtOvsSetupBridgeCommandWrapper());
+        linbvirtCommands.put(OvsDestroyBridgeCommand.class, new LibvirtOvsDestroyBridgeCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/4887ce72/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 2432c98..b8046f5 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -77,6 +77,8 @@ import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
+import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -764,6 +766,203 @@ public class LibvirtComputingResourceTest {
         verify(diskTO, times(1)).getType();
     }
 
+    @Test
+    public void testPrepareForMigrationCommandMigration() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
+        final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final NicTO nicTO = Mockito.mock(NicTO.class);
+        final DiskTO diskTO = Mockito.mock(DiskTO.class);
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+
+        final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
+        when(vm.getDisks()).thenReturn(new DiskTO[]{diskTO});
+
+        when(nicTO.getType()).thenReturn(TrafficType.Guest);
+        when(diskTO.getType()).thenReturn(Volume.Type.ISO);
+
+        when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
+        when(storagePoolManager.connectPhysicalDisksViaVmSpec(vm)).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(vm, times(1)).getNics();
+        verify(vm, times(1)).getDisks();
+        verify(diskTO, times(1)).getType();
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPrepareForMigrationCommandLibvirtException() {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
+        final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final NicTO nicTO = Mockito.mock(NicTO.class);
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+
+        final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
+        when(nicTO.getType()).thenReturn(TrafficType.Guest);
+
+        when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(vm, times(1)).getNics();
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPrepareForMigrationCommandURISyntaxException() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
+        final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final NicTO nicTO = Mockito.mock(NicTO.class);
+        final DiskTO volume = Mockito.mock(DiskTO.class);
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+
+        final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
+        when(vm.getDisks()).thenReturn(new DiskTO[]{volume});
+
+        when(nicTO.getType()).thenReturn(TrafficType.Guest);
+        when(volume.getType()).thenReturn(Volume.Type.ISO);
+
+        when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenReturn(vifDriver);
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
+        try {
+            when(libvirtComputingResource.getVolumePath(conn, volume)).thenThrow(URISyntaxException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final URISyntaxException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(vm, times(1)).getNics();
+        verify(vm, times(1)).getDisks();
+        verify(volume, times(1)).getType();
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPrepareForMigrationCommandInternalErrorException() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
+        final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
+        final NicTO nicTO = Mockito.mock(NicTO.class);
+        final DiskTO volume = Mockito.mock(DiskTO.class);
+
+        final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
+        when(nicTO.getType()).thenReturn(TrafficType.Guest);
+
+        when(libvirtComputingResource.getVifDriver(nicTO.getType())).thenThrow(InternalErrorException.class);
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
+        try {
+            when(libvirtComputingResource.getVolumePath(conn, volume)).thenReturn("/path");
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final URISyntaxException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(vm, times(1)).getNics();
+    }
+
     @Test(expected = UnsatisfiedLinkError.class)
     public void testMigrateCommand() {
         // The Connect constructor used inside the LibvirtMigrateCommandWrapper has a call to native methods, which
@@ -1708,4 +1907,92 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
         verify(storagePoolMgr, times(1)).deleteStoragePool(pool.getType(), pool.getUuid());
     }
+
+    @Test
+    public void testOvsSetupBridgeCommand() {
+        final String name = "Test";
+        final Long hostId = 1l;
+        final Long networkId = 1l;
+
+        final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName())).thenReturn(true);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+        verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName());
+    }
+
+    @Test
+    public void testOvsSetupBridgeCommandFailure() {
+        final String name = "Test";
+        final Long hostId = 1l;
+        final Long networkId = 1l;
+
+        final OvsSetupBridgeCommand command = new OvsSetupBridgeCommand(name, hostId, networkId);
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(command.getBridgeName())).thenReturn(true);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName())).thenReturn(false);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
+        verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getHostId(),
+                command.getBridgeName());
+    }
+
+    @Test
+    public void testOvsDestroyBridgeCommand() {
+        final String name = "Test";
+        final Long hostId = 1l;
+        final Long networkId = 1l;
+
+        final OvsDestroyBridgeCommand command = new OvsDestroyBridgeCommand(networkId, name, hostId);
+
+        when(libvirtComputingResource.destroyTunnelNetwork(command.getBridgeName())).thenReturn(true);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).destroyTunnelNetwork(command.getBridgeName());
+    }
+
+    @Test
+    public void testOvsDestroyBridgeCommandFailure() {
+        final String name = "Test";
+        final Long hostId = 1l;
+        final Long networkId = 1l;
+
+        final OvsDestroyBridgeCommand command = new OvsDestroyBridgeCommand(networkId, name, hostId);
+
+        when(libvirtComputingResource.destroyTunnelNetwork(command.getBridgeName())).thenReturn(false);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).destroyTunnelNetwork(command.getBridgeName());
+    }
 }
\ No newline at end of file


[43/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8481: Adding test cases for validating global limit on concurrent snapshots

Signed-off-by: Gaurav Aradhye <ga...@clogeny.com>
This closes #252


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/19c436fd
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/19c436fd
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/19c436fd

Branch: refs/heads/CLOUDSTACK-8301
Commit: 19c436fd592de6cebd347892c8225362c90b4660
Parents: 4b597ca
Author: Gaurav Aradhye <ga...@clogeny.com>
Authored: Tue May 19 15:15:29 2015 +0530
Committer: Gaurav Aradhye <ga...@clogeny.com>
Committed: Tue May 19 15:25:29 2015 +0530

----------------------------------------------------------------------
 .../test_concurrent_snapshots_limit.py          | 299 +++++++++++++++++++
 1 file changed, 299 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/19c436fd/test/integration/component/test_concurrent_snapshots_limit.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_concurrent_snapshots_limit.py b/test/integration/component/test_concurrent_snapshots_limit.py
new file mode 100644
index 0000000..910cb00
--- /dev/null
+++ b/test/integration/component/test_concurrent_snapshots_limit.py
@@ -0,0 +1,299 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+""" Test cases for validating global limit for concurrent snapshots
+"""
+from nose.plugins.attrib import attr
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.utils import (cleanup_resources,
+                              validateList)
+from marvin.lib.base import (Account,
+                             ServiceOffering,
+                             VirtualMachine,
+                             Snapshot,
+                             Volume,
+                             Configurations
+                             )
+from marvin.lib.common import (get_domain,
+                               get_zone,
+                               get_template
+                               )
+
+from marvin.codes import PASS, BACKED_UP
+from threading import Thread
+
+
+class TestConcurrentSnapshotLimit(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestConcurrentSnapshotLimit, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        cls.hypervisor = cls.testClient.getHypervisorInfo()
+
+        # Get Zone, Domain and templates
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
+
+        cls.template = get_template(
+            cls.apiclient,
+            cls.zone.id,
+            cls.testdata["ostype"])
+
+        cls._cleanup = []
+        cls.supportedHypervisor = True
+
+        if cls.hypervisor.lower() in [
+                "hyperv",
+                "lxc"]:
+            cls.supportedHypervisor = False
+            return
+
+        # Create Service offering
+        cls.service_offering = ServiceOffering.create(
+            cls.apiclient,
+            cls.testdata["service_offering"],
+        )
+        cls._cleanup.append(cls.service_offering)
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.dbclient = self.testClient.getDbConnection()
+        self.cleanup = []
+
+        self.exceptionOccured = False
+
+        if not self.supportedHypervisor:
+            self.skipTest("Snapshot not supported on %s" % self.hypervisor)
+
+    def createSnapshot(self, volumeid):
+        try:
+            Snapshot.create(
+                self.apiclient,
+                volumeid
+            )
+        except Exception as e:
+            self.debug("Exception occured: %s" % e)
+            self.exceptionOccured = True
+
+    def tearDown(self):
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    @attr(tags=["advanced", "basic"], required_hardware="true")
+    def test_01_concurrent_snapshot_global_limit(self):
+        """ Test if global value concurrent.snapshots.threshold.perhost
+            value respected
+            This is positive test cases and tests if we are able to create
+            as many snapshots mentioned in global value
+        # 1. Create an account and a VM in it
+        # 2. Read the global value for concurrent.snapshots.threshold.perhost
+        # 3. If the value is Null, create at least 10 concurrent snapshots
+             and verify they are created successfully
+        # 4. Else, create as many snapshots specified in the global value, and
+             verify they are created successfully
+        """
+
+        # Create an account
+        account = Account.create(
+            self.apiclient,
+            self.testdata["account"],
+            domainid=self.domain.id
+        )
+
+        self.cleanup.append(account)
+        # Create user api client of the account
+        userapiclient = self.testClient.getUserApiClient(
+            UserName=account.name,
+            DomainName=account.domain
+        )
+
+        # Create VM
+        virtual_machine = VirtualMachine.create(
+            userapiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=account.name,
+            domainid=account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        # Create 10 concurrent snapshots by default
+        # We can have any value, so keeping it 10 as it
+        # seems good enough to test
+        concurrentSnapshots = 10
+
+        # Step 1
+        # Get ROOT Volume Id
+        volumes = Volume.list(
+            self.apiclient,
+            virtualmachineid=virtual_machine.id,
+            type='ROOT',
+            listall=True
+        )
+
+        self.assertEqual(validateList(volumes)[0], PASS,
+                         "Volumes list validation failed")
+
+        root_volume = volumes[0]
+
+        config = Configurations.list(
+            self.apiclient,
+            name="concurrent.snapshots.threshold.perhost"
+        )
+        self.assertEqual(
+            isinstance(
+                config,
+                list),
+            True,
+            "concurrent.snapshots.threshold.perhost should be present\
+                    in global config")
+        if config[0].value:
+            concurrentSnapshots = int(config[0].value)
+        self.debug("concurrent Snapshots: %s" % concurrentSnapshots)
+
+        threads = []
+        for i in range(0, (concurrentSnapshots)):
+            thread = Thread(
+                target=Snapshot.create,
+                args=(
+                    self.apiclient,
+                    root_volume.id
+                ))
+            threads.append(thread)
+            thread.start()
+        for thread in threads:
+            thread.join()
+
+        snapshots = Snapshot.list(self.apiclient,
+                                  volumeid=root_volume.id,
+                                  listall=True)
+
+        self.assertEqual(validateList(snapshots)[0], PASS,
+                         "Snapshots list validation failed")
+        self.assertEqual(
+            len(snapshots),
+            concurrentSnapshots,
+            "There should be exactly %s snapshots present" %
+            concurrentSnapshots)
+
+        for snapshot in snapshots:
+            self.assertEqual(str(snapshot.state).lower(), BACKED_UP,
+                             "Snapshot state should be backedUp but it is\
+                            %s" % snapshot.state)
+        return
+
+    @attr(tags=["advanced", "basic"], required_hardware="true")
+    def test_02_concurrent_snapshot_global_limit(self):
+        """ Test if global value concurrent.snapshots.threshold.perhost
+            value is respected
+            This is negative test cases and tests no more concurrent
+            snapshots as specified in global value are created
+        # 1. Read the global value for concurrent.snapshots.threshold.perhost
+        # 2. If the value is Null, skip the test case
+        # 3. Create an account and a VM in it
+        # 4. Create more concurrent snapshots than specified in
+             global allowed limit
+        # 5. Verify that exception is raised while creating snapshots
+        """
+
+        config = Configurations.list(
+            self.apiclient,
+            name="concurrent.snapshots.threshold.perhost"
+        )
+        self.assertEqual(
+            isinstance(
+                config,
+                list),
+            True,
+            "concurrent.snapshots.threshold.perhost should be present\
+                    in global config")
+        if config[0].value:
+            concurrentSnapshots = int(config[0].value)
+        else:
+            self.skipTest("Skipping tests as the config value \
+                    concurrent.snapshots.threshold.perhost is Null")
+
+        # Create an account
+        account = Account.create(
+            self.apiclient,
+            self.testdata["account"],
+            domainid=self.domain.id
+        )
+
+        self.cleanup.append(account)
+        # Create user api client of the account
+        userapiclient = self.testClient.getUserApiClient(
+            UserName=account.name,
+            DomainName=account.domain
+        )
+
+        # Create VM
+        virtual_machine = VirtualMachine.create(
+            userapiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=account.name,
+            domainid=account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        # Step 1
+        # Get ROOT Volume Id
+        volumes = Volume.list(
+            self.apiclient,
+            virtualmachineid=virtual_machine.id,
+            type='ROOT',
+            listall=True
+        )
+
+        self.assertEqual(validateList(volumes)[0], PASS,
+                         "Volumes list validation failed")
+
+        root_volume = volumes[0]
+
+        threads = []
+        for i in range(0, (concurrentSnapshots + 1)):
+            thread = Thread(
+                target=self.createSnapshot,
+                args=(
+                    self.apiclient,
+                    root_volume.id
+                ))
+            threads.append(thread)
+            thread.start()
+
+        for thread in threads:
+            thread.join()
+
+        self.assertTrue(self.exceptionOccured, "Concurrent snapshots\
+                more than concurrent.snapshots.threshold.perhost\
+                value successfully created")
+        return


[23/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - 5 unit tests added
  - KVM hypervisor plugin with 20.1% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/7fd43f33
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/7fd43f33
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/7fd43f33

Branch: refs/heads/CLOUDSTACK-8301
Commit: 7fd43f33d35fc514cc480c0e15f934e58be2cfdc
Parents: 0b1b2b6
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 08:48:24 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:15 2015 +0200

----------------------------------------------------------------------
 .../LibvirtCopyVolumeCommandWrapper.java        |  15 +-
 .../resource/LibvirtComputingResourceTest.java  | 210 ++++++++++++++++++-
 2 files changed, 216 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7fd43f33/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
index d14b045..348c421 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
@@ -37,11 +37,12 @@ public final class LibvirtCopyVolumeCommandWrapper extends CommandWrapper<CopyVo
     @Override
     public Answer execute(final CopyVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
         /**
-        This method is only used for copying files from Primary Storage TO Secondary Storage
-
-        It COULD also do it the other way around, but the code in the ManagementServerImpl shows
-        that it always sets copyToSecondary to true
-
+         * This method is only used for copying files from Primary Storage TO
+         * Secondary Storage
+         *
+         * It COULD also do it the other way around, but the code in the
+         * ManagementServerImpl shows that it always sets copyToSecondary to
+         * true
          */
         final boolean copyToSecondary = command.toSecondaryStorage();
         String volumePath = command.getVolumePath();
@@ -56,9 +57,7 @@ public final class LibvirtCopyVolumeCommandWrapper extends CommandWrapper<CopyVo
                 primaryPool = storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
             } catch (final CloudRuntimeException e) {
                 if (e.getMessage().contains("not found")) {
-                    primaryPool =
-                            storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(),
-                                    command.getPool().getUserInfo(), command.getPool().getType());
+                    primaryPool = storagePoolMgr.createStoragePool(pool.getUuid(), pool.getHost(), pool.getPort(), pool.getPath(), pool.getUserInfo(), pool.getType());
                 } else {
                     return new CopyVolumeAnswer(command, false, e.getMessage(), null, null);
                 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7fd43f33/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index c5c1553..86ff007 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -119,6 +119,7 @@ import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
@@ -133,8 +134,8 @@ import com.cloud.exception.InternalErrorException;
 import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
-import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper;
+import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
@@ -3890,4 +3891,211 @@ public class LibvirtComputingResourceTest {
         verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
         verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
     }
+
+    @Test
+    public void testCopyVolumeCommand() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long volumeId = 1l;
+        final int wait = 0;
+        final String volumePath = "/vol/path";
+        final boolean toSecondaryStorage = true;
+        final boolean executeInSequence = false;
+
+        final CopyVolumeCommand command = new CopyVolumeCommand(volumeId, volumePath, storagePool, secondaryStoragePoolURL, toSecondaryStorage, wait, executeInSequence );
+
+        final String destVolumeName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+        final String volumeDestPath = "/volumes/" + command.getVolumeId() + File.separator;
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondary = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final StorageFilerTO pool = command.getPool();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(destVolumeName);
+        when(primary.getPhysicalDisk(command.getVolumePath())).thenReturn(disk);
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL)).thenReturn(secondary);
+        when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
+        when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
+        when(secondary.createFolder(volumeDestPath)).thenReturn(true);
+        when(storagePoolMgr.deleteStoragePool(secondary.getType(), secondary.getUuid())).thenReturn(true);
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
+        when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, secondary, 0)).thenReturn(disk);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testCopyVolumeCommandToSecFalse() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long volumeId = 1l;
+        final int wait = 0;
+        final String volumePath = "/vol/path";
+        final boolean toSecondaryStorage = false;
+        final boolean executeInSequence = false;
+
+        final CopyVolumeCommand command = new CopyVolumeCommand(volumeId, volumePath, storagePool, secondaryStoragePoolURL, toSecondaryStorage, wait, executeInSequence );
+
+        final String destVolumeName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+        final String volumeDestPath = "/volumes/" + command.getVolumeId() + File.separator;
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondary = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final StorageFilerTO pool = command.getPool();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(destVolumeName);
+        when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
+        when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
+        when(primary.getPhysicalDisk(command.getVolumePath() + ".qcow2")).thenReturn(disk);
+        when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, primary, 0)).thenReturn(disk);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCopyVolumeCommandCloudRuntime() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long volumeId = 1l;
+        final int wait = 0;
+        final String volumePath = "/vol/path";
+        final boolean toSecondaryStorage = false;
+        final boolean executeInSequence = false;
+
+        final CopyVolumeCommand command = new CopyVolumeCommand(volumeId, volumePath, storagePool, secondaryStoragePoolURL, toSecondaryStorage, wait, executeInSequence );
+
+        final String destVolumeName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+        final String volumeDestPath = "/volumes/" + command.getVolumeId() + File.separator;
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondary = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final StorageFilerTO pool = command.getPool();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primary);
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(destVolumeName);
+        when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
+        when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
+        when(secondary.getPhysicalDisk(command.getVolumePath() + ".qcow2")).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testCopyVolumeCommandCloudRuntime2() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long volumeId = 1l;
+        final int wait = 0;
+        final String volumePath = "/vol/path";
+        final boolean toSecondaryStorage = false;
+        final boolean executeInSequence = false;
+
+        final CopyVolumeCommand command = new CopyVolumeCommand(volumeId, volumePath, storagePool, secondaryStoragePoolURL, toSecondaryStorage, wait, executeInSequence );
+
+        final StorageFilerTO pool = command.getPool();
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenThrow(new CloudRuntimeException("error"));
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testCopyVolumeCommandPrimaryNotFound() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long volumeId = 1l;
+        final int wait = 0;
+        final String volumePath = "/vol/path";
+        final boolean toSecondaryStorage = false;
+        final boolean executeInSequence = false;
+
+        final CopyVolumeCommand command = new CopyVolumeCommand(volumeId, volumePath, storagePool, secondaryStoragePoolURL, toSecondaryStorage, wait, executeInSequence );
+
+        final String destVolumeName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+        final String volumeDestPath = "/volumes/" + command.getVolumeId() + File.separator;
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondary = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final StorageFilerTO pool = command.getPool();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenThrow(new CloudRuntimeException("not found"));
+
+        when(storagePoolMgr.createStoragePool(pool.getUuid(), pool.getHost(), pool.getPort(), pool.getPath(),
+                pool.getUserInfo(), pool.getType())).thenReturn(primary);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.generatereUUIDName()).thenReturn(destVolumeName);
+        when(secondary.getType()).thenReturn(StoragePoolType.ManagedNFS);
+        when(secondary.getUuid()).thenReturn("60d979d8-d132-4181-8eca-8dfde50d7df6");
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolURL + volumeDestPath)).thenReturn(secondary);
+        when(primary.getPhysicalDisk(command.getVolumePath() + ".qcow2")).thenReturn(disk);
+        when(storagePoolMgr.copyPhysicalDisk(disk, destVolumeName, primary, 0)).thenReturn(disk);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
 }
\ No newline at end of file


[39/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
systemvmtemplate: install libc6:i386 for 64bit template

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/9d8a62d0
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/9d8a62d0
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/9d8a62d0

Branch: refs/heads/CLOUDSTACK-8301
Commit: 9d8a62d0ee379bf8b67405944c86f68587245db6
Parents: 95e7673
Author: Rohit Yadav <ro...@shapeblue.com>
Authored: Mon May 18 19:58:57 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon May 18 19:58:57 2015 +0200

----------------------------------------------------------------------
 .../definitions/systemvmtemplate/install_systemvm_packages.sh      | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/9d8a62d0/tools/appliance/definitions/systemvmtemplate/install_systemvm_packages.sh
----------------------------------------------------------------------
diff --git a/tools/appliance/definitions/systemvmtemplate/install_systemvm_packages.sh b/tools/appliance/definitions/systemvmtemplate/install_systemvm_packages.sh
index fc90eba..83117a1 100644
--- a/tools/appliance/definitions/systemvmtemplate/install_systemvm_packages.sh
+++ b/tools/appliance/definitions/systemvmtemplate/install_systemvm_packages.sh
@@ -48,7 +48,7 @@ function install_packages() {
   if [ "${arch}" != "i386" ]; then
     dpkg --add-architecture i386
     apt-get update
-    ${apt_get} install links:i386 libuuid1:i386
+    ${apt_get} install links:i386 libuuid1:i386 libc6:i386
   fi
 
   ${apt_get} install \


[50/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Merge branch 'CLOUDSTACK-8301' of https://git-wip-us.apache.org/repos/asf/cloudstack into CLOUDSTACK-8301


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/8ff90008
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/8ff90008
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/8ff90008

Branch: refs/heads/CLOUDSTACK-8301
Commit: 8ff90008b8aa696b2c96c6417ac25166e651bb7e
Parents: b776cbc e5cee45
Author: Koushik Das <ko...@apache.org>
Authored: Tue May 19 21:49:24 2015 +0530
Committer: Koushik Das <ko...@apache.org>
Committed: Tue May 19 21:49:24 2015 +0530

----------------------------------------------------------------------

----------------------------------------------------------------------



[21/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtResizeVolumeCommandWrapper
  - 5 unit tests added
  - KVM hypervisor plugin with 22.1% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/08106e34
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/08106e34
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/08106e34

Branch: refs/heads/CLOUDSTACK-8301
Commit: 08106e34d0eb8e4a182b32aa24e625f294555724
Parents: ae505e7
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 13:36:15 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:15 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  98 +---------
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../LibvirtResizeVolumeCommandWrapper.java      | 136 ++++++++++++++
 .../resource/LibvirtComputingResourceTest.java  | 178 +++++++++++++++++++
 4 files changed, 321 insertions(+), 93 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08106e34/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 31a9ed7..e98e945 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -60,7 +60,6 @@ import org.libvirt.DomainInfo.DomainState;
 import org.libvirt.DomainInterfaceStats;
 import org.libvirt.LibvirtException;
 import org.libvirt.NodeInfo;
-import org.libvirt.StorageVol;
 
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
@@ -80,15 +79,12 @@ import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
-import com.cloud.agent.api.storage.ResizeVolumeAnswer;
-import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
 import com.cloud.agent.api.to.DataTO;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.IpAddressTO;
 import com.cloud.agent.api.to.NfsTO;
 import com.cloud.agent.api.to.NicTO;
-import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRouterDeployer;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
@@ -408,6 +404,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _ovsPvlanVmPath;
     }
 
+    public String getResizeVolumePath() {
+        return _resizeVolumePath;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1259,8 +1259,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((StartCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
-            } else if (cmd instanceof ResizeVolumeCommand) {
-                return execute((ResizeVolumeCommand)cmd);
             } else if (cmd instanceof StorageSubSystemCommand) {
                 return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
             } else {
@@ -1401,7 +1399,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private String getResizeScriptType(final KVMStoragePool pool, final KVMPhysicalDisk vol) {
+    public String getResizeScriptType(final KVMStoragePool pool, final KVMPhysicalDisk vol) {
         final StoragePoolType poolType = pool.getType();
         final PhysicalDiskFormat volFormat = vol.getFormat();
 
@@ -1417,92 +1415,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         throw new CloudRuntimeException("Cannot determine resize type from pool type " + pool.getType());
     }
 
-    /* uses a local script now, eventually support for virStorageVolResize() will maybe work on
-       qcow2 and lvm and we can do this in libvirt calls */
-    public Answer execute(final ResizeVolumeCommand cmd) {
-        final String volid = cmd.getPath();
-        final long newSize = cmd.getNewSize();
-        final long currentSize = cmd.getCurrentSize();
-        final String vmInstanceName = cmd.getInstanceName();
-        final boolean shrinkOk = cmd.getShrinkOk();
-        final StorageFilerTO spool = cmd.getPool();
-        final String notifyOnlyType = "NOTIFYONLY";
-
-        if ( currentSize == newSize) {
-            // nothing to do
-            s_logger.info("No need to resize volume: current size " + currentSize + " is same as new size " + newSize);
-            return new ResizeVolumeAnswer(cmd, true, "success", currentSize);
-        }
-
-        try {
-            KVMStoragePool pool = _storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid());
-            final KVMPhysicalDisk vol = pool.getPhysicalDisk(volid);
-            final String path = vol.getPath();
-            String type = getResizeScriptType(pool, vol);
-
-            if (pool.getType() != StoragePoolType.RBD) {
-                if (type.equals("QCOW2") && shrinkOk) {
-                    return new ResizeVolumeAnswer(cmd, false, "Unable to shrink volumes of type " + type);
-                }
-            } else {
-                s_logger.debug("Volume " + path + " is on a RBD storage pool. No need to query for additional information.");
-            }
-
-            s_logger.debug("Resizing volume: " + path + "," + currentSize + "," + newSize + "," + type + "," + vmInstanceName + "," + shrinkOk);
-
-            /* libvirt doesn't support resizing (C)LVM devices, and corrupts QCOW2 in some scenarios, so we have to do these via Bash script */
-            if (pool.getType() != StoragePoolType.CLVM && vol.getFormat() != PhysicalDiskFormat.QCOW2) {
-                s_logger.debug("Volume " + path +  " can be resized by libvirt. Asking libvirt to resize the volume.");
-                try {
-                    final Connect conn = LibvirtConnection.getConnection();
-                    final StorageVol v = conn.storageVolLookupByPath(path);
-                    int flags = 0;
-
-                    if (conn.getLibVirVersion() > 1001000 && vol.getFormat() == PhysicalDiskFormat.RAW && pool.getType() != StoragePoolType.RBD) {
-                        flags = 1;
-                    }
-                    if (shrinkOk) {
-                        flags = 4;
-                    }
-
-                    v.resize(newSize, flags);
-                    type = notifyOnlyType;
-                } catch (final LibvirtException e) {
-                    return new ResizeVolumeAnswer(cmd, false, e.toString());
-                }
-            }
-            s_logger.debug("Invoking resize script to handle type " + type);
-            final Script resizecmd = new Script(_resizeVolumePath, _cmdsTimeout, s_logger);
-            resizecmd.add("-s", String.valueOf(newSize));
-            resizecmd.add("-c", String.valueOf(currentSize));
-            resizecmd.add("-p", path);
-            resizecmd.add("-t", type);
-            resizecmd.add("-r", String.valueOf(shrinkOk));
-            resizecmd.add("-v", vmInstanceName);
-            final String result = resizecmd.execute();
-
-            if (result != null) {
-                if(type.equals(notifyOnlyType)) {
-                    return new ResizeVolumeAnswer(cmd, true, "Resize succeeded, but need reboot to notify guest");
-                } else {
-                    return new ResizeVolumeAnswer(cmd, false, result);
-                }
-            }
-
-            /* fetch new size as seen from libvirt, don't want to assume anything */
-            pool = _storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid());
-            pool.refresh();
-            final long finalSize = pool.getPhysicalDisk(volid).getVirtualSize();
-            s_logger.debug("after resize, size reports as " + finalSize + ", requested " + newSize);
-            return new ResizeVolumeAnswer(cmd, true, "success", finalSize);
-        } catch (final CloudRuntimeException e) {
-            final String error = "Failed to resize volume: " + e.getMessage();
-            s_logger.debug(error);
-            return new ResizeVolumeAnswer(cmd, false, error);
-        }
-
-    }
-
     private String getBroadcastUriFromBridge(final String brName) {
         final String pif = matchPifFileInDirectory(brName);
         final Pattern pattern = Pattern.compile("(\\D+)(\\d+)(\\D*)(\\d*)");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08106e34/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index c103ef3..363981d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -74,6 +74,7 @@ import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
+import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.RequestWrapper;
@@ -148,6 +149,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
         linbvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
         linbvirtCommands.put(PvlanSetupCommand.class, new LibvirtPvlanSetupCommandWrapper());
+        linbvirtCommands.put(ResizeVolumeCommand.class, new LibvirtResizeVolumeCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08106e34/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java
new file mode 100644
index 0000000..bbcba47
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtResizeVolumeCommandWrapper.java
@@ -0,0 +1,136 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+import org.libvirt.StorageVol;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.ResizeVolumeAnswer;
+import com.cloud.agent.api.storage.ResizeVolumeCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+
+/*
+ * Uses a local script now, eventually support for virStorageVolResize() will maybe work on qcow2 and lvm and we can do this in libvirt calls
+ */
+public final class LibvirtResizeVolumeCommandWrapper extends CommandWrapper<ResizeVolumeCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtResizeVolumeCommandWrapper.class);
+
+    @Override
+    public Answer execute(final ResizeVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String volid = command.getPath();
+        final long newSize = command.getNewSize();
+        final long currentSize = command.getCurrentSize();
+        final String vmInstanceName = command.getInstanceName();
+        final boolean shrinkOk = command.getShrinkOk();
+        final StorageFilerTO spool = command.getPool();
+        final String notifyOnlyType = "NOTIFYONLY";
+
+        if ( currentSize == newSize) {
+            // nothing to do
+            s_logger.info("No need to resize volume: current size " + currentSize + " is same as new size " + newSize);
+            return new ResizeVolumeAnswer(command, true, "success", currentSize);
+        }
+
+        try {
+            final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            KVMStoragePool pool = storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid());
+
+            final KVMPhysicalDisk vol = pool.getPhysicalDisk(volid);
+            final String path = vol.getPath();
+            String type = libvirtComputingResource.getResizeScriptType(pool, vol);
+
+            if (pool.getType() != StoragePoolType.RBD) {
+                if (type.equals("QCOW2") && shrinkOk) {
+                    return new ResizeVolumeAnswer(command, false, "Unable to shrink volumes of type " + type);
+                }
+            } else {
+                s_logger.debug("Volume " + path + " is on a RBD storage pool. No need to query for additional information.");
+            }
+
+            s_logger.debug("Resizing volume: " + path + "," + currentSize + "," + newSize + "," + type + "," + vmInstanceName + "," + shrinkOk);
+
+            /* libvirt doesn't support resizing (C)LVM devices, and corrupts QCOW2 in some scenarios, so we have to do these via Bash script */
+            if (pool.getType() != StoragePoolType.CLVM && vol.getFormat() != PhysicalDiskFormat.QCOW2) {
+                s_logger.debug("Volume " + path +  " can be resized by libvirt. Asking libvirt to resize the volume.");
+                try {
+                    final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+
+                    final Connect conn = libvirtUtilitiesHelper.getConnection();
+                    final StorageVol v = conn.storageVolLookupByPath(path);
+                    int flags = 0;
+
+                    if (conn.getLibVirVersion() > 1001000 && vol.getFormat() == PhysicalDiskFormat.RAW && pool.getType() != StoragePoolType.RBD) {
+                        flags = 1;
+                    }
+                    if (shrinkOk) {
+                        flags = 4;
+                    }
+
+                    v.resize(newSize, flags);
+                    type = notifyOnlyType;
+                } catch (final LibvirtException e) {
+                    return new ResizeVolumeAnswer(command, false, e.toString());
+                }
+            }
+            s_logger.debug("Invoking resize script to handle type " + type);
+
+            final Script resizecmd = new Script(libvirtComputingResource.getResizeVolumePath(), libvirtComputingResource.getCmdsTimeout(), s_logger);
+            resizecmd.add("-s", String.valueOf(newSize));
+            resizecmd.add("-c", String.valueOf(currentSize));
+            resizecmd.add("-p", path);
+            resizecmd.add("-t", type);
+            resizecmd.add("-r", String.valueOf(shrinkOk));
+            resizecmd.add("-v", vmInstanceName);
+            final String result = resizecmd.execute();
+
+            if (result != null) {
+                if(type.equals(notifyOnlyType)) {
+                    return new ResizeVolumeAnswer(command, true, "Resize succeeded, but need reboot to notify guest");
+                } else {
+                    return new ResizeVolumeAnswer(command, false, result);
+                }
+            }
+
+            /* fetch new size as seen from libvirt, don't want to assume anything */
+            pool = storagePoolMgr.getStoragePool(spool.getType(), spool.getUuid());
+            pool.refresh();
+            final long finalSize = pool.getPhysicalDisk(volid).getVirtualSize();
+            s_logger.debug("after resize, size reports as " + finalSize + ", requested " + newSize);
+            return new ResizeVolumeAnswer(command, true, "success", finalSize);
+        } catch (final CloudRuntimeException e) {
+            final String error = "Failed to resize volume: " + e.getMessage();
+            s_logger.debug(error);
+            return new ResizeVolumeAnswer(command, false, error);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08106e34/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index ad75b53..4e8d7bd 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -46,6 +46,7 @@ import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
 
+import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
 import org.apache.commons.lang.SystemUtils;
 import org.junit.Assert;
 import org.junit.Assume;
@@ -59,6 +60,7 @@ import org.libvirt.DomainInfo.DomainState;
 import org.libvirt.DomainInterfaceStats;
 import org.libvirt.LibvirtException;
 import org.libvirt.NodeInfo;
+import org.libvirt.StorageVol;
 import org.mockito.Matchers;
 import org.mockito.Mock;
 import org.mockito.Mockito;
@@ -126,6 +128,7 @@ import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
+import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
@@ -4328,4 +4331,179 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
     }
+
+    @Test
+    public void testResizeVolumeCommand() {
+        final String path = "nfs:/192.168.2.2/storage/secondary";
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final Long currentSize = 100l;
+        final Long newSize = 200l;
+        final boolean shrinkOk = true;
+        final String vmInstance = "Test";
+
+        final ResizeVolumeCommand command = new ResizeVolumeCommand(path, pool, currentSize, newSize, shrinkOk, vmInstance);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final StorageVol v = Mockito.mock(StorageVol.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
+        when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
+        when(vol.getPath()).thenReturn(path);
+        when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("FILE");
+        when(storagePool.getType()).thenReturn(StoragePoolType.RBD);
+        when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnection()).thenReturn(conn);
+            when(conn.storageVolLookupByPath(path)).thenReturn(v);
+
+            when(conn.getLibVirVersion()).thenReturn(10010l);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnection();
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testResizeVolumeCommandSameSize() {
+        final String path = "nfs:/192.168.2.2/storage/secondary";
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final Long currentSize = 100l;
+        final Long newSize = 100l;
+        final boolean shrinkOk = false;
+        final String vmInstance = "Test";
+
+        final ResizeVolumeCommand command = new ResizeVolumeCommand(path, pool, currentSize, newSize, shrinkOk, vmInstance);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testResizeVolumeCommandShrink() {
+        final String path = "nfs:/192.168.2.2/storage/secondary";
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final Long currentSize = 100l;
+        final Long newSize = 200l;
+        final boolean shrinkOk = true;
+        final String vmInstance = "Test";
+
+        final ResizeVolumeCommand command = new ResizeVolumeCommand(path, pool, currentSize, newSize, shrinkOk, vmInstance);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
+        when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
+        when(vol.getPath()).thenReturn(path);
+        when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("QCOW2");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testResizeVolumeCommandException() {
+        final String path = "nfs:/192.168.2.2/storage/secondary";
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final Long currentSize = 100l;
+        final Long newSize = 200l;
+        final boolean shrinkOk = false;
+        final String vmInstance = "Test";
+
+        final ResizeVolumeCommand command = new ResizeVolumeCommand(path, pool, currentSize, newSize, shrinkOk, vmInstance);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk vol = Mockito.mock(KVMPhysicalDisk.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
+        when(storagePool.getPhysicalDisk(path)).thenReturn(vol);
+        when(vol.getPath()).thenReturn(path);
+        when(libvirtComputingResource.getResizeScriptType(storagePool, vol)).thenReturn("FILE");
+        when(storagePool.getType()).thenReturn(StoragePoolType.RBD);
+        when(vol.getFormat()).thenReturn(PhysicalDiskFormat.FILE);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnection()).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnection();
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testResizeVolumeCommandException2() {
+        final String path = "nfs:/192.168.2.2/storage/secondary";
+        final StorageFilerTO pool = Mockito.mock(StorageFilerTO.class);
+        final Long currentSize = 100l;
+        final Long newSize = 200l;
+        final boolean shrinkOk = false;
+        final String vmInstance = "Test";
+
+        final ResizeVolumeCommand command = new ResizeVolumeCommand(path, pool, currentSize, newSize, shrinkOk, vmInstance);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool storagePool = Mockito.mock(KVMStoragePool.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(storagePool);
+        when(storagePool.getPhysicalDisk(path)).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
 }
\ No newline at end of file


[20/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Renaming LibvirtConnectionWrapper to LibvirtUtilitiesHelper
  - Gave it a better, more suggestive, name since I now added other methods to the class.
  - It makes easier to mock objects and get a better coverage of the classes


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/885b9e45
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/885b9e45
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/885b9e45

Branch: refs/heads/CLOUDSTACK-8301
Commit: 885b9e45d767d9c1e97f9f89323733446b0815f0
Parents: b3913ca
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue May 5 13:44:52 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:14 2015 +0200

----------------------------------------------------------------------
 .../kvm-compute/spring-kvm-compute-context.xml  |   4 +-
 .../kvm/resource/LibvirtComputingResource.java  |   8 +-
 .../wrapper/LibvirtAttachIsoCommandWrapper.java |   4 +-
 .../LibvirtAttachVolumeCommandWrapper.java      |   4 +-
 .../LibvirtBackupSnapshotCommandWrapper.java    |   4 +-
 ...ibvirtCheckVirtualMachineCommandWrapper.java |   4 +-
 .../wrapper/LibvirtConnectionWrapper.java       |  68 ----
 ...ivateTemplateFromSnapshotCommandWrapper.java |   8 +-
 .../LibvirtGetVmDiskStatsCommandWrapper.java    |   4 +-
 .../LibvirtGetVmStatsCommandWrapper.java        |   4 +-
 .../LibvirtGetVncPortCommandWrapper.java        |   4 +-
 .../LibvirtManageSnapshotCommandWrapper.java    |   4 +-
 .../wrapper/LibvirtMigrateCommandWrapper.java   |   4 +-
 ...bvirtNetworkRulesSystemVmCommandWrapper.java |   4 +-
 ...NetworkRulesVmSecondaryIpCommandWrapper.java |   4 +-
 .../wrapper/LibvirtPlugNicCommandWrapper.java   |   4 +-
 ...ibvirtPrepareForMigrationCommandWrapper.java |   4 +-
 .../wrapper/LibvirtRebootCommandWrapper.java    |   4 +-
 ...LibvirtSecurityGroupRulesCommandWrapper.java |   4 +-
 .../wrapper/LibvirtStopCommandWrapper.java      |   6 +-
 .../wrapper/LibvirtUnPlugNicCommandWrapper.java |   4 +-
 .../wrapper/LibvirtUtilitiesHelper.java         |  68 ++++
 .../resource/LibvirtComputingResourceTest.java  | 376 +++++++++----------
 23 files changed, 301 insertions(+), 301 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/resources/META-INF/cloudstack/kvm-compute/spring-kvm-compute-context.xml
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/resources/META-INF/cloudstack/kvm-compute/spring-kvm-compute-context.xml b/plugins/hypervisors/kvm/resources/META-INF/cloudstack/kvm-compute/spring-kvm-compute-context.xml
index de6853e..10f33ec 100644
--- a/plugins/hypervisors/kvm/resources/META-INF/cloudstack/kvm-compute/spring-kvm-compute-context.xml
+++ b/plugins/hypervisors/kvm/resources/META-INF/cloudstack/kvm-compute/spring-kvm-compute-context.xml
@@ -31,7 +31,7 @@
         <property name="name" value="KVMInvestigator" />
     </bean>
     
-    <bean id="libvirtConnectionWrapper"
-        class="com.cloud.hypervisor.kvm.resource.wrapper.LibvirtConnectionWrapper" />
+    <bean id="libvirtUtilitiesHelper"
+        class="com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper" />
     
 </beans>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 977288b..a9410fb 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -119,7 +119,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VideoDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VirtioSerialDef;
-import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtConnectionWrapper;
+import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper;
 import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
@@ -272,7 +272,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     protected int _stopTimeout;
 
     @Inject
-    private LibvirtConnectionWrapper libvirtConnectionWrapper;
+    private LibvirtUtilitiesHelper libvirtUtilitiesHelper;
 
     @Override
     public ExecutionResult executeInVR(final String routerIp, final String script, final String args) {
@@ -335,8 +335,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new ExecutionResult(true, null);
     }
 
-    public LibvirtConnectionWrapper getLibvirtConnectionWrapper() {
-        return libvirtConnectionWrapper;
+    public LibvirtUtilitiesHelper getLibvirtConnectionWrapper() {
+        return libvirtUtilitiesHelper;
     }
 
     public VirtualRoutingResource getVirtRouterResource() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
index 4380b66..9c12845 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
@@ -35,9 +35,9 @@ public final class LibvirtAttachIsoCommandWrapper extends CommandWrapper<AttachI
     @Override
     public Answer execute(final AttachIsoCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             libvirtComputingResource.attachOrDetachISO(conn, command.getVmName(), command.getIsoPath(), command.isAttach());
         } catch (final LibvirtException e) {
             return new Answer(command, false, e.toString());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
index 861bccc..038670d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
@@ -36,9 +36,9 @@ public final class LibvirtAttachVolumeCommandWrapper extends CommandWrapper<Atta
     @Override
     public Answer execute(final AttachVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
 
             final KVMStoragePool primary = libvirtComputingResource.getStoragePoolMgr().getStoragePool(command.getPooltype(), command.getPoolUuid());
             final KVMPhysicalDisk disk = primary.getPhysicalDisk(command.getVolumePath());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
index afbbf73..89fdea0 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
@@ -68,8 +68,8 @@ public final class LibvirtBackupSnapshotCommandWrapper extends CommandWrapper<Ba
         final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
 
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
 
             secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl);
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
index 3ad3300..d59ea5d 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
@@ -34,9 +34,9 @@ public final class LibvirtCheckVirtualMachineCommandWrapper extends CommandWrapp
     @Override
     public Answer execute(final CheckVirtualMachineCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             final PowerState state = libvirtComputingResource.getVmState(conn, command.getVmName());
             Integer vncPort = null;
             if (state == PowerState.PowerOn) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
deleted file mode 100644
index 3a51a37..0000000
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
+++ /dev/null
@@ -1,68 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
-package com.cloud.hypervisor.kvm.resource.wrapper;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.naming.ConfigurationException;
-
-import org.libvirt.Connect;
-import org.libvirt.LibvirtException;
-
-import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
-import com.cloud.storage.StorageLayer;
-import com.cloud.storage.template.Processor;
-import com.cloud.storage.template.QCOW2Processor;
-import com.cloud.storage.template.TemplateLocation;
-
-/**
- * This class is used to wrap the calls to several static methods. By doing so, we make easier to mock this class
- * and the methods wrapped here.
- *
- * Please do not instantiate this class directly, but inject it using the {@code @Inject} annotation.
- */
-public class LibvirtConnectionWrapper {
-
-    public Connect getConnectionByVmName(final String vmName) throws LibvirtException {
-        return LibvirtConnection.getConnectionByVmName(vmName);
-    }
-
-    public Connect getConnection() throws LibvirtException {
-        return LibvirtConnection.getConnection();
-    }
-
-    public TemplateLocation buildTemplateLocation(final StorageLayer storage, final String templatePath) {
-        final TemplateLocation location = new TemplateLocation(storage, templatePath);
-        return location;
-    }
-
-    public Processor buildQCOW2Processor(final StorageLayer storage) throws ConfigurationException {
-        final Map<String, Object> params = new HashMap<String, Object>();
-        params.put(StorageLayer.InstanceConfigKey, storage);
-
-        final Processor qcow2Processor = new QCOW2Processor();
-        qcow2Processor.configure("QCOW2 Processor", params);
-
-        return qcow2Processor;
-    }
-
-    public String buildTemplateUUIDName() {
-        return UUID.randomUUID().toString();
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
index 20bebad..0778586 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
@@ -48,11 +48,11 @@ public final class LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper extend
 
     @Override
     public Answer execute(final CreatePrivateTemplateFromSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
         final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
-        final String tmplName = libvirtConnectionWrapper.buildTemplateUUIDName();
+        final String tmplName = libvirtUtilitiesHelper.buildTemplateUUIDName();
         final String tmplFileName = tmplName + ".qcow2";
 
         KVMStoragePool secondaryPool = null;
@@ -84,9 +84,9 @@ public final class LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper extend
             scriptCommand.add("-f", snapshot.getPath());
             scriptCommand.execute();
 
-            final Processor qcow2Processor = libvirtConnectionWrapper.buildQCOW2Processor(storage);
+            final Processor qcow2Processor = libvirtUtilitiesHelper.buildQCOW2Processor(storage);
             final FormatInfo info = qcow2Processor.process(templatePath, null, tmplName);
-            final TemplateLocation loc = libvirtConnectionWrapper.buildTemplateLocation(storage, templatePath);
+            final TemplateLocation loc = libvirtUtilitiesHelper.buildTemplateLocation(storage, templatePath);
 
             loc.create(1, true, tmplName);
             loc.addFormat(info);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
index 32ff7df..7c76833 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
@@ -40,11 +40,11 @@ public final class LibvirtGetVmDiskStatsCommandWrapper extends CommandWrapper<Ge
     @Override
     public Answer execute(final GetVmDiskStatsCommand command, final LibvirtComputingResource libvirtComputingResource) {
         final List<String> vmNames = command.getVmNames();
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
         try {
             final HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsNameMap = new HashMap<String, List<VmDiskStatsEntry>>();
-            final Connect conn = libvirtConnectionWrapper.getConnection();
+            final Connect conn = libvirtUtilitiesHelper.getConnection();
             for (final String vmName : vmNames) {
                 final List<VmDiskStatsEntry> statEntry = libvirtComputingResource.getVmDiskStat(conn, vmName);
                 if (statEntry == null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
index e0649da..f1ddca1 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
@@ -44,9 +44,9 @@ public final class LibvirtGetVmStatsCommandWrapper extends CommandWrapper<GetVmS
             final HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
             for (final String vmName : vmNames) {
 
-                final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+                final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-                final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+                final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
                 final VmStatsEntry statEntry = libvirtComputingResource.getVmStat(conn, vmName);
                 if (statEntry == null) {
                     continue;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
index 9b76374..d7c1820 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
@@ -33,9 +33,9 @@ public final class LibvirtGetVncPortCommandWrapper extends CommandWrapper<GetVnc
     @Override
     public Answer execute(final GetVncPortCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getName());
             final Integer vncPort = libvirtComputingResource.getVncPort(conn, command.getName());
             return new GetVncPortAnswer(command, libvirtComputingResource.getPrivateIp(), 5900 + vncPort);
         } catch (final LibvirtException e) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
index 9a991a1..154e67b 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
@@ -53,8 +53,8 @@ public final class LibvirtManageSnapshotCommandWrapper extends CommandWrapper<Ma
         final String snapshotPath = command.getSnapshotPath();
         final String vmName = command.getVmName();
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             DomainState state = null;
             Domain vm = null;
             if (vmName != null) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
index d3637e6..e30e976 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
@@ -63,9 +63,9 @@ public final class LibvirtMigrateCommandWrapper extends CommandWrapper<MigrateCo
         Connect conn = null;
         String xmlDesc = null;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             ifaces = libvirtComputingResource.getInterfaces(conn, vmName);
             disks = libvirtComputingResource.getDisks(conn, vmName);
             dm = conn.domainLookupByName(vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
index b8ef8a8..a328c37 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
@@ -36,9 +36,9 @@ public final class LibvirtNetworkRulesSystemVmCommandWrapper extends CommandWrap
     public Answer execute(final NetworkRulesSystemVmCommand command, final LibvirtComputingResource libvirtComputingResource) {
         boolean success = false;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             success = libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName());
         } catch (final LibvirtException e) {
             s_logger.trace("Ignoring libvirt error.", e);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
index 6f15345..19eb3d3 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
@@ -36,9 +36,9 @@ public final class LibvirtNetworkRulesVmSecondaryIpCommandWrapper extends Comman
     public Answer execute(final NetworkRulesVmSecondaryIpCommand command, final LibvirtComputingResource libvirtComputingResource) {
         boolean result = false;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             result = libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction());
         } catch (final LibvirtException e) {
             s_logger.debug("Could not configure VM secondary IP! => " + e.getLocalizedMessage());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
index 7e6f642..692f79e 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
@@ -46,8 +46,8 @@ public final class LibvirtPlugNicCommandWrapper extends CommandWrapper<PlugNicCo
         final String vmName = command.getVmName();
         Domain vm = null;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             vm = libvirtComputingResource.getDomain(conn, vmName);
 
             final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
index 108b0d2..b9bf770 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
@@ -54,9 +54,9 @@ public final class LibvirtPrepareForMigrationCommandWrapper extends CommandWrapp
 
         final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vm.getName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vm.getName());
             for (final NicTO nic : nics) {
                 libvirtComputingResource.getVifDriver(nic.getType()).plug(nic, null, "");
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
index e91604a..414fcd6 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
@@ -35,10 +35,10 @@ public final class LibvirtRebootCommandWrapper extends CommandWrapper<RebootComm
 
     @Override
     public Answer execute(final RebootCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
         try {
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             final String result = libvirtComputingResource.rebootVM(conn, command.getVmName());
             if (result == null) {
                 Integer vncPort = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
index 5bdafe7..c661a16 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
@@ -41,9 +41,9 @@ public final class LibvirtSecurityGroupRulesCommandWrapper extends CommandWrappe
         String vif = null;
         String brname = null;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());
 
             vif = nics.get(0).getDevName();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
index 280c7f1..0d5f892 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
@@ -44,11 +44,11 @@ public final class LibvirtStopCommandWrapper extends CommandWrapper<StopCommand,
     public Answer execute(final StopCommand command, final LibvirtComputingResource libvirtComputingResource) {
         final String vmName = command.getVmName();
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
         if (command.checkBeforeCleanup()) {
             try {
-                final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+                final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
                 final Domain vm = conn.domainLookupByName(command.getVmName());
                 if (vm != null && vm.getInfo().state == DomainState.VIR_DOMAIN_RUNNING) {
                     return new StopAnswer(command, "vm is still running on host", false);
@@ -59,7 +59,7 @@ public final class LibvirtStopCommandWrapper extends CommandWrapper<StopCommand,
         }
 
         try {
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
 
             final List<DiskDef> disks = libvirtComputingResource.getDisks(conn, vmName);
             final List<InterfaceDef> ifaces = libvirtComputingResource.getInterfaces(conn, vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
index 4ce14f2..b3016fa 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
@@ -45,9 +45,9 @@ public final class LibvirtUnPlugNicCommandWrapper extends CommandWrapper<UnPlugN
         final String vmName = command.getVmName();
         Domain vm = null;
         try {
-            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
 
-            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             vm = libvirtComputingResource.getDomain(conn, vmName);
             final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
new file mode 100644
index 0000000..5930bf0
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -0,0 +1,68 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.naming.ConfigurationException;
+
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
+import com.cloud.storage.StorageLayer;
+import com.cloud.storage.template.Processor;
+import com.cloud.storage.template.QCOW2Processor;
+import com.cloud.storage.template.TemplateLocation;
+
+/**
+ * This class is used to wrap the calls to several static methods. By doing so, we make easier to mock this class
+ * and the methods wrapped here.
+ *
+ * Please do not instantiate this class directly, but inject it using the {@code @Inject} annotation.
+ */
+public class LibvirtUtilitiesHelper {
+
+    public Connect getConnectionByVmName(final String vmName) throws LibvirtException {
+        return LibvirtConnection.getConnectionByVmName(vmName);
+    }
+
+    public Connect getConnection() throws LibvirtException {
+        return LibvirtConnection.getConnection();
+    }
+
+    public TemplateLocation buildTemplateLocation(final StorageLayer storage, final String templatePath) {
+        final TemplateLocation location = new TemplateLocation(storage, templatePath);
+        return location;
+    }
+
+    public Processor buildQCOW2Processor(final StorageLayer storage) throws ConfigurationException {
+        final Map<String, Object> params = new HashMap<String, Object>();
+        params.put(StorageLayer.InstanceConfigKey, storage);
+
+        final Processor qcow2Processor = new QCOW2Processor();
+        qcow2Processor.configure("QCOW2 Processor", params);
+
+        return qcow2Processor;
+    }
+
+    public String buildTemplateUUIDName() {
+        return UUID.randomUUID().toString();
+    }
+}
\ No newline at end of file


[19/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/885b9e45/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 5f9c50a..1504f70 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -133,7 +133,7 @@ import com.cloud.exception.InternalErrorException;
 import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
-import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtConnectionWrapper;
+import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper;
 import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
@@ -475,14 +475,14 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testStopCommandNoCheck() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final StopCommand command = new StopCommand(vmName, false, false);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -496,7 +496,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -505,15 +505,15 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testStopCommandCheck() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Domain domain = Mockito.mock(Domain.class);
 
         final String vmName = "Test";
         final StopCommand command = new StopCommand(vmName, false, true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
             when(conn.domainLookupByName(command.getVmName())).thenReturn(domain);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
@@ -528,7 +528,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(2)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(2)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -537,7 +537,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testGetVmStatsCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
@@ -546,9 +546,9 @@ public class LibvirtComputingResourceTest {
 
         final GetVmStatsCommand command = new GetVmStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -561,7 +561,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -570,7 +570,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testGetVmDiskStatsCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
@@ -579,9 +579,9 @@ public class LibvirtComputingResourceTest {
 
         final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnection()).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnection()).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -594,7 +594,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnection();
+            verify(libvirtUtilitiesHelper, times(1)).getConnection();
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -604,7 +604,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testGetVmDiskStatsCommandException() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
@@ -613,9 +613,9 @@ public class LibvirtComputingResourceTest {
 
         final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnection()).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnection()).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -628,7 +628,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnection();
+            verify(libvirtUtilitiesHelper, times(1)).getConnection();
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -637,14 +637,14 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testRebootCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final RebootCommand command = new RebootCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -657,7 +657,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -667,15 +667,15 @@ public class LibvirtComputingResourceTest {
     public void testRebootRouterCommand() {
         final VirtualRoutingResource routingResource = Mockito.mock(VirtualRoutingResource.class);
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final RebootRouterCommand command = new RebootRouterCommand(vmName, "192.168.0.10");
 
         when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource);
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -690,7 +690,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -700,16 +700,16 @@ public class LibvirtComputingResourceTest {
     public void testRebootRouterCommandConnect() {
         final VirtualRoutingResource routingResource = Mockito.mock(VirtualRoutingResource.class);
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final RebootRouterCommand command = new RebootRouterCommand(vmName, "192.168.0.10");
 
         when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource);
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(routingResource.connect(command.getPrivateIpAddress())).thenReturn(true);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -723,7 +723,7 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getVirtRouterResource();
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -758,7 +758,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testPrepareForMigrationCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
         final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
@@ -768,9 +768,9 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -792,7 +792,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -806,7 +806,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testPrepareForMigrationCommandMigration() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
         final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
@@ -816,9 +816,9 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -841,7 +841,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -855,7 +855,7 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testPrepareForMigrationCommandLibvirtException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
         final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
@@ -864,9 +864,9 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -885,7 +885,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -898,7 +898,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testPrepareForMigrationCommandURISyntaxException() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
         final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
@@ -908,9 +908,9 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -939,7 +939,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -954,7 +954,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testPrepareForMigrationCommandInternalErrorException() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final VirtualMachineTO vm = Mockito.mock(VirtualMachineTO.class);
         final KVMStoragePoolManager storagePoolManager = Mockito.mock(KVMStoragePoolManager.class);
@@ -963,9 +963,9 @@ public class LibvirtComputingResourceTest {
 
         final PrepareForMigrationCommand command = new PrepareForMigrationCommand(vm);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vm.getName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vm.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -991,7 +991,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vm.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vm.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1007,7 +1007,7 @@ public class LibvirtComputingResourceTest {
         // Will keep it expecting the UnsatisfiedLinkError and fix later.
 
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final String destIp = "10.1.1.100";
@@ -1017,9 +1017,9 @@ public class LibvirtComputingResourceTest {
 
         final MigrateCommand command = new MigrateCommand(vmName, destIp, isWindows, vmTO, executeInSequence );
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1058,7 +1058,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1109,14 +1109,14 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testCheckVirtualMachineCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1131,7 +1131,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1141,14 +1141,14 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testExceptionCheckVirtualMachineCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final CheckVirtualMachineCommand command = new CheckVirtualMachineCommand(vmName);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1163,7 +1163,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1183,14 +1183,14 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testAttachIsoCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1203,7 +1203,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1212,14 +1212,14 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testAttachIsoCommandLibvirtException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1232,7 +1232,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1241,14 +1241,14 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testAttachIsoCommandURISyntaxException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(URISyntaxException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(URISyntaxException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1261,7 +1261,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1270,14 +1270,14 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testAttachIsoCommandInternalErrorException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String vmName = "Test";
         final AttachIsoCommand command = new AttachIsoCommand(vmName, "/path", true);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1290,7 +1290,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1299,7 +1299,7 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testAttachVolumeCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final boolean attach = true;
         final boolean managed = true;
@@ -1316,9 +1316,9 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1335,7 +1335,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1344,7 +1344,7 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testAttachVolumeCommandLibvirtException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final boolean attach = true;
         final boolean managed = true;
@@ -1361,9 +1361,9 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1380,7 +1380,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1389,7 +1389,7 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testAttachVolumeCommandInternalErrorException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final boolean attach = true;
         final boolean managed = true;
@@ -1406,9 +1406,9 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1425,7 +1425,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1467,13 +1467,13 @@ public class LibvirtComputingResourceTest {
     @Test
     public void testGetVncPortCommand() {
         final Connect conn = Mockito.mock(Connect.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1486,7 +1486,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1495,13 +1495,13 @@ public class LibvirtComputingResourceTest {
     @SuppressWarnings("unchecked")
     @Test
     public void testGetVncPortCommandLibvirtException() {
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final GetVncPortCommand command = new GetVncPortCommand(1l, "host");
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -1514,7 +1514,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2242,12 +2242,12 @@ public class LibvirtComputingResourceTest {
 
         final NetworkRulesVmSecondaryIpCommand command = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, action );
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2260,7 +2260,7 @@ public class LibvirtComputingResourceTest {
         assertTrue(answer.getResult());
 
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2278,11 +2278,11 @@ public class LibvirtComputingResourceTest {
 
         final NetworkRulesVmSecondaryIpCommand command = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, action );
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2293,7 +2293,7 @@ public class LibvirtComputingResourceTest {
         assertFalse(answer.getResult());
 
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2307,12 +2307,12 @@ public class LibvirtComputingResourceTest {
 
         final NetworkRulesSystemVmCommand command = new NetworkRulesSystemVmCommand(vmName, type);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2325,7 +2325,7 @@ public class LibvirtComputingResourceTest {
         assertTrue(answer.getResult());
 
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2341,11 +2341,11 @@ public class LibvirtComputingResourceTest {
 
         final NetworkRulesSystemVmCommand command = new NetworkRulesSystemVmCommand(vmName, type);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2357,7 +2357,7 @@ public class LibvirtComputingResourceTest {
         assertFalse(answer.getResult());
 
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2799,17 +2799,17 @@ public class LibvirtComputingResourceTest {
 
         final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
         final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2832,7 +2832,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2851,17 +2851,17 @@ public class LibvirtComputingResourceTest {
 
         final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
         final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2893,7 +2893,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2913,17 +2913,17 @@ public class LibvirtComputingResourceTest {
 
         final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
 
         final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
         nics.add(interfaceDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2936,7 +2936,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -2950,7 +2950,7 @@ public class LibvirtComputingResourceTest {
 
         final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
         final Domain vm = Mockito.mock(Domain.class);
 
@@ -2958,7 +2958,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -2968,7 +2968,7 @@ public class LibvirtComputingResourceTest {
         when(nic.getMac()).thenReturn("00:00:00:00");
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
             when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
@@ -2982,7 +2982,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
@@ -2997,7 +2997,7 @@ public class LibvirtComputingResourceTest {
 
         final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
         final Domain vm = Mockito.mock(Domain.class);
         final VifDriver vifDriver = Mockito.mock(VifDriver.class);
@@ -3007,7 +3007,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3017,7 +3017,7 @@ public class LibvirtComputingResourceTest {
         when(nic.getMac()).thenReturn("00:00:00:01");
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
             when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
 
             when(libvirtComputingResource.getVifDriver(nic.getType())).thenReturn(vifDriver);
@@ -3042,7 +3042,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
             verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType());
             verify(vifDriver, times(1)).plug(nic, "Other PV", "");
@@ -3062,12 +3062,12 @@ public class LibvirtComputingResourceTest {
 
         final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3080,7 +3080,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3095,7 +3095,7 @@ public class LibvirtComputingResourceTest {
 
         final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
         final Domain vm = Mockito.mock(Domain.class);
         final VifDriver vifDriver = Mockito.mock(VifDriver.class);
@@ -3104,7 +3104,7 @@ public class LibvirtComputingResourceTest {
         final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
         nics.add(intDef);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3114,7 +3114,7 @@ public class LibvirtComputingResourceTest {
         when(nic.getMac()).thenReturn("00:00:00:01");
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
             when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
 
             when(libvirtComputingResource.getVifDriver(nic.getType())).thenReturn(vifDriver);
@@ -3135,7 +3135,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
             verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType());
             verify(vifDriver, times(1)).plug(nic, "Other PV", "");
@@ -3153,7 +3153,7 @@ public class LibvirtComputingResourceTest {
 
         final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
         final Domain vm = Mockito.mock(Domain.class);
         final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
@@ -3166,7 +3166,7 @@ public class LibvirtComputingResourceTest {
         final List<VifDriver> drivers = new ArrayList<VifDriver>();
         drivers.add(vifDriver);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         when(intDef.getDevName()).thenReturn("eth0");
@@ -3176,7 +3176,7 @@ public class LibvirtComputingResourceTest {
         when(nic.getMac()).thenReturn("00:00:00:00");
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
             when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
 
             when(interfaceDef.toString()).thenReturn("Interface");
@@ -3200,7 +3200,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
             verify(libvirtComputingResource, times(1)).getAllVifDrivers();
         } catch (final LibvirtException e) {
@@ -3215,7 +3215,7 @@ public class LibvirtComputingResourceTest {
 
         final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final Connect conn = Mockito.mock(Connect.class);
         final Domain vm = Mockito.mock(Domain.class);
 
@@ -3225,11 +3225,11 @@ public class LibvirtComputingResourceTest {
         final List<VifDriver> drivers = new ArrayList<VifDriver>();
         drivers.add(vifDriver);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
         when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
             when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
@@ -3243,7 +3243,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
             verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
@@ -3258,12 +3258,12 @@ public class LibvirtComputingResourceTest {
 
         final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3276,7 +3276,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3468,13 +3468,13 @@ public class LibvirtComputingResourceTest {
 
         final ManageSnapshotCommand command = new ManageSnapshotCommand(snapshotId, volumePath, pool, preSnapshotPath, snapshotName, vmName);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         //final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3487,7 +3487,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3519,13 +3519,13 @@ public class LibvirtComputingResourceTest {
 
         final BackupSnapshotCommand command = new BackupSnapshotCommand(secondaryStorageUrl, dcId, accountId, volumeId, snapshotId, secHostId, volumePath, pool, snapshotUuid, snapshotName, prevSnapshotUuid, prevBackupUuid, isVolumeInactive, vmName, wait);
 
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         //final Connect conn = Mockito.mock(Connect.class);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
 
         try {
-            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+            when(libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3538,7 +3538,7 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
-            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(command.getVmName());
         } catch (final LibvirtException e) {
             fail(e.getMessage());
         }
@@ -3569,7 +3569,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
         final StorageLayer storage = Mockito.mock(StorageLayer.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final TemplateLocation location = Mockito.mock(TemplateLocation.class);
         final Processor qcow2Processor = Mockito.mock(Processor.class);
         final FormatInfo info = Mockito.mock(FormatInfo.class);
@@ -3593,12 +3593,12 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
-        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
 
         try {
-            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
             when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
         } catch (final ConfigurationException e) {
             fail(e.getMessage());
@@ -3643,7 +3643,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
         final StorageLayer storage = Mockito.mock(StorageLayer.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final TemplateLocation location = Mockito.mock(TemplateLocation.class);
         final Processor qcow2Processor = Mockito.mock(Processor.class);
         final FormatInfo info = Mockito.mock(FormatInfo.class);
@@ -3667,12 +3667,12 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
-        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
 
         try {
-            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenThrow(ConfigurationException.class);
+            when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenThrow(ConfigurationException.class);
             when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
         } catch (final ConfigurationException e) {
             fail(e.getMessage());
@@ -3717,7 +3717,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
         final StorageLayer storage = Mockito.mock(StorageLayer.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final TemplateLocation location = Mockito.mock(TemplateLocation.class);
         final Processor qcow2Processor = Mockito.mock(Processor.class);
 
@@ -3740,12 +3740,12 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
-        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
 
         try {
-            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
             when(qcow2Processor.process(tmplPath, null, tmplName)).thenThrow(InternalErrorException.class);
         } catch (final ConfigurationException e) {
             fail(e.getMessage());
@@ -3790,7 +3790,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
         final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
         final StorageLayer storage = Mockito.mock(StorageLayer.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
         final TemplateLocation location = Mockito.mock(TemplateLocation.class);
         final Processor qcow2Processor = Mockito.mock(Processor.class);
         final FormatInfo info = Mockito.mock(FormatInfo.class);
@@ -3814,12 +3814,12 @@ public class LibvirtComputingResourceTest {
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
         final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
-        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
-        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
 
         try {
-            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(libvirtUtilitiesHelper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
             when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
 
             when(location.create(1, true, tmplName)).thenThrow(IOException.class);
@@ -3863,7 +3863,7 @@ public class LibvirtComputingResourceTest {
         final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
         final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
         final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
-        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
 
         final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
 
@@ -3873,8 +3873,8 @@ public class LibvirtComputingResourceTest {
         final int index = snapshotPath.lastIndexOf("/");
         snapshotPath = snapshotPath.substring(0, index);
 
-        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
-        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.buildTemplateUUIDName()).thenReturn(tmplName);
 
         when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
         when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);


[27/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtNetworkElementCommandWrapper and LibvirtStorageSubSystemCommandWrapper
  - 2 unit tests added
  - KVM hypervisor plugin with 22.2% coverage

I also refactored the StorageSubSystemCommand interface into an abstract class
  - Remove the pseudo-multiple-inheritance implementation
    - The StorageSubSystemCommand was an interface, not related to the Command class
      and its implementation were extending the Command class anyway. The whole structure is better now.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/09656ca8
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/09656ca8
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/09656ca8

Branch: refs/heads/CLOUDSTACK-8301
Commit: 09656ca84ef1afbc2603b2cd70186c52430daa5c
Parents: 08106e3
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 14:31:02 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:16 2015 +0200

----------------------------------------------------------------------
 .../storage/command/AttachCommand.java          | 13 +++----
 .../command/AttachPrimaryDataStoreCmd.java      |  7 ++--
 .../cloudstack/storage/command/CopyCommand.java | 31 ++++++++--------
 .../storage/command/CreateObjectCommand.java    |  7 ++--
 .../command/CreatePrimaryDataStoreCmd.java      | 11 +++---
 .../storage/command/DeleteCommand.java          |  7 ++--
 .../storage/command/DettachCommand.java         | 19 +++++-----
 .../storage/command/ForgetObjectCmd.java        |  9 ++---
 .../storage/command/IntroduceObjectCmd.java     |  9 ++---
 .../storage/command/SnapshotAndCopyCommand.java | 14 +++----
 .../command/StorageSubSystemCommand.java        |  8 ++--
 .../kvm/resource/LibvirtComputingResource.java  |  9 ++---
 .../LibvirtNetworkElementCommandWrapper.java    | 35 ++++++++++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  5 +++
 .../LibvirtStorageSubSystemCommandWrapper.java  | 36 ++++++++++++++++++
 .../resource/LibvirtComputingResourceTest.java  | 39 ++++++++++++++++++++
 16 files changed, 182 insertions(+), 77 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/AttachCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/AttachCommand.java b/core/src/org/apache/cloudstack/storage/command/AttachCommand.java
index 795deb2..34aaac9 100644
--- a/core/src/org/apache/cloudstack/storage/command/AttachCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/AttachCommand.java
@@ -19,15 +19,14 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DiskTO;
 
-public final class AttachCommand extends Command implements StorageSubSystemCommand {
+public final class AttachCommand extends StorageSubSystemCommand {
     private DiskTO disk;
     private String vmName;
-    private boolean inSeq = false;
+    private boolean inSeq;
 
-    public AttachCommand(DiskTO disk, String vmName) {
+    public AttachCommand(final DiskTO disk, final String vmName) {
         super();
         this.disk = disk;
         this.vmName = vmName;
@@ -42,7 +41,7 @@ public final class AttachCommand extends Command implements StorageSubSystemComm
         return disk;
     }
 
-    public void setDisk(DiskTO disk) {
+    public void setDisk(final DiskTO disk) {
         this.disk = disk;
     }
 
@@ -50,12 +49,12 @@ public final class AttachCommand extends Command implements StorageSubSystemComm
         return vmName;
     }
 
-    public void setVmName(String vmName) {
+    public void setVmName(final String vmName) {
         this.vmName = vmName;
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
         this.inSeq = inSeq;
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java b/core/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java
index 4a72c97..9f4d14e 100644
--- a/core/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java
+++ b/core/src/org/apache/cloudstack/storage/command/AttachPrimaryDataStoreCmd.java
@@ -19,17 +19,16 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 
-public final class AttachPrimaryDataStoreCmd extends Command implements StorageSubSystemCommand {
+public final class AttachPrimaryDataStoreCmd extends StorageSubSystemCommand {
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 
     private final String dataStore;
 
-    public AttachPrimaryDataStoreCmd(String uri) {
+    public AttachPrimaryDataStoreCmd(final String uri) {
         super();
         dataStore = uri;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
index cfede14..f1895a4 100644
--- a/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/CopyCommand.java
@@ -22,10 +22,9 @@ package org.apache.cloudstack.storage.command;
 import java.util.HashMap;
 import java.util.Map;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DataTO;
 
-public final class CopyCommand extends Command implements StorageSubSystemCommand {
+public final class CopyCommand extends StorageSubSystemCommand {
     private DataTO srcTO;
     private DataTO destTO;
     private DataTO cacheTO;
@@ -33,28 +32,28 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
     private Map<String, String> options = new HashMap<String, String>();
     private Map<String, String> options2 = new HashMap<String, String>();
 
-    public CopyCommand(DataTO srcData, DataTO destData, int timeout, boolean executeInSequence) {
+    public CopyCommand(final DataTO srcData, final DataTO destData, final int timeout, final boolean executeInSequence) {
         super();
-        this.srcTO = srcData;
-        this.destTO = destData;
-        this.setWait(timeout);
+        srcTO = srcData;
+        destTO = destData;
+        setWait(timeout);
         this.executeInSequence = executeInSequence;
     }
 
     public DataTO getDestTO() {
-        return this.destTO;
+        return destTO;
     }
 
-    public void setSrcTO(DataTO srcTO) {
+    public void setSrcTO(final DataTO srcTO) {
         this.srcTO = srcTO;
     }
 
-    public void setDestTO(DataTO destTO) {
+    public void setDestTO(final DataTO destTO) {
         this.destTO = destTO;
     }
 
     public DataTO getSrcTO() {
-        return this.srcTO;
+        return srcTO;
     }
 
     @Override
@@ -66,15 +65,15 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
         return cacheTO;
     }
 
-    public void setCacheTO(DataTO cacheTO) {
+    public void setCacheTO(final DataTO cacheTO) {
         this.cacheTO = cacheTO;
     }
 
     public int getWaitInMillSeconds() {
-        return this.getWait() * 1000;
+        return getWait() * 1000;
     }
 
-    public void setOptions(Map<String, String> options) {
+    public void setOptions(final Map<String, String> options) {
         this.options = options;
     }
 
@@ -82,7 +81,7 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
         return options;
     }
 
-    public void setOptions2(Map<String, String> options2) {
+    public void setOptions2(final Map<String, String> options2) {
         this.options2 = options2;
     }
 
@@ -91,7 +90,7 @@ public final class CopyCommand extends Command implements StorageSubSystemComman
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
-        this.executeInSequence = inSeq;
+    public void setExecuteInSequence(final boolean inSeq) {
+        executeInSequence = inSeq;
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java b/core/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java
index 6079a95..88a582d 100644
--- a/core/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/CreateObjectCommand.java
@@ -19,13 +19,12 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DataTO;
 
-public final class CreateObjectCommand extends Command implements StorageSubSystemCommand {
+public final class CreateObjectCommand extends StorageSubSystemCommand {
     private DataTO data;
 
-    public CreateObjectCommand(DataTO obj) {
+    public CreateObjectCommand(final DataTO obj) {
         super();
         data = obj;
     }
@@ -44,7 +43,7 @@ public final class CreateObjectCommand extends Command implements StorageSubSyst
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java b/core/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java
index 0017dd2..b1f32a9 100644
--- a/core/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java
+++ b/core/src/org/apache/cloudstack/storage/command/CreatePrimaryDataStoreCmd.java
@@ -19,18 +19,17 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 
-public final class CreatePrimaryDataStoreCmd extends Command implements StorageSubSystemCommand {
+public final class CreatePrimaryDataStoreCmd extends StorageSubSystemCommand {
     private final String dataStore;
 
-    public CreatePrimaryDataStoreCmd(String uri) {
+    public CreatePrimaryDataStoreCmd(final String uri) {
         super();
-        this.dataStore = uri;
+        dataStore = uri;
     }
 
     public String getDataStore() {
-        return this.dataStore;
+        return dataStore;
     }
 
     @Override
@@ -39,7 +38,7 @@ public final class CreatePrimaryDataStoreCmd extends Command implements StorageS
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/DeleteCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/DeleteCommand.java b/core/src/org/apache/cloudstack/storage/command/DeleteCommand.java
index 5683f41..6f82fa9 100644
--- a/core/src/org/apache/cloudstack/storage/command/DeleteCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/DeleteCommand.java
@@ -19,13 +19,12 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DataTO;
 
-public final class DeleteCommand extends Command implements StorageSubSystemCommand {
+public final class DeleteCommand extends StorageSubSystemCommand {
     private DataTO data;
 
-    public DeleteCommand(DataTO data) {
+    public DeleteCommand(final DataTO data) {
         super();
         this.data = data;
     }
@@ -44,7 +43,7 @@ public final class DeleteCommand extends Command implements StorageSubSystemComm
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/DettachCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/DettachCommand.java b/core/src/org/apache/cloudstack/storage/command/DettachCommand.java
index b699862..8d89dd5 100644
--- a/core/src/org/apache/cloudstack/storage/command/DettachCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/DettachCommand.java
@@ -19,10 +19,9 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DiskTO;
 
-public class DettachCommand extends Command implements StorageSubSystemCommand {
+public class DettachCommand extends StorageSubSystemCommand {
     private DiskTO disk;
     private String vmName;
     private boolean _managed;
@@ -30,7 +29,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
     private String _storageHost;
     private int _storagePort;
 
-    public DettachCommand(DiskTO disk, String vmName) {
+    public DettachCommand(final DiskTO disk, final String vmName) {
         super();
         this.disk = disk;
         this.vmName = vmName;
@@ -45,7 +44,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
         return disk;
     }
 
-    public void setDisk(DiskTO disk) {
+    public void setDisk(final DiskTO disk) {
         this.disk = disk;
     }
 
@@ -53,11 +52,11 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
         return vmName;
     }
 
-    public void setVmName(String vmName) {
+    public void setVmName(final String vmName) {
         this.vmName = vmName;
     }
 
-    public void setManaged(boolean managed) {
+    public void setManaged(final boolean managed) {
         _managed = managed;
     }
 
@@ -65,7 +64,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
         return _managed;
     }
 
-    public void set_iScsiName(String iScsiName) {
+    public void set_iScsiName(final String iScsiName) {
         _iScsiName = iScsiName;
     }
 
@@ -73,7 +72,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
         return _iScsiName;
     }
 
-    public void setStorageHost(String storageHost) {
+    public void setStorageHost(final String storageHost) {
         _storageHost = storageHost;
     }
 
@@ -81,7 +80,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
         return _storageHost;
     }
 
-    public void setStoragePort(int storagePort) {
+    public void setStoragePort(final int storagePort) {
         _storagePort = storagePort;
     }
 
@@ -90,7 +89,7 @@ public class DettachCommand extends Command implements StorageSubSystemCommand {
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/ForgetObjectCmd.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/ForgetObjectCmd.java b/core/src/org/apache/cloudstack/storage/command/ForgetObjectCmd.java
index 9bcaa62..c47ee88 100644
--- a/core/src/org/apache/cloudstack/storage/command/ForgetObjectCmd.java
+++ b/core/src/org/apache/cloudstack/storage/command/ForgetObjectCmd.java
@@ -19,13 +19,12 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DataTO;
 
-public class ForgetObjectCmd extends Command implements StorageSubSystemCommand {
-    private DataTO dataTO;
+public class ForgetObjectCmd extends StorageSubSystemCommand {
+    private final DataTO dataTO;
 
-    public ForgetObjectCmd(DataTO data) {
+    public ForgetObjectCmd(final DataTO data) {
         dataTO = data;
     }
 
@@ -39,7 +38,7 @@ public class ForgetObjectCmd extends Command implements StorageSubSystemCommand
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/IntroduceObjectCmd.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/IntroduceObjectCmd.java b/core/src/org/apache/cloudstack/storage/command/IntroduceObjectCmd.java
index c20c50f..8c3bc5e 100644
--- a/core/src/org/apache/cloudstack/storage/command/IntroduceObjectCmd.java
+++ b/core/src/org/apache/cloudstack/storage/command/IntroduceObjectCmd.java
@@ -19,13 +19,12 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
 import com.cloud.agent.api.to.DataTO;
 
-public class IntroduceObjectCmd extends Command implements StorageSubSystemCommand {
-    private DataTO dataTO;
+public class IntroduceObjectCmd extends StorageSubSystemCommand {
+    private final DataTO dataTO;
 
-    public IntroduceObjectCmd(DataTO dataTO) {
+    public IntroduceObjectCmd(final DataTO dataTO) {
         this.dataTO = dataTO;
     }
 
@@ -39,7 +38,7 @@ public class IntroduceObjectCmd extends Command implements StorageSubSystemComma
     }
 
     @Override
-    public void setExecuteInSequence(boolean inSeq) {
+    public void setExecuteInSequence(final boolean inSeq) {
 
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/SnapshotAndCopyCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/SnapshotAndCopyCommand.java b/core/src/org/apache/cloudstack/storage/command/SnapshotAndCopyCommand.java
index c599916..0a1a84d 100644
--- a/core/src/org/apache/cloudstack/storage/command/SnapshotAndCopyCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/SnapshotAndCopyCommand.java
@@ -19,18 +19,16 @@
 
 package org.apache.cloudstack.storage.command;
 
-import com.cloud.agent.api.Command;
-
 import java.util.Map;
 
-public final class SnapshotAndCopyCommand extends Command implements StorageSubSystemCommand {
-    private String _uuidOfSourceVdi;
-    private Map<String, String> _sourceDetails;
-    private Map<String, String> _destDetails;
+public final class SnapshotAndCopyCommand extends StorageSubSystemCommand {
+    private final String _uuidOfSourceVdi;
+    private final Map<String, String> _sourceDetails;
+    private final Map<String, String> _destDetails;
 
     private boolean _executeInSequence = true;
 
-    public SnapshotAndCopyCommand(String uuidOfSourceVdi, Map<String, String> sourceDetails, Map<String, String> destDetails) {
+    public SnapshotAndCopyCommand(final String uuidOfSourceVdi, final Map<String, String> sourceDetails, final Map<String, String> destDetails) {
         _uuidOfSourceVdi = uuidOfSourceVdi;
         _sourceDetails = sourceDetails;
         _destDetails = destDetails;
@@ -49,7 +47,7 @@ public final class SnapshotAndCopyCommand extends Command implements StorageSubS
     }
 
     @Override
-    public void setExecuteInSequence(boolean executeInSequence) {
+    public void setExecuteInSequence(final boolean executeInSequence) {
         _executeInSequence = executeInSequence;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java b/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
index 5893f62..6507bb0 100644
--- a/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
@@ -19,6 +19,8 @@
 
 package org.apache.cloudstack.storage.command;
 
-public interface StorageSubSystemCommand {
-    void setExecuteInSequence(boolean inSeq);
-}
+import com.cloud.agent.api.Command;
+
+public abstract class StorageSubSystemCommand extends Command {
+    abstract void setExecuteInSequence(boolean inSeq);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index e98e945..d7b4b18 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -45,7 +45,6 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
-import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
 import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
 import org.apache.cloudstack.storage.to.VolumeObjectTO;
 import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
@@ -408,6 +407,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _resizeVolumePath;
     }
 
+    public StorageSubsystemCommandHandler getStorageHandler() {
+        return storageHandler;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1257,10 +1260,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         try {
             if (cmd instanceof StartCommand) {
                 return execute((StartCommand)cmd);
-            } else if (cmd instanceof NetworkElementCommand) {
-                return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
-            } else if (cmd instanceof StorageSubSystemCommand) {
-                return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
             } else {
                 s_logger.warn("Unsupported command ");
                 return Answer.createUnsupportedCommandAnswer(cmd);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkElementCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkElementCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkElementCommandWrapper.java
new file mode 100644
index 0000000..3046b09
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkElementCommandWrapper.java
@@ -0,0 +1,35 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.routing.NetworkElementCommand;
+import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtNetworkElementCommandWrapper extends CommandWrapper<NetworkElementCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final NetworkElementCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
+        return virtRouterResource.executeRequest(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 363981d..e8b7b8c 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -20,6 +20,8 @@ package com.cloud.hypervisor.kvm.resource.wrapper;
 
 import java.util.Hashtable;
 
+import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
+
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
@@ -70,6 +72,7 @@ import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
@@ -150,6 +153,8 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
         linbvirtCommands.put(PvlanSetupCommand.class, new LibvirtPvlanSetupCommandWrapper());
         linbvirtCommands.put(ResizeVolumeCommand.class, new LibvirtResizeVolumeCommandWrapper());
+        linbvirtCommands.put(NetworkElementCommand.class, new LibvirtNetworkElementCommandWrapper());
+        linbvirtCommands.put(StorageSubSystemCommand.class, new LibvirtStorageSubSystemCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStorageSubSystemCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStorageSubSystemCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStorageSubSystemCommandWrapper.java
new file mode 100644
index 0000000..d2044ed
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStorageSubSystemCommandWrapper.java
@@ -0,0 +1,36 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.resource.StorageSubsystemCommandHandler;
+
+public final class LibvirtStorageSubSystemCommandWrapper extends CommandWrapper<StorageSubSystemCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final StorageSubSystemCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final StorageSubsystemCommandHandler handler = libvirtComputingResource.getStorageHandler();
+        return handler.handleStorageCommands(command);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/09656ca8/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 4e8d7bd..140262f 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -46,6 +46,8 @@ import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
 
+import org.apache.cloudstack.storage.command.AttachAnswer;
+import org.apache.cloudstack.storage.command.AttachCommand;
 import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
 import org.apache.commons.lang.SystemUtils;
 import org.junit.Assert;
@@ -76,6 +78,8 @@ import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
+import com.cloud.agent.api.CheckRouterAnswer;
+import com.cloud.agent.api.CheckRouterCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
@@ -152,6 +156,7 @@ import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageLayer;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.Volume;
+import com.cloud.storage.resource.StorageSubsystemCommandHandler;
 import com.cloud.storage.template.Processor;
 import com.cloud.storage.template.Processor.FormatInfo;
 import com.cloud.storage.template.TemplateLocation;
@@ -4506,4 +4511,38 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
     }
+
+    @Test
+    public void testNetworkElementCommand() {
+        final CheckRouterCommand command = new CheckRouterCommand();
+
+        final VirtualRoutingResource virtRouterResource = Mockito.mock(VirtualRoutingResource.class);
+        when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
+
+        when(virtRouterResource.executeRequest(command)).thenReturn(new CheckRouterAnswer(command, "mock_resource"));
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @Test
+    public void testStorageSubSystemCommand() {
+        final DiskTO disk = Mockito.mock(DiskTO.class);
+        final String vmName = "Test";
+        final AttachCommand command = new AttachCommand(disk, vmName);
+
+        final StorageSubsystemCommandHandler handler = Mockito.mock(StorageSubsystemCommandHandler.class);
+        when(libvirtComputingResource.getStorageHandler()).thenReturn(handler);
+
+        when(handler.handleStorageCommands(command)).thenReturn(new AttachAnswer(disk));
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
 }
\ No newline at end of file


[15/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtBackupSnapshotCommandWrapper, LibvirtCreatePrivateTemplateFromVolumeCommandWrapper and LibvirtManageSnapshotCommandWrapper
  - 3 unit tests added
  - KVM hypervisor plugin with 18.3% coverage

Less tests added to those classes because the code is quite complex and way too long.
The tests added are just covering the new flow, to make sure it works fine. I will come back to those classes later.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/bcf78d3b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bcf78d3b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bcf78d3b

Branch: refs/heads/CLOUDSTACK-8301
Commit: bcf78d3b4304800d9a60db72742fb169c470093b
Parents: 52d9f0c
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue May 5 11:48:55 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:13 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 402 +------------------
 .../LibvirtBackupSnapshotCommandWrapper.java    | 204 ++++++++++
 ...PrivateTemplateFromVolumeCommandWrapper.java | 176 ++++++++
 .../LibvirtManageSnapshotCommandWrapper.java    | 163 ++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   6 +
 .../resource/LibvirtComputingResourceTest.java  | 137 ++++++-
 6 files changed, 699 insertions(+), 389 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 3c40c90..4e8b4cf 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -16,26 +16,20 @@
 // under the License.
 package com.cloud.hypervisor.kvm.resource;
 
-import java.io.BufferedOutputStream;
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.Reader;
 import java.net.InetAddress;
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Calendar;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -54,10 +48,7 @@ import javax.naming.ConfigurationException;
 import org.apache.cloudstack.storage.command.StorageSubSystemCommand;
 import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
 import org.apache.cloudstack.storage.to.VolumeObjectTO;
-import org.apache.cloudstack.utils.qemu.QemuImg;
 import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
-import org.apache.cloudstack.utils.qemu.QemuImgException;
-import org.apache.cloudstack.utils.qemu.QemuImgFile;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.log4j.Logger;
@@ -67,26 +58,14 @@ import org.libvirt.DomainBlockStats;
 import org.libvirt.DomainInfo;
 import org.libvirt.DomainInfo.DomainState;
 import org.libvirt.DomainInterfaceStats;
-import org.libvirt.DomainSnapshot;
 import org.libvirt.LibvirtException;
 import org.libvirt.NodeInfo;
 import org.libvirt.StorageVol;
 
-import com.ceph.rados.IoCTX;
-import com.ceph.rados.Rados;
-import com.ceph.rados.RadosException;
-import com.ceph.rbd.Rbd;
-import com.ceph.rbd.RbdException;
-import com.ceph.rbd.RbdImage;
 import com.cloud.agent.api.Answer;
-import com.cloud.agent.api.BackupSnapshotAnswer;
-import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
-import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
-import com.cloud.agent.api.ManageSnapshotAnswer;
-import com.cloud.agent.api.ManageSnapshotCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
@@ -156,7 +135,6 @@ import com.cloud.resource.ServerResource;
 import com.cloud.resource.ServerResourceBase;
 import com.cloud.storage.JavaStorageLayer;
 import com.cloud.storage.Storage;
-import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StorageLayer;
 import com.cloud.storage.Volume;
@@ -234,7 +212,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud";
 
     private String _mountPoint = "/mnt";
-    StorageLayer _storage;
+    private StorageLayer _storage;
     private KVMStoragePoolManager _storagePoolMgr;
 
     private VifDriver _defaultVifDriver;
@@ -276,9 +254,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     private final Map <String, String> _pifs = new HashMap<String, String>();
     private final Map<String, VmStats> _vmStats = new ConcurrentHashMap<String, VmStats>();
 
-    protected static final MessageFormat SnapshotXML = new MessageFormat("   <domainsnapshot>" + "       <name>{0}</name>" + "          <domain>"
-            + "            <uuid>{1}</uuid>" + "        </domain>" + "    </domainsnapshot>");
-
     protected static final HashMap<DomainState, PowerState> s_powerStatesTable;
     static {
         s_powerStatesTable = new HashMap<DomainState, PowerState>();
@@ -414,6 +389,22 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _monitor;
     }
 
+    public StorageLayer getStorage() {
+        return _storage;
+    }
+
+    public String createTmplPath() {
+        return _createTmplPath;
+    }
+
+    public int getCmdsTimeout() {
+        return _cmdsTimeout;
+    }
+
+    public String manageSnapshotPath() {
+        return _manageSnapshotPath;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1261,13 +1252,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
-                return execute((CreatePrivateTemplateFromVolumeCommand)cmd);
-            } else if (cmd instanceof ManageSnapshotCommand) {
-                return execute((ManageSnapshotCommand)cmd);
-            } else if (cmd instanceof BackupSnapshotCommand) {
-                return execute((BackupSnapshotCommand)cmd);
-            } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
+            if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                 return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
             } else if (cmd instanceof StartCommand) {
                 return execute((StartCommand)cmd);
@@ -1899,248 +1884,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new ExecutionResult(true, null);
     }
 
-    protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) {
-        final String snapshotName = cmd.getSnapshotName();
-        final String snapshotPath = cmd.getSnapshotPath();
-        final String vmName = cmd.getVmName();
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(vmName);
-            DomainState state = null;
-            Domain vm = null;
-            if (vmName != null) {
-                try {
-                    vm = getDomain(conn, cmd.getVmName());
-                    state = vm.getInfo().state;
-                } catch (final LibvirtException e) {
-                    s_logger.trace("Ignoring libvirt error.", e);
-                }
-            }
-
-            final KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd.getPool().getType(), cmd.getPool().getUuid());
-
-            final KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(cmd.getVolumePath());
-            if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryPool.isExternalSnapshot()) {
-                final String vmUuid = vm.getUUIDString();
-                final Object[] args = new Object[] {snapshotName, vmUuid};
-                final String snapshot = SnapshotXML.format(args);
-                s_logger.debug(snapshot);
-                if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
-                    vm.snapshotCreateXML(snapshot);
-                } else {
-                    final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
-                    snap.delete(0);
-                }
-
-                /*
-                 * libvirt on RHEL6 doesn't handle resume event emitted from
-                 * qemu
-                 */
-                vm = getDomain(conn, cmd.getVmName());
-                state = vm.getInfo().state;
-                if (state == DomainState.VIR_DOMAIN_PAUSED) {
-                    vm.resume();
-                }
-            } else {
-                /**
-                 * For RBD we can't use libvirt to do our snapshotting or any Bash scripts.
-                 * libvirt also wants to store the memory contents of the Virtual Machine,
-                 * but that's not possible with RBD since there is no way to store the memory
-                 * contents in RBD.
-                 *
-                 * So we rely on the Java bindings for RBD to create our snapshot
-                 *
-                 * This snapshot might not be 100% consistent due to writes still being in the
-                 * memory of the Virtual Machine, but if the VM runs a kernel which supports
-                 * barriers properly (>2.6.32) this won't be any different then pulling the power
-                 * cord out of a running machine.
-                 */
-                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(disk.getName());
-
-                        if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
-                            s_logger.debug("Attempting to create RBD snapshot " + disk.getName() + "@" + snapshotName);
-                            image.snapCreate(snapshotName);
-                        } else {
-                            s_logger.debug("Attempting to remove RBD snapshot " + disk.getName() + "@" + snapshotName);
-                            image.snapRemove(snapshotName);
-                        }
-
-                        rbd.close(image);
-                        r.ioCtxDestroy(io);
-                    } catch (final Exception e) {
-                        s_logger.error("A RBD snapshot operation on " + disk.getName() + " failed. The error was: " + e.getMessage());
-                    }
-                } else {
-                    /* VM is not running, create a snapshot by ourself */
-                    final Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
-                    if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
-                        command.add("-c", disk.getPath());
-                    } else {
-                        command.add("-d", snapshotPath);
-                    }
-
-                    command.add("-n", snapshotName);
-                    final String result = command.execute();
-                    if (result != null) {
-                        s_logger.debug("Failed to manage snapshot: " + result);
-                        return new ManageSnapshotAnswer(cmd, false, "Failed to manage snapshot: " + result);
-                    }
-                }
-            }
-            return new ManageSnapshotAnswer(cmd, cmd.getSnapshotId(), disk.getPath() + File.separator + snapshotName, true, null);
-        } catch (final LibvirtException e) {
-            s_logger.debug("Failed to manage snapshot: " + e.toString());
-            return new ManageSnapshotAnswer(cmd, false, "Failed to manage snapshot: " + e.toString());
-        }
-
-    }
-
-    protected BackupSnapshotAnswer execute(final BackupSnapshotCommand cmd) {
-        final Long dcId = cmd.getDataCenterId();
-        final Long accountId = cmd.getAccountId();
-        final Long volumeId = cmd.getVolumeId();
-        final String secondaryStoragePoolUrl = cmd.getSecondaryStorageUrl();
-        final String snapshotName = cmd.getSnapshotName();
-        String snapshotDestPath = null;
-        String snapshotRelPath = null;
-        final String vmName = cmd.getVmName();
-        KVMStoragePool secondaryStoragePool = null;
-        try {
-            final Connect conn = LibvirtConnection.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(cmd.getPool().getType(), cmd.getPrimaryStoragePoolNameLabel());
-            final KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(cmd.getVolumePath());
-
-            /**
-             * 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(cmd, 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(cmd, false, e.toString(), null, true);
-                }
-            } else {
-                final Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
-                command.add("-b", snapshotDisk.getPath());
-                command.add("-n", snapshotName);
-                command.add("-p", snapshotDestPath);
-                command.add("-t", snapshotName);
-                final String result = command.execute();
-                if (result != null) {
-                    s_logger.debug("Failed to backup snaptshot: " + result);
-                    return new BackupSnapshotAnswer(cmd, false, result, null, true);
-                }
-            }
-            /* Delete the snapshot on primary */
-
-            DomainState state = null;
-            Domain vm = null;
-            if (vmName != null) {
-                try {
-                    vm = getDomain(conn, cmd.getVmName());
-                    state = vm.getInfo().state;
-                } catch (final LibvirtException e) {
-                    s_logger.trace("Ignoring libvirt error.", e);
-                }
-            }
-
-            final KVMStoragePool primaryStorage = _storagePoolMgr.getStoragePool(cmd.getPool().getType(), cmd.getPool().getUuid());
-            if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) {
-                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);
-                snap.delete(0);
-
-                /*
-                 * libvirt on RHEL6 doesn't handle resume event emitted from
-                 * qemu
-                 */
-                vm = getDomain(conn, cmd.getVmName());
-                state = vm.getInfo().state;
-                if (state == DomainState.VIR_DOMAIN_PAUSED) {
-                    vm.resume();
-                }
-            } else {
-                final Script command = new Script(_manageSnapshotPath, _cmdsTimeout, s_logger);
-                command.add("-d", snapshotDisk.getPath());
-                command.add("-n", snapshotName);
-                final String result = command.execute();
-                if (result != null) {
-                    s_logger.debug("Failed to backup snapshot: " + result);
-                    return new BackupSnapshotAnswer(cmd, false, "Failed to backup snapshot: " + result, null, true);
-                }
-            }
-        } catch (final LibvirtException e) {
-            return new BackupSnapshotAnswer(cmd, false, e.toString(), null, true);
-        } catch (final CloudRuntimeException e) {
-            return new BackupSnapshotAnswer(cmd, false, e.toString(), null, true);
-        } finally {
-            if (secondaryStoragePool != null) {
-                _storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
-            }
-        }
-        return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath + File.separator + snapshotName, true);
-    }
-
     protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) {
         final String templateFolder = cmd.getAccountId() + File.separator + cmd.getNewTemplateId();
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
@@ -2198,115 +1941,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromVolumeCommand cmd) {
-        final String secondaryStorageURL = cmd.getSecondaryStorageUrl();
-
-        KVMStoragePool secondaryStorage = null;
-        KVMStoragePool primary = null;
-        try {
-            final String templateFolder = cmd.getAccountId() + File.separator + cmd.getTemplateId() + File.separator;
-            final String templateInstallFolder = "/template/tmpl/" + templateFolder;
-
-            secondaryStorage = _storagePoolMgr.getStoragePoolByURI(secondaryStorageURL);
-
-            try {
-                primary = _storagePoolMgr.getStoragePool(cmd.getPool().getType(), cmd.getPrimaryStoragePoolNameLabel());
-            } catch (final CloudRuntimeException e) {
-                if (e.getMessage().contains("not found")) {
-                    primary =
-                            _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(),
-                                    cmd.getPool().getUserInfo(), cmd.getPool().getType());
-                } else {
-                    return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
-                }
-            }
-
-            final KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
-            final String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder;
-            _storage.mkdirs(tmpltPath);
-
-            if (primary.getType() != StoragePoolType.RBD) {
-                final Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
-                command.add("-f", disk.getPath());
-                command.add("-t", tmpltPath);
-                command.add("-n", cmd.getUniqueName() + ".qcow2");
-
-                final String result = command.execute();
-
-                if (result != null) {
-                    s_logger.debug("failed to create template: " + result);
-                    return new CreatePrivateTemplateAnswer(cmd, false, result);
-                }
-            } else {
-                s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + cmd.getUniqueName());
-
-                final QemuImgFile srcFile =
-                        new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(),
-                                primary.getAuthSecret(), disk.getPath()));
-                srcFile.setFormat(PhysicalDiskFormat.RAW);
-
-                final QemuImgFile destFile = new QemuImgFile(tmpltPath + "/" + cmd.getUniqueName() + ".qcow2");
-                destFile.setFormat(PhysicalDiskFormat.QCOW2);
-
-                final QemuImg q = new QemuImg(0);
-                try {
-                    q.convert(srcFile, destFile);
-                } catch (final QemuImgException e) {
-                    s_logger.error("Failed to create new template while converting " + srcFile.getFileName() + " to " + destFile.getFileName() + " the error was: " +
-                            e.getMessage());
-                }
-
-                final File templateProp = new File(tmpltPath + "/template.properties");
-                if (!templateProp.exists()) {
-                    templateProp.createNewFile();
-                }
-
-                String templateContent = "filename=" + cmd.getUniqueName() + ".qcow2" + System.getProperty("line.separator");
-
-                final DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
-                final Date date = new Date();
-                templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
-
-                try(FileOutputStream templFo = new FileOutputStream(templateProp);) {
-                    templFo.write(templateContent.getBytes());
-                    templFo.flush();
-                }catch(final IOException ex)
-                {
-                    s_logger.error("CreatePrivateTemplateAnswer:Exception:"+ex.getMessage());
-                }
-
-            }
-
-            final Map<String, Object> params = new HashMap<String, Object>();
-            params.put(StorageLayer.InstanceConfigKey, _storage);
-            final Processor qcow2Processor = new QCOW2Processor();
-
-            qcow2Processor.configure("QCOW2 Processor", params);
-
-            final FormatInfo info = qcow2Processor.process(tmpltPath, null, cmd.getUniqueName());
-
-            final 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 (final InternalErrorException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
-        } catch (final IOException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
-        } catch (final ConfigurationException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
-        } catch (final CloudRuntimeException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
-        } finally {
-            if (secondaryStorage != null) {
-                _storagePoolMgr.deleteStoragePool(secondaryStorage.getType(), secondaryStorage.getUuid());
-            }
-        }
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
new file mode 100644
index 0000000..afbbf73
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
@@ -0,0 +1,204 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.MessageFormat;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.Domain;
+import org.libvirt.DomainInfo.DomainState;
+import org.libvirt.DomainSnapshot;
+import org.libvirt.LibvirtException;
+
+import com.ceph.rados.IoCTX;
+import com.ceph.rados.Rados;
+import com.ceph.rados.RadosException;
+import com.ceph.rbd.Rbd;
+import com.ceph.rbd.RbdException;
+import com.ceph.rbd.RbdImage;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.BackupSnapshotAnswer;
+import com.cloud.agent.api.BackupSnapshotCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtBackupSnapshotCommandWrapper extends CommandWrapper<BackupSnapshotCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtBackupSnapshotCommandWrapper.class);
+
+    @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 LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtConnectionWrapper.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);
+                snap.delete(0);
+
+                /*
+                 * 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);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromVolumeCommandWrapper.java
new file mode 100644
index 0000000..f3bfe1f
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromVolumeCommandWrapper.java
@@ -0,0 +1,176 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.cloudstack.utils.qemu.QemuImg;
+import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
+import org.apache.cloudstack.utils.qemu.QemuImgException;
+import org.apache.cloudstack.utils.qemu.QemuImgFile;
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
+import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
+import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.Storage.ImageFormat;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.storage.StorageLayer;
+import com.cloud.storage.template.Processor;
+import com.cloud.storage.template.Processor.FormatInfo;
+import com.cloud.storage.template.QCOW2Processor;
+import com.cloud.storage.template.TemplateLocation;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtCreatePrivateTemplateFromVolumeCommandWrapper extends CommandWrapper<CreatePrivateTemplateFromVolumeCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtCreatePrivateTemplateFromVolumeCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CreatePrivateTemplateFromVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String secondaryStorageURL = command.getSecondaryStorageUrl();
+
+        KVMStoragePool secondaryStorage = null;
+        KVMStoragePool primary = null;
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+        try {
+            final String templateFolder = command.getAccountId() + File.separator + command.getTemplateId() + File.separator;
+            final String templateInstallFolder = "/template/tmpl/" + templateFolder;
+
+            secondaryStorage = storagePoolMgr.getStoragePoolByURI(secondaryStorageURL);
+
+            try {
+                primary = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel());
+            } catch (final CloudRuntimeException e) {
+                if (e.getMessage().contains("not found")) {
+                    primary =
+                            storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(),
+                                    command.getPool().getUserInfo(), command.getPool().getType());
+                } else {
+                    return new CreatePrivateTemplateAnswer(command, false, e.getMessage());
+                }
+            }
+
+            final KVMPhysicalDisk disk = primary.getPhysicalDisk(command.getVolumePath());
+            final String tmpltPath = secondaryStorage.getLocalPath() + File.separator + templateInstallFolder;
+            final StorageLayer storage = libvirtComputingResource.getStorage();
+            storage.mkdirs(tmpltPath);
+
+            if (primary.getType() != StoragePoolType.RBD) {
+                final String createTmplPath = libvirtComputingResource.createTmplPath();
+                final int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
+
+                final Script scriptCommand = new Script(createTmplPath, cmdsTimeout, s_logger);
+                scriptCommand.add("-f", disk.getPath());
+                scriptCommand.add("-t", tmpltPath);
+                scriptCommand.add("-n", command.getUniqueName() + ".qcow2");
+
+                final String result = scriptCommand.execute();
+
+                if (result != null) {
+                    s_logger.debug("failed to create template: " + result);
+                    return new CreatePrivateTemplateAnswer(command, false, result);
+                }
+            } else {
+                s_logger.debug("Converting RBD disk " + disk.getPath() + " into template " + command.getUniqueName());
+
+                final QemuImgFile srcFile =
+                        new QemuImgFile(KVMPhysicalDisk.RBDStringBuilder(primary.getSourceHost(), primary.getSourcePort(), primary.getAuthUserName(),
+                                primary.getAuthSecret(), disk.getPath()));
+                srcFile.setFormat(PhysicalDiskFormat.RAW);
+
+                final QemuImgFile destFile = new QemuImgFile(tmpltPath + "/" + command.getUniqueName() + ".qcow2");
+                destFile.setFormat(PhysicalDiskFormat.QCOW2);
+
+                final QemuImg q = new QemuImg(0);
+                try {
+                    q.convert(srcFile, destFile);
+                } catch (final QemuImgException e) {
+                    s_logger.error("Failed to create new template while converting " + srcFile.getFileName() + " to " + destFile.getFileName() + " the error was: " +
+                            e.getMessage());
+                }
+
+                final File templateProp = new File(tmpltPath + "/template.properties");
+                if (!templateProp.exists()) {
+                    templateProp.createNewFile();
+                }
+
+                String templateContent = "filename=" + command.getUniqueName() + ".qcow2" + System.getProperty("line.separator");
+
+                final DateFormat dateFormat = new SimpleDateFormat("MM_dd_yyyy");
+                final Date date = new Date();
+                templateContent += "snapshot.name=" + dateFormat.format(date) + System.getProperty("line.separator");
+
+                try(FileOutputStream templFo = new FileOutputStream(templateProp);) {
+                    templFo.write(templateContent.getBytes());
+                    templFo.flush();
+                }catch(final IOException ex)
+                {
+                    s_logger.error("CreatePrivateTemplateAnswer:Exception:"+ex.getMessage());
+                }
+
+            }
+
+            final Map<String, Object> params = new HashMap<String, Object>();
+            params.put(StorageLayer.InstanceConfigKey, storage);
+            final Processor qcow2Processor = new QCOW2Processor();
+
+            qcow2Processor.configure("QCOW2 Processor", params);
+
+            final FormatInfo info = qcow2Processor.process(tmpltPath, null, command.getUniqueName());
+
+            final TemplateLocation loc = new TemplateLocation(storage, tmpltPath);
+            loc.create(1, true, command.getUniqueName());
+            loc.addFormat(info);
+            loc.save();
+
+            return new CreatePrivateTemplateAnswer(command, true, null, templateInstallFolder + command.getUniqueName() + ".qcow2", info.virtualSize, info.size,
+                    command.getUniqueName(), ImageFormat.QCOW2);
+        } catch (final InternalErrorException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.toString());
+        } catch (final IOException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.toString());
+        } catch (final ConfigurationException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.toString());
+        } catch (final CloudRuntimeException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.toString());
+        } finally {
+            if (secondaryStorage != null) {
+                storagePoolMgr.deleteStoragePool(secondaryStorage.getType(), secondaryStorage.getUuid());
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
new file mode 100644
index 0000000..9a991a1
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
@@ -0,0 +1,163 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.File;
+import java.text.MessageFormat;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.Domain;
+import org.libvirt.DomainInfo.DomainState;
+import org.libvirt.DomainSnapshot;
+import org.libvirt.LibvirtException;
+
+import com.ceph.rados.IoCTX;
+import com.ceph.rados.Rados;
+import com.ceph.rbd.Rbd;
+import com.ceph.rbd.RbdImage;
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ManageSnapshotAnswer;
+import com.cloud.agent.api.ManageSnapshotCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtManageSnapshotCommandWrapper extends CommandWrapper<ManageSnapshotCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtManageSnapshotCommandWrapper.class);
+
+    @Override
+    public Answer execute(final ManageSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String snapshotName = command.getSnapshotName();
+        final String snapshotPath = command.getSnapshotPath();
+        final String vmName = command.getVmName();
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            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 primaryPool = libvirtComputingResource.getStoragePoolMgr().getStoragePool(command.getPool().getType(), command.getPool().getUuid());
+
+            final KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(command.getVolumePath());
+            if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryPool.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);
+                if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
+                    vm.snapshotCreateXML(snapshot);
+                } else {
+                    final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
+                    snap.delete(0);
+                }
+
+                /*
+                 * 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 {
+                /**
+                 * For RBD we can't use libvirt to do our snapshotting or any Bash scripts.
+                 * libvirt also wants to store the memory contents of the Virtual Machine,
+                 * but that's not possible with RBD since there is no way to store the memory
+                 * contents in RBD.
+                 *
+                 * So we rely on the Java bindings for RBD to create our snapshot
+                 *
+                 * This snapshot might not be 100% consistent due to writes still being in the
+                 * memory of the Virtual Machine, but if the VM runs a kernel which supports
+                 * barriers properly (>2.6.32) this won't be any different then pulling the power
+                 * cord out of a running machine.
+                 */
+                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(disk.getName());
+
+                        if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
+                            s_logger.debug("Attempting to create RBD snapshot " + disk.getName() + "@" + snapshotName);
+                            image.snapCreate(snapshotName);
+                        } else {
+                            s_logger.debug("Attempting to remove RBD snapshot " + disk.getName() + "@" + snapshotName);
+                            image.snapRemove(snapshotName);
+                        }
+
+                        rbd.close(image);
+                        r.ioCtxDestroy(io);
+                    } catch (final Exception e) {
+                        s_logger.error("A RBD snapshot operation on " + disk.getName() + " failed. The error was: " + e.getMessage());
+                    }
+                } else {
+                    /* VM is not running, create a snapshot by ourself */
+                    final int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
+                    final String manageSnapshotPath = libvirtComputingResource.manageSnapshotPath();
+
+                    final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
+                    if (command.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) {
+                        scriptCommand.add("-c", disk.getPath());
+                    } else {
+                        scriptCommand.add("-d", snapshotPath);
+                    }
+
+                    scriptCommand.add("-n", snapshotName);
+                    final String result = scriptCommand.execute();
+                    if (result != null) {
+                        s_logger.debug("Failed to manage snapshot: " + result);
+                        return new ManageSnapshotAnswer(command, false, "Failed to manage snapshot: " + result);
+                    }
+                }
+            }
+            return new ManageSnapshotAnswer(command, command.getSnapshotId(), disk.getPath() + File.separator + snapshotName, true, null);
+        } catch (final LibvirtException e) {
+            s_logger.debug("Failed to manage snapshot: " + e.toString());
+            return new ManageSnapshotAnswer(command, false, "Failed to manage snapshot: " + e.toString());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 148075b..2656037 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -23,12 +23,14 @@ import java.util.Hashtable;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
+import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
+import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
@@ -39,6 +41,7 @@ import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
+import com.cloud.agent.api.ManageSnapshotCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
@@ -136,6 +139,9 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(PlugNicCommand.class, new LibvirtPlugNicCommandWrapper());
         linbvirtCommands.put(UnPlugNicCommand.class, new LibvirtUnPlugNicCommandWrapper());
         linbvirtCommands.put(NetworkUsageCommand.class, new LibvirtNetworkUsageCommandWrapper());
+        linbvirtCommands.put(CreatePrivateTemplateFromVolumeCommand.class, new LibvirtCreatePrivateTemplateFromVolumeCommandWrapper());
+        linbvirtCommands.put(ManageSnapshotCommand.class, new LibvirtManageSnapshotCommandWrapper());
+        linbvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bcf78d3b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 9b0be08..b0c2734 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -66,11 +66,13 @@ import org.xml.sax.SAXException;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
+import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
+import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
@@ -81,6 +83,7 @@ import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
+import com.cloud.agent.api.ManageSnapshotCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
@@ -3313,7 +3316,6 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        //Being called twice, although I did not find the second place yet.
         verify(libvirtComputingResource, times(1)).networkUsage(command.getPrivateIP(), "create", null);
     }
 
@@ -3337,7 +3339,6 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        //Being called twice, although I did not find the second place yet.
         verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR());
     }
 
@@ -3360,7 +3361,6 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        //Being called twice, although I did not find the second place yet.
         verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption());
     }
 
@@ -3383,7 +3383,6 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        //Being called twice, although I did not find the second place yet.
         verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption());
     }
 
@@ -3406,7 +3405,135 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
 
-        //Being called twice, although I did not find the second place yet.
         verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR());
     }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreatePrivateTemplateFromVolumeCommand() {
+        //Simple test used to make sure the flow (LibvirtComputingResource => Request => CommandWrapper) is working.
+        //The code is way to big and complex. Will finish the refactor and come back to this to add more cases.
+
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final String secondaryStorageUrl = "nfs:/192.168.2.2/storage/secondary";
+        final long templateId = 1l;
+        final long accountId = 1l;
+        final String userSpecifiedName = "User";
+        final String uniqueName = "Unique";
+        final String volumePath = "/123/vol";
+        final String vmName = "Test";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromVolumeCommand command = new CreatePrivateTemplateFromVolumeCommand(pool, secondaryStorageUrl, templateId, accountId, userSpecifiedName, uniqueName, volumePath, vmName, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryStorage = Mockito.mock(KVMStoragePool.class);
+        //final KVMStoragePool primary = Mockito.mock(KVMStoragePool.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl)).thenReturn(secondaryStorage);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel())).thenThrow(new CloudRuntimeException("error"));
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(secondaryStorageUrl);
+        verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testManageSnapshotCommandLibvirtException() {
+        //Simple test used to make sure the flow (LibvirtComputingResource => Request => CommandWrapper) is working.
+        //The code is way to big and complex. Will finish the refactor and come back to this to add more cases.
+
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final String volumePath = "/123/vol";
+        final String vmName = "Test";
+
+        final long snapshotId = 1l;
+        final String preSnapshotPath = "/snapshot/path";
+        final String snapshotName = "snap";
+
+        final ManageSnapshotCommand command = new ManageSnapshotCommand(snapshotId, volumePath, pool, preSnapshotPath, snapshotName, vmName);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        //final Connect conn = Mockito.mock(Connect.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testBackupSnapshotCommandLibvirtException() {
+        //Simple test used to make sure the flow (LibvirtComputingResource => Request => CommandWrapper) is working.
+        //The code is way to big and complex. Will finish the refactor and come back to this to add more cases.
+
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final String secondaryStorageUrl = "nfs:/192.168.2.2/storage/secondary";
+        final long accountId = 1l;
+        final String volumePath = "/123/vol";
+        final String vmName = "Test";
+        final int wait = 0;
+
+        final long snapshotId = 1l;
+        final String snapshotName = "snap";
+
+        final Long dcId = 1l;
+        final Long volumeId = 1l;
+        final Long secHostId = 1l;
+        final String snapshotUuid = "9a0afe7c-26a7-4585-bf87-abf82ae106d9";
+        final String prevBackupUuid = "003a0cc2-2e04-417a-bee0-534ef1724561";
+        final boolean isVolumeInactive = false;
+        final String prevSnapshotUuid = "1791efae-f22d-474b-87c6-92547d6c5877";
+
+        final BackupSnapshotCommand command = new BackupSnapshotCommand(secondaryStorageUrl, dcId, accountId, volumeId, snapshotId, secHostId, volumePath, pool, snapshotUuid, snapshotName, prevSnapshotUuid, prevBackupUuid, isVolumeInactive, vmName, wait);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        //final Connect conn = Mockito.mock(Connect.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
 }
\ No newline at end of file


[37/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8476: Disabling Zone, Pod, Cluster: --Test cases for testing the behaviour of resources running on zone and admin/non-admin user after disabling the Zone

Signed-off-by: Gaurav Aradhye <ga...@clogeny.com>
This closes #242


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/f6789532
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/f6789532
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/f6789532

Branch: refs/heads/CLOUDSTACK-8301
Commit: f6789532b0012287a0fcd8bfaa9df0cbc4d632a0
Parents: e8f8e0e
Author: pritisarap12 <pr...@clogeny.com>
Authored: Mon May 11 22:36:14 2015 +0530
Committer: Gaurav Aradhye <ga...@clogeny.com>
Committed: Mon May 18 12:18:15 2015 +0530

----------------------------------------------------------------------
 .../maint/testpath_disable_enable_zone.py       | 499 +++++++++++++++++++
 tools/marvin/marvin/codes.py                    |   1 +
 2 files changed, 500 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f6789532/test/integration/component/maint/testpath_disable_enable_zone.py
----------------------------------------------------------------------
diff --git a/test/integration/component/maint/testpath_disable_enable_zone.py b/test/integration/component/maint/testpath_disable_enable_zone.py
new file mode 100644
index 0000000..ba3a014
--- /dev/null
+++ b/test/integration/component/maint/testpath_disable_enable_zone.py
@@ -0,0 +1,499 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+""" Test cases for Disable enable Zone Test Path
+"""
+
+from nose.plugins.attrib import attr
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.lib.utils import (cleanup_resources)
+from marvin.lib.base import (Account,
+                             VirtualMachine,
+                             ServiceOffering,
+                             Zone,
+                             Template,
+                             Snapshot,
+                             Volume,
+                             DiskOffering,
+                             Iso
+                             )
+from marvin.lib.common import (get_domain,
+                               get_zone,
+                               get_template,
+                               list_volumes,
+                               list_snapshots,
+                               get_builtin_template_info
+                               )
+
+from marvin.cloudstackAPI import updateZone
+from marvin.codes import (ENABLED,
+                          DISABLED,
+                          STOPPED,
+                          RUNNING)
+
+
+class TestDisableEnableZone(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestDisableEnableZone, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        cls.hypervisor = cls.testClient.getHypervisorInfo()
+
+        # Get Zone, Domain and templates
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
+
+        cls.template = get_template(
+            cls.apiclient,
+            cls.zone.id,
+            cls.testdata["ostype"])
+
+        cls._cleanup = []
+
+        try:
+            cls.service_offering = ServiceOffering.create(
+                cls.apiclient,
+                cls.testdata["service_offering"],
+            )
+            cls._cleanup.append(cls.service_offering)
+
+            cls.disk_offering = DiskOffering.create(
+                cls.apiclient,
+                cls.testdata["disk_offering"],
+            )
+            cls._cleanup.append(cls.disk_offering)
+
+            # Create an account
+            cls.account = Account.create(
+                cls.apiclient,
+                cls.testdata["account"],
+                domainid=cls.domain.id
+            )
+            cls._cleanup.append(cls.account)
+
+            # Create user api client of the account
+            cls.userapiclient = testClient.getUserApiClient(
+                UserName=cls.account.name,
+                DomainName=cls.account.domain
+            )
+
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            zoneList = Zone.list(cls.apiclient, id=cls.zone.id)
+            if zoneList[0].allocationstate == DISABLED:
+                cmd = updateZone.updateZoneCmd()
+                cmd.id = zoneList[0].id
+                cmd.allocationstate = ENABLED
+                cls.apiclient.updateZone(cmd)
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.dbclient = self.testClient.getDbConnection()
+        self.cleanup = []
+
+    def tearDown(self):
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            raise Exception("Warning: Exception during cleanup : %s" % e)
+        return
+
+    @attr(tags=["advanced", "basic"], required_hardware="true")
+    def test_01_disable_enable_zone(self):
+        """disable enable zone
+            1. Disable zone and verify following things:
+                For admin user:
+                    1. Should be create to start/stop exsiting vms
+                    2. Should be create to deploy new vm, snapshot,volume,
+                       template,iso in the same zone
+                For Non-admin user:
+                    1. Should be create to start/stop exsiting vms
+                    2. Should not be create to deploy new vm, snapshot,volume,
+                       template,iso in the same zone
+            2. Enable the above disabled zone and verify that:
+                -All users should be create to deploy new vm,
+                    snapshot,volume,template,iso in the same zone
+            3. Try to delete the zone and it should fail with error message:
+                -"The zone is not deletable because there are
+                    servers running in this zone"
+        """
+        # Step 1
+        vm_user = VirtualMachine.create(
+            self.userapiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=self.account.name,
+            domainid=self.account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        vm_root = VirtualMachine.create(
+            self.apiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=self.account.name,
+            domainid=self.account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        cmd = updateZone.updateZoneCmd()
+        cmd.id = self.zone.id
+        cmd.allocationstate = DISABLED
+        self.apiclient.updateZone(cmd)
+        zoneList = Zone.list(self.apiclient, id=self.zone.id)
+
+        self.assertEqual(zoneList[0].allocationstate,
+                         DISABLED,
+                         "Check if the zone is in disabled state"
+                         )
+
+        # Both user and admin vms shoul be running
+        self.assertEqual(vm_user.state,
+                         RUNNING,
+                         "Verify that the user vm is running")
+
+        self.assertEqual(vm_root.state,
+                         RUNNING,
+                         "Verify that the admin vm is running")
+
+        vm_root.stop(self.apiclient)
+        vm_user.stop(self.apiclient)
+
+        root_state = self.dbclient.execute(
+            "select state from vm_instance where name='%s'" %
+            vm_root.name)[0][0]
+
+        user_state = self.dbclient.execute(
+            "select state from vm_instance where name='%s'" %
+            vm_user.name)[0][0]
+
+        self.assertEqual(root_state,
+                         STOPPED,
+                         "verify that vm is Stopped")
+
+        self.assertEqual(user_state,
+                         STOPPED,
+                         "verify that vm is stopped")
+
+        root_volume = list_volumes(
+            self.userapiclient,
+            virtualmachineid=vm_root.id,
+            type='ROOT',
+            listall=True
+        )
+
+        snap = Snapshot.create(
+            self.apiclient,
+            root_volume[0].id)
+
+        self.assertNotEqual(snap,
+                            None,
+                            "Verify that admin should be \
+                                    able to create snapshot")
+
+        snapshots = list_snapshots(
+            self.apiclient,
+            volumeid=root_volume[0].id,
+            listall=True)
+
+        template_from_snapshot = Template.create_from_snapshot(
+            self.apiclient,
+            snapshots[0],
+            self.testdata["privatetemplate"])
+
+        self.assertNotEqual(
+            template_from_snapshot,
+            None,
+            "Verify that admin should be able to create template"
+        )
+
+        builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
+        self.testdata["privatetemplate"]["url"] = builtin_info[0]
+        self.testdata["privatetemplate"]["hypervisor"] = builtin_info[1]
+        self.testdata["privatetemplate"]["format"] = builtin_info[2]
+
+        template_regis = Template.register(
+            self.apiclient,
+            self.testdata["privatetemplate"],
+            zoneid=self.zone.id)
+
+        self.assertNotEqual(
+            template_regis,
+            None,
+            "Check if template gets created"
+        )
+        self.assertNotEqual(
+            template_from_snapshot,
+            None,
+            "Check if template gets created"
+        )
+
+        data_volume = Volume.create(
+            self.apiclient,
+            self.testdata["volume"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+            diskofferingid=self.disk_offering.id
+        )
+        self.assertNotEqual(
+            data_volume,
+            None,
+            "Check if volume gets created"
+        )
+
+        ISO = Iso.create(
+            self.apiclient,
+            self.testdata["iso2"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+        )
+
+        self.assertNotEqual(
+            ISO,
+            None,
+            "Check if volume gets created"
+        )
+        # non-admin user should fail to create vm, snap, temp etc
+        with self.assertRaises(Exception):
+            VirtualMachine.create(self.userapiclient,
+                                  self.testdata["small"],
+                                  templateid=self.template.id,
+                                  accountid=self.account.name,
+                                  domainid=self.account.domainid,
+                                  serviceofferingid=self.service_offering.id,
+                                  zoneid=self.zone.id
+                                  )
+
+        root_volume = list_volumes(
+            self.userapiclient,
+            virtualmachineid=vm_user.id,
+            type='ROOT',
+            listall=True
+        )
+
+        with self.assertRaises(Exception):
+            snap = Snapshot.create(
+                self.userapiclient,
+                root_volume[0].id)
+
+        with self.assertRaises(Exception):
+            Template.register(
+                self.userapiclient,
+                self.testdata["privatetemplate"],
+                zoneid=self.zone.id)
+
+        with self.assertRaises(Exception):
+            Volume.create(
+                self.userapiclient,
+                self.testdata["volume"],
+                zoneid=self.zone.id,
+                account=self.account.name,
+                domainid=self.account.domainid,
+                diskofferingid=self.disk_offering.id
+            )
+
+        with self.assertRaises(Exception):
+            ISO = Iso.create(
+                self.userapiclient,
+                self.testdata["iso2"],
+                zoneid=self.zone.id,
+                account=self.account.name,
+                domainid=self.account.domainid,
+            )
+
+        # Step 2
+        cmd.allocationstate = ENABLED
+        self.apiclient.updateZone(cmd)
+
+        # After enabling the zone all users should be able to add new VM,
+        # volume, template and iso
+
+        root_vm_new = VirtualMachine.create(
+            self.apiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=self.account.name,
+            domainid=self.account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        self.assertNotEqual(root_vm_new,
+                            None,
+                            "Verify that admin should create new VM")
+
+        snap = Snapshot.create(
+            self.apiclient,
+            root_volume[0].id)
+
+        self.assertNotEqual(snap,
+                            None,
+                            "Verify that admin should snashot")
+
+        snapshots = list_snapshots(
+            self.apiclient,
+            volumeid=root_volume[0].id,
+            listall=True)
+
+        template_from_snapshot = Template.create_from_snapshot(
+            self.apiclient,
+            snapshots[0],
+            self.testdata["privatetemplate"])
+
+        self.assertNotEqual(
+            template_from_snapshot,
+            None,
+            "Check if template gets created"
+        )
+
+        template_regis = Template.register(
+            self.apiclient,
+            self.testdata["privatetemplate"],
+            zoneid=self.zone.id)
+
+        self.assertNotEqual(
+            template_regis,
+            None,
+            "Check if template gets created"
+        )
+        self.assertNotEqual(
+            template_from_snapshot,
+            None,
+            "Check if template gets created"
+        )
+
+        data_volume = Volume.create(
+            self.apiclient,
+            self.testdata["volume"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+            diskofferingid=self.disk_offering.id
+        )
+        self.assertNotEqual(
+            data_volume,
+            None,
+            "Check if volume gets created"
+        )
+
+        ISO = Iso.create(
+            self.apiclient,
+            self.testdata["iso2"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+        )
+
+        self.assertNotEqual(
+            ISO,
+            None,
+            "Check if volume gets created"
+        )
+        root_vm_new.delete(self.apiclient)
+        # Non root user
+        user_vm_new = VirtualMachine.create(
+            self.userapiclient,
+            self.testdata["small"],
+            templateid=self.template.id,
+            accountid=self.account.name,
+            domainid=self.account.domainid,
+            serviceofferingid=self.service_offering.id,
+            zoneid=self.zone.id
+        )
+
+        self.assertNotEqual(user_vm_new,
+                            None,
+                            "Verify that admin should create new VM")
+
+        snap = Snapshot.create(
+            self.userapiclient,
+            root_volume[0].id)
+
+        self.assertNotEqual(snap,
+                            None,
+                            "Verify that admin should snashot")
+
+        snapshots = list_snapshots(
+            self.userapiclient,
+            volumeid=root_volume[0].id,
+            listall=True)
+
+        template_regis = Template.register(
+            self.userapiclient,
+            self.testdata["privatetemplate"],
+            zoneid=self.zone.id)
+
+        self.assertNotEqual(
+            template_regis,
+            None,
+            "Check if template gets created"
+        )
+        self.assertNotEqual(
+            template_from_snapshot,
+            None,
+            "Check if template gets created"
+        )
+
+        data_volume = Volume.create(
+            self.userapiclient,
+            self.testdata["volume"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+            diskofferingid=self.disk_offering.id
+        )
+        self.assertNotEqual(
+            data_volume,
+            None,
+            "Check if volume gets created"
+        )
+
+        ISO = Iso.create(
+            self.userapiclient,
+            self.testdata["iso2"],
+            zoneid=self.zone.id,
+            account=self.account.name,
+            domainid=self.account.domainid,
+        )
+
+        self.assertNotEqual(
+            ISO,
+            None,
+            "Check if volume gets created"
+        )
+        user_vm_new.delete(self.apiclient)
+
+        # Step 3
+        # Deletion of zone should fail if vm,volume is present on the zone
+        with self.assertRaises(Exception):
+            self.zone.delete(self.apiclient)
+
+        return

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f6789532/tools/marvin/marvin/codes.py
----------------------------------------------------------------------
diff --git a/tools/marvin/marvin/codes.py b/tools/marvin/marvin/codes.py
index 921b619..502e49e 100644
--- a/tools/marvin/marvin/codes.py
+++ b/tools/marvin/marvin/codes.py
@@ -54,6 +54,7 @@ Snapshot States - END
 
 RECURRING = "RECURRING"
 ENABLED = "Enabled"
+DISABLED = "Disabled"
 NETWORK_OFFERING = "network_offering"
 ROOT = "ROOT"
 INVALID_INPUT = "INVALID INPUT"


[04/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCheckConsoleProxyLoadCommandWrapper, LibvirtConsoleProxyLoadCommandWrapper, LibvirtWatchConsoleProxyLoadCommandWrapperand CitrixConsoleProxyLoadCommandWrapper
  - 2 unit tests added
  - KVM hypervisor plugin with 12% coverage

Refactored the CommandWrapper interface in order to remove the esecuteProxyLoadScan, which is now
implemented bu subclasses.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/7319a126
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/7319a126
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/7319a126

Branch: refs/heads/CLOUDSTACK-8301
Commit: 7319a12600a7823aef8167348ee66a74a43ede8b
Parents: 08a9523
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri Apr 24 11:49:00 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:20:43 2015 +0200

----------------------------------------------------------------------
 core/src/com/cloud/resource/CommandWrapper.java | 65 ---------------
 .../kvm/resource/LibvirtComputingResource.java  | 59 +-------------
 ...virtCheckConsoleProxyLoadCommandWrapper.java | 41 ++++++++++
 .../LibvirtConsoleProxyLoadCommandWrapper.java  | 78 ++++++++++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  4 +
 ...virtWatchConsoleProxyLoadCommandWrapper.java | 41 ++++++++++
 .../resource/LibvirtComputingResourceTest.java  | 35 +++++++++
 ...trixCheckConsoleProxyLoadCommandWrapper.java | 17 ++--
 .../CitrixConsoleProxyLoadCommandWrapper.java   | 83 ++++++++++++++++++++
 ...trixWatchConsoleProxyLoadCommandWrapper.java | 17 ++--
 10 files changed, 303 insertions(+), 137 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/core/src/com/cloud/resource/CommandWrapper.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/resource/CommandWrapper.java b/core/src/com/cloud/resource/CommandWrapper.java
index 48c105f..f68e92a 100644
--- a/core/src/com/cloud/resource/CommandWrapper.java
+++ b/core/src/com/cloud/resource/CommandWrapper.java
@@ -19,81 +19,16 @@
 
 package com.cloud.resource;
 
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.net.URLConnection;
-import java.nio.charset.Charset;
-
-import org.apache.log4j.Logger;
-
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
-import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
 
 
 public abstract class CommandWrapper<T extends Command, A extends Answer, R extends ServerResource> {
 
-    private static final Logger s_logger = Logger.getLogger(CommandWrapper.class);
-
     /**
      * @param T is the command to be used.
      * @param R is the resource base to be used.
      * @return A and the Answer from the command.
      */
     public abstract A execute(T command, R serverResource);
-
-    /**
-     * Common method so we added it here.
-     *
-     * @param cmd
-     * @param proxyVmId
-     * @param proxyVmName
-     * @param proxyManagementIp
-     * @param cmdPort
-     * @return
-     */
-    protected 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();
-
-            // setting TIMEOUTs to avoid possible waiting until death situations
-            conn.setConnectTimeout(5000);
-            conn.setReadTimeout(5000);
-
-            final InputStream is = conn.getInputStream();
-            final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
-            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);
-    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 95b2faf..07cb4dd 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -23,14 +23,10 @@ import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.io.Reader;
 import java.net.InetAddress;
 import java.net.URI;
 import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
 import java.text.DateFormat;
 import java.text.MessageFormat;
 import java.text.SimpleDateFormat;
@@ -148,9 +144,6 @@ import com.cloud.agent.api.VmDiskStatsEntry;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.check.CheckSshAnswer;
 import com.cloud.agent.api.check.CheckSshCommand;
-import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
-import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
-import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
@@ -1307,11 +1300,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof CheckConsoleProxyLoadCommand) {
-                return execute((CheckConsoleProxyLoadCommand)cmd);
-            } else if (cmd instanceof WatchConsoleProxyLoadCommand) {
-                return execute((WatchConsoleProxyLoadCommand)cmd);
-            } else if (cmd instanceof GetVncPortCommand) {
+            if (cmd instanceof GetVncPortCommand) {
                 return execute((GetVncPortCommand)cmd);
             } else if (cmd instanceof ModifySshKeysCommand) {
                 return execute((ModifySshKeysCommand)cmd);
@@ -2886,56 +2875,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    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(final 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);
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckConsoleProxyLoadCommandWrapper.java
new file mode 100644
index 0000000..1267984
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckConsoleProxyLoadCommandWrapper.java
@@ -0,0 +1,41 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.ServerResource;
+
+public class LibvirtCheckConsoleProxyLoadCommandWrapper extends LibvirtConsoleProxyLoadCommandWrapper<CheckConsoleProxyLoadCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final Command command, final ServerResource serverResource) {
+        final CheckConsoleProxyLoadCommand cmd = (CheckConsoleProxyLoadCommand) command;
+
+        final long proxyVmId = cmd.getProxyVmId();
+        final String proxyVmName = cmd.getProxyVmName();
+        final String proxyManagementIp = cmd.getProxyManagementIp();
+        final int proxyCmdPort = cmd.getProxyCmdPort();
+
+        return executeProxyLoadScan(cmd, proxyVmId, proxyVmName, proxyManagementIp, proxyCmdPort);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConsoleProxyLoadCommandWrapper.java
new file mode 100644
index 0000000..125a295
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConsoleProxyLoadCommandWrapper.java
@@ -0,0 +1,78 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ServerResource;
+
+public abstract class LibvirtConsoleProxyLoadCommandWrapper<T extends Command, A extends Answer, R extends ServerResource> extends CommandWrapper<Command, Answer, ServerResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtConsoleProxyLoadCommandWrapper.class);
+
+    public 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);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 601db13..72d3a87 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -36,6 +36,8 @@ import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
+import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
+import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.RequestWrapper;
@@ -72,6 +74,8 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(ReadyCommand.class, new LibvirtReadyCommandWrapper());
         linbvirtCommands.put(AttachIsoCommand.class, new LibvirtAttachIsoCommandWrapper());
         linbvirtCommands.put(AttachVolumeCommand.class, new LibvirtAttachVolumeCommandWrapper());
+        linbvirtCommands.put(WatchConsoleProxyLoadCommand.class, new LibvirtWatchConsoleProxyLoadCommandWrapper());
+        linbvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtWatchConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtWatchConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtWatchConsoleProxyLoadCommandWrapper.java
new file mode 100644
index 0000000..62fff11
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtWatchConsoleProxyLoadCommandWrapper.java
@@ -0,0 +1,41 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.ServerResource;
+
+public class LibvirtWatchConsoleProxyLoadCommandWrapper extends LibvirtConsoleProxyLoadCommandWrapper<WatchConsoleProxyLoadCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final Command command, final ServerResource serverResource) {
+        final WatchConsoleProxyLoadCommand cmd = (WatchConsoleProxyLoadCommand) command;
+
+        final long proxyVmId = cmd.getProxyVmId();
+        final String proxyVmName = cmd.getProxyVmName();
+        final String proxyManagementIp = cmd.getProxyManagementIp();
+        final int proxyCmdPort = cmd.getProxyCmdPort();
+
+        return executeProxyLoadScan(cmd, proxyVmId, proxyVmName, proxyManagementIp, proxyCmdPort);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 75ce221..8f56ee0 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -79,6 +79,8 @@ import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.VmStatsEntry;
+import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
+import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.VirtualMachineTO;
@@ -1109,4 +1111,37 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testWatchConsoleProxyLoadCommand() {
+        final int interval = 0;
+        final long proxyVmId = 0l;
+        final String proxyVmName = "host";
+        final String proxyManagementIp = "169.172.15.16";
+        final int proxyCmdPort = 0;
+
+        final WatchConsoleProxyLoadCommand command = new WatchConsoleProxyLoadCommand(interval, proxyVmId, proxyVmName, proxyManagementIp, proxyCmdPort);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @Test
+    public void testCheckConsoleProxyLoadCommand() {
+        final long proxyVmId = 0l;
+        final String proxyVmName = "host";
+        final String proxyManagementIp = "169.172.15.16";
+        final int proxyCmdPort = 0;
+
+        final CheckConsoleProxyLoadCommand command = new CheckConsoleProxyLoadCommand(proxyVmId, proxyVmName, proxyManagementIp, proxyCmdPort);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixCheckConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixCheckConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixCheckConsoleProxyLoadCommandWrapper.java
index bdf7c31..08d36b3 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixCheckConsoleProxyLoadCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixCheckConsoleProxyLoadCommandWrapper.java
@@ -20,18 +20,21 @@
 package com.cloud.hypervisor.xenserver.resource.wrapper;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
-import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ServerResource;
 
-public final class CitrixCheckConsoleProxyLoadCommandWrapper extends CommandWrapper<CheckConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
+public final class CitrixCheckConsoleProxyLoadCommandWrapper extends CitrixConsoleProxyLoadCommandWrapper<CheckConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
 
     @Override
-    public Answer execute(final CheckConsoleProxyLoadCommand command, final CitrixResourceBase citrixResourceBase) {
-        final long proxyVmId = command.getProxyVmId();
-        final String proxyVmName = command.getProxyVmName();
-        final String proxyManagementIp = command.getProxyManagementIp();
-        final int cmdPort = command.getProxyCmdPort();
+    public Answer execute(final Command command, final ServerResource serverResource) {
+        final CheckConsoleProxyLoadCommand cmd = (CheckConsoleProxyLoadCommand) command;
+
+        final long proxyVmId = cmd.getProxyVmId();
+        final String proxyVmName = cmd.getProxyVmName();
+        final String proxyManagementIp = cmd.getProxyManagementIp();
+        final int cmdPort = cmd.getProxyCmdPort();
 
         return executeProxyLoadScan(command, proxyVmId, proxyVmName, proxyManagementIp, cmdPort);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixConsoleProxyLoadCommandWrapper.java
new file mode 100644
index 0000000..4e71b0e
--- /dev/null
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixConsoleProxyLoadCommandWrapper.java
@@ -0,0 +1,83 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.xenserver.resource.wrapper;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.charset.Charset;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
+import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ServerResource;
+
+public abstract class CitrixConsoleProxyLoadCommandWrapper<T extends Command, A extends Answer, R extends ServerResource> extends CommandWrapper<Command, Answer, ServerResource> {
+
+    private static final Logger s_logger = Logger.getLogger(CitrixConsoleProxyLoadCommandWrapper.class);
+
+    protected 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();
+
+            // setting TIMEOUTs to avoid possible waiting until death situations
+            conn.setConnectTimeout(5000);
+            conn.setReadTimeout(5000);
+
+            final InputStream is = conn.getInputStream();
+            final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
+            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);
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7319a126/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixWatchConsoleProxyLoadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixWatchConsoleProxyLoadCommandWrapper.java b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixWatchConsoleProxyLoadCommandWrapper.java
index 4ee9614..f188c20 100644
--- a/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixWatchConsoleProxyLoadCommandWrapper.java
+++ b/plugins/hypervisors/xenserver/src/com/cloud/hypervisor/xenserver/resource/wrapper/CitrixWatchConsoleProxyLoadCommandWrapper.java
@@ -20,18 +20,21 @@
 package com.cloud.hypervisor.xenserver.resource.wrapper;
 
 import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.Command;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.hypervisor.xenserver.resource.CitrixResourceBase;
-import com.cloud.resource.CommandWrapper;
+import com.cloud.resource.ServerResource;
 
-public final class CitrixWatchConsoleProxyLoadCommandWrapper extends CommandWrapper<WatchConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
+public final class CitrixWatchConsoleProxyLoadCommandWrapper extends CitrixConsoleProxyLoadCommandWrapper<WatchConsoleProxyLoadCommand, Answer, CitrixResourceBase> {
 
     @Override
-    public Answer execute(final WatchConsoleProxyLoadCommand command, final CitrixResourceBase citrixResourceBase) {
-        final long proxyVmId = command.getProxyVmId();
-        final String proxyVmName = command.getProxyVmName();
-        final String proxyManagementIp = command.getProxyManagementIp();
-        final int cmdPort = command.getProxyCmdPort();
+    public Answer execute(final Command command, final ServerResource serverResource) {
+        final WatchConsoleProxyLoadCommand cmd = (WatchConsoleProxyLoadCommand) command;
+
+        final long proxyVmId = cmd.getProxyVmId();
+        final String proxyVmName = cmd.getProxyVmName();
+        final String proxyManagementIp = cmd.getProxyManagementIp();
+        final int cmdPort = cmd.getProxyCmdPort();
 
         return executeProxyLoadScan(command, proxyVmId, proxyVmName, proxyManagementIp, cmdPort);
     }


[45/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Implementation for the ability to disable a storage pool for provisioning

... of new volumes. Following changes are implemented 1. Disable or enable a pool with the
updateStoragePool api. A new 'enabled' parameter added for the same. 2. When a
pool is disabled the state of the pool is updated to 'Disabled' in the db. On
enabling it is updated back to 'Up'. Alert is raised when a pool is disabled or
enabled. 3. Updated other storage providers to also honour the disabled state.
4. A disabled pool is skipped by allocators for provisioing of new volumes. 5.
Since the allocators skip a disabled pool for provisioning of volumes, the
volumes are also not listed as a destination for volume migration.

FS: https://cwiki.apache.org/confluence/display/CLOUDSTACK/Disabling+Storage+Pool+for+Provisioning

This closes #257

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/a99c9d0e
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/a99c9d0e
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/a99c9d0e

Branch: refs/heads/CLOUDSTACK-8301
Commit: a99c9d0e68b42725a9f174d94f8d91c8a05398f3
Parents: bab4e3a
Author: Devdeep Singh <de...@gmail.com>
Authored: Tue May 5 18:24:04 2015 +0530
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue May 19 11:16:49 2015 +0100

----------------------------------------------------------------------
 api/src/com/cloud/event/EventTypes.java         |  9 +++++
 .../com/cloud/storage/StoragePoolStatus.java    |  2 +-
 .../admin/storage/UpdateStoragePoolCmd.java     |  8 +++++
 .../api/storage/PrimaryDataStoreLifeCycle.java  |  2 ++
 .../datastore/db/PrimaryDataStoreDao.java       |  2 ++
 .../datastore/db/PrimaryDataStoreDaoImpl.java   | 21 +++++++++++
 .../ClusterScopeStoragePoolAllocator.java       | 16 +++++++--
 .../allocator/LocalStoragePoolAllocator.java    | 11 ++++++
 .../allocator/ZoneWideStoragePoolAllocator.java | 11 ++++++
 .../datastore/PrimaryDataStoreHelper.java       | 14 ++++++++
 .../ElastistorPrimaryDataStoreLifeCycle.java    | 10 ++++++
 ...CloudStackPrimaryDataStoreLifeCycleImpl.java | 10 ++++++
 .../NexentaPrimaryDataStoreLifeCycle.java       | 10 ++++++
 .../SamplePrimaryDataStoreLifeCycleImpl.java    |  8 +++++
 .../SolidFirePrimaryDataStoreLifeCycle.java     | 10 ++++++
 ...olidFireSharedPrimaryDataStoreLifeCycle.java | 10 ++++++
 .../com/cloud/storage/StorageManagerImpl.java   | 37 +++++++++++++++++++-
 17 files changed, 187 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/api/src/com/cloud/event/EventTypes.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java
index 20f287a..78236fa 100644
--- a/api/src/com/cloud/event/EventTypes.java
+++ b/api/src/com/cloud/event/EventTypes.java
@@ -54,6 +54,7 @@ import com.cloud.offering.NetworkOffering;
 import com.cloud.offering.ServiceOffering;
 import com.cloud.projects.Project;
 import com.cloud.server.ResourceTag;
+import com.cloud.storage.StoragePool;
 import com.cloud.storage.GuestOS;
 import com.cloud.storage.GuestOSHypervisor;
 import com.cloud.storage.Snapshot;
@@ -306,6 +307,10 @@ public class EventTypes {
     public static final String EVENT_MAINTENANCE_PREPARE = "MAINT.PREPARE";
     public static final String EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE = "MAINT.PREPARE.PS";
 
+    // Primary storage pool
+    public static final String EVENT_ENABLE_PRIMARY_STORAGE = "ENABLE.PS";
+    public static final String EVENT_DISABLE_PRIMARY_STORAGE = "DISABLE.PS";
+
     // VPN
     public static final String EVENT_REMOTE_ACCESS_VPN_CREATE = "VPN.REMOTE.ACCESS.CREATE";
     public static final String EVENT_REMOTE_ACCESS_VPN_DESTROY = "VPN.REMOTE.ACCESS.DESTROY";
@@ -728,6 +733,10 @@ public class EventTypes {
         entityEventDetails.put(EVENT_MAINTENANCE_PREPARE, Host.class);
         entityEventDetails.put(EVENT_MAINTENANCE_PREPARE_PRIMARY_STORAGE, Host.class);
 
+        // Primary storage pool
+        entityEventDetails.put(EVENT_ENABLE_PRIMARY_STORAGE, StoragePool.class);
+        entityEventDetails.put(EVENT_DISABLE_PRIMARY_STORAGE, StoragePool.class);
+
         // VPN
         entityEventDetails.put(EVENT_REMOTE_ACCESS_VPN_CREATE, RemoteAccessVpn.class);
         entityEventDetails.put(EVENT_REMOTE_ACCESS_VPN_DESTROY, RemoteAccessVpn.class);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/api/src/com/cloud/storage/StoragePoolStatus.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/storage/StoragePoolStatus.java b/api/src/com/cloud/storage/StoragePoolStatus.java
index c7ff0ff..778d388 100644
--- a/api/src/com/cloud/storage/StoragePoolStatus.java
+++ b/api/src/com/cloud/storage/StoragePoolStatus.java
@@ -17,5 +17,5 @@
 package com.cloud.storage;
 
 public enum StoragePoolStatus {
-    Initial, Initialized, Creating, Attaching, Up, PrepareForMaintenance, ErrorInMaintenance, CancelMaintenance, Maintenance, Removed;
+    Initial, Initialized, Creating, Attaching, Up, PrepareForMaintenance, ErrorInMaintenance, CancelMaintenance, Maintenance, Disabled, Removed;
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
index 3d1a773..6bf6228 100644
--- a/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java
@@ -54,6 +54,10 @@ public class UpdateStoragePoolCmd extends BaseCmd {
     @Parameter(name = ApiConstants.CAPACITY_BYTES, type = CommandType.LONG, required = false, description = "bytes CloudStack can provision from this storage pool")
     private Long capacityBytes;
 
+    @Parameter(name = ApiConstants.ENABLED, type = CommandType.BOOLEAN, required = false, description = "false to disable the pool for allocation of new volumes, true to" +
+            " enable it back.")
+    private Boolean enabled;
+
     /////////////////////////////////////////////////////
     /////////////////// Accessors ///////////////////////
     /////////////////////////////////////////////////////
@@ -74,6 +78,10 @@ public class UpdateStoragePoolCmd extends BaseCmd {
         return capacityBytes;
     }
 
+    public Boolean getEnabled() {
+        return enabled;
+    }
+
     /////////////////////////////////////////////////////
     /////////////// API Implementation///////////////////
     /////////////////////////////////////////////////////

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java
----------------------------------------------------------------------
diff --git a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java
index 7640cf3..fcbc19c 100644
--- a/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java
+++ b/engine/api/src/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java
@@ -27,4 +27,6 @@ public interface PrimaryDataStoreLifeCycle extends DataStoreLifeCycle {
     public static final String CAPACITY_IOPS = "capacityIops";
 
     void updateStoragePool(StoragePool storagePool, Map<String, String> details);
+    void enableStoragePool(DataStore store);
+    void disableStoragePool(DataStore store);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java
index a976bfb..3939545 100644
--- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java
+++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDao.java
@@ -77,6 +77,8 @@ public interface PrimaryDataStoreDao extends GenericDao<StoragePoolVO, Long> {
 
     List<StoragePoolVO> findPoolsByTags(long dcId, long podId, Long clusterId, String[] tags);
 
+    List<StoragePoolVO> findDisabledPoolsByScope(long dcId, Long podId, Long clusterId, ScopeType scope);
+
     /**
      * Find pool by UUID.
      *

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java
index ae2287e..faf5291 100644
--- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java
+++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java
@@ -76,6 +76,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase<StoragePoolVO, Long>
         AllFieldSearch.and("datacenterId", AllFieldSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
         AllFieldSearch.and("hostAddress", AllFieldSearch.entity().getHostAddress(), SearchCriteria.Op.EQ);
         AllFieldSearch.and("status", AllFieldSearch.entity().getStatus(), SearchCriteria.Op.EQ);
+        AllFieldSearch.and("scope", AllFieldSearch.entity().getScope(), SearchCriteria.Op.EQ);
         AllFieldSearch.and("path", AllFieldSearch.entity().getPath(), SearchCriteria.Op.EQ);
         AllFieldSearch.and("podId", AllFieldSearch.entity().getPodId(), Op.EQ);
         AllFieldSearch.and("clusterId", AllFieldSearch.entity().getClusterId(), Op.EQ);
@@ -310,6 +311,26 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase<StoragePoolVO, Long>
     }
 
     @Override
+    public List<StoragePoolVO> findDisabledPoolsByScope(long dcId, Long podId, Long clusterId, ScopeType scope) {
+        List<StoragePoolVO> storagePools = null;
+        SearchCriteria<StoragePoolVO> sc = AllFieldSearch.create();
+        sc.setParameters("status", StoragePoolStatus.Disabled);
+        sc.setParameters("scope", scope);
+
+        if (scope == ScopeType.ZONE) {
+            sc.setParameters("datacenterId", dcId);
+            storagePools = listBy(sc);
+        } else if ((scope == ScopeType.CLUSTER || scope == ScopeType.HOST) && podId != null && clusterId != null) {
+            sc.setParameters("datacenterId", dcId);
+            sc.setParameters("podId", podId);
+            sc.setParameters("clusterId", clusterId);
+            storagePools = listBy(sc);
+        }
+
+        return storagePools;
+    }
+
+    @Override
     public List<StoragePoolVO> findLocalStoragePoolsByTags(long dcId, long podId, Long clusterId, String[] tags) {
         List<StoragePoolVO> storagePools = null;
         if (tags == null || tags.length == 0) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
index 0f4df4f..d78bd09 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ClusterScopeStoragePoolAllocator.java
@@ -33,6 +33,7 @@ import org.springframework.stereotype.Component;
 import com.cloud.deploy.DeploymentPlan;
 import com.cloud.deploy.DeploymentPlanner.ExcludeList;
 import com.cloud.offering.ServiceOffering;
+import com.cloud.storage.ScopeType;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.dao.DiskOfferingDao;
 import com.cloud.vm.DiskProfile;
@@ -70,9 +71,20 @@ public class ClusterScopeStoragePoolAllocator extends AbstractStoragePoolAllocat
             return null;
         }
         if (dskCh.getTags() != null && dskCh.getTags().length != 0) {
-            s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId + " having tags:" + Arrays.toString(dskCh.getTags()));
+            s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId + " having tags:" + Arrays.toString(dskCh.getTags()) +
+                    ". Disabled pools will be ignored.");
         } else {
-            s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId);
+            s_logger.debug("Looking for pools in dc: " + dcId + "  pod:" + podId + "  cluster:" + clusterId + ". Disabled pools will be ignored.");
+        }
+
+        if (s_logger.isTraceEnabled()) {
+            // Log the pools details that are ignored because they are in disabled state
+            List<StoragePoolVO> disabledPools = _storagePoolDao.findDisabledPoolsByScope(dcId, podId, clusterId, ScopeType.CLUSTER);
+            if (disabledPools != null && !disabledPools.isEmpty()) {
+                for (StoragePoolVO pool : disabledPools) {
+                    s_logger.trace("Ignoring pool " + pool + " as it is in disabled state.");
+                }
+            }
         }
 
         List<StoragePoolVO> pools = _storagePoolDao.findPoolsByTags(dcId, podId, clusterId, dskCh.getTags());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
index 446e101..a4edf76 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/LocalStoragePoolAllocator.java
@@ -35,6 +35,7 @@ import com.cloud.capacity.dao.CapacityDao;
 import com.cloud.deploy.DeploymentPlan;
 import com.cloud.deploy.DeploymentPlanner.ExcludeList;
 import com.cloud.service.dao.ServiceOfferingDao;
+import com.cloud.storage.ScopeType;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.dao.StoragePoolHostDao;
 import com.cloud.utils.NumbersUtil;
@@ -69,6 +70,16 @@ public class LocalStoragePoolAllocator extends AbstractStoragePoolAllocator {
             return null;
         }
 
+        if (s_logger.isTraceEnabled()) {
+            // Log the pools details that are ignored because they are in disabled state
+            List<StoragePoolVO> disabledPools = _storagePoolDao.findDisabledPoolsByScope(plan.getDataCenterId(), plan.getPodId(), plan.getClusterId(), ScopeType.HOST);
+            if (disabledPools != null && !disabledPools.isEmpty()) {
+                for (StoragePoolVO pool : disabledPools) {
+                    s_logger.trace("Ignoring pool " + pool + " as it is in disabled state.");
+                }
+            }
+        }
+
         List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 
         // data disk and host identified from deploying vm (attach volume case)

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
index b38b76f..7a10966 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/allocator/ZoneWideStoragePoolAllocator.java
@@ -33,6 +33,7 @@ import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
 import com.cloud.deploy.DeploymentPlan;
 import com.cloud.deploy.DeploymentPlanner.ExcludeList;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
+import com.cloud.storage.ScopeType;
 import com.cloud.storage.StoragePool;
 import com.cloud.user.Account;
 import com.cloud.vm.DiskProfile;
@@ -55,6 +56,16 @@ public class ZoneWideStoragePoolAllocator extends AbstractStoragePoolAllocator {
             return null;
         }
 
+        if (s_logger.isTraceEnabled()) {
+            // Log the pools details that are ignored because they are in disabled state
+            List<StoragePoolVO> disabledPools = _storagePoolDao.findDisabledPoolsByScope(plan.getDataCenterId(), null, null, ScopeType.ZONE);
+            if (disabledPools != null && !disabledPools.isEmpty()) {
+                for (StoragePoolVO pool : disabledPools) {
+                    s_logger.trace("Ignoring pool " + pool + " as it is in disabled state.");
+                }
+            }
+        }
+
         List<StoragePool> suitablePools = new ArrayList<StoragePool>();
 
         List<StoragePoolVO> storagePools = _storagePoolDao.findZoneWideStoragePoolsByTags(plan.getDataCenterId(), dskCh.getTags());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java
----------------------------------------------------------------------
diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java b/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java
index ef0db85..8752c19 100644
--- a/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java
+++ b/engine/storage/src/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java
@@ -192,6 +192,20 @@ public class PrimaryDataStoreHelper {
         return true;
     }
 
+    public boolean disable(DataStore store) {
+        StoragePoolVO pool = this.dataStoreDao.findById(store.getId());
+        pool.setStatus(StoragePoolStatus.Disabled);
+        this.dataStoreDao.update(pool.getId(), pool);
+        return true;
+    }
+
+    public boolean enable(DataStore store) {
+        StoragePoolVO pool = this.dataStoreDao.findById(store.getId());
+        pool.setStatus(StoragePoolStatus.Up);
+        dataStoreDao.update(pool.getId(), pool);
+        return true;
+    }
+
     protected boolean deletePoolStats(Long poolId) {
         CapacityVO capacity1 = _capacityDao.findByHostIdType(poolId, Capacity.CAPACITY_TYPE_STORAGE);
         CapacityVO capacity2 = _capacityDao.findByHostIdType(poolId, Capacity.CAPACITY_TYPE_STORAGE_ALLOCATED);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/cloudbyte/src/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/cloudbyte/src/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/cloudbyte/src/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java
index 1778d43..5a8ccf1 100644
--- a/plugins/storage/volume/cloudbyte/src/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java
+++ b/plugins/storage/volume/cloudbyte/src/org/apache/cloudstack/storage/datastore/lifecycle/ElastistorPrimaryDataStoreLifeCycle.java
@@ -464,6 +464,16 @@ public class ElastistorPrimaryDataStoreLifeCycle implements PrimaryDataStoreLife
         return true;
     }
 
+    @Override
+    public void enableStoragePool(DataStore dataStore) {
+        _dataStoreHelper.enable(dataStore);
+    }
+
+    @Override
+    public void disableStoragePool(DataStore dataStore) {
+        _dataStoreHelper.disable(dataStore);
+    }
+
     @SuppressWarnings("finally")
     @Override
     public boolean deleteDataStore(DataStore store) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java
index d11342c..38e9d9c 100644
--- a/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java
+++ b/plugins/storage/volume/default/src/org/apache/cloudstack/storage/datastore/lifecycle/CloudStackPrimaryDataStoreLifeCycleImpl.java
@@ -522,4 +522,14 @@ public class CloudStackPrimaryDataStoreLifeCycleImpl implements PrimaryDataStore
     @Override
     public void updateStoragePool(StoragePool storagePool, Map<String, String> details) {
     }
+
+    @Override
+    public void enableStoragePool(DataStore dataStore) {
+        dataStoreHelper.enable(dataStore);
+    }
+
+    @Override
+    public void disableStoragePool(DataStore dataStore) {
+        dataStoreHelper.disable(dataStore);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java
index 493f274..4fffb34 100644
--- a/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java
+++ b/plugins/storage/volume/nexenta/src/org/apache/cloudstack/storage/datastore/lifecylce/NexentaPrimaryDataStoreLifeCycle.java
@@ -166,6 +166,16 @@ public class NexentaPrimaryDataStoreLifeCycle
     }
 
     @Override
+    public void enableStoragePool(DataStore dataStore) {
+        dataStoreHelper.enable(dataStore);
+    }
+
+    @Override
+    public void disableStoragePool(DataStore dataStore) {
+        dataStoreHelper.disable(dataStore);
+    }
+
+    @Override
     public boolean deleteDataStore(DataStore store) {
         return dataStoreHelper.deletePrimaryDataStore(store);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java
index ee38072..3a0ce83 100644
--- a/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java
+++ b/plugins/storage/volume/sample/src/org/apache/cloudstack/storage/datastore/lifecycle/SamplePrimaryDataStoreLifeCycleImpl.java
@@ -138,4 +138,12 @@ public class SamplePrimaryDataStoreLifeCycleImpl implements PrimaryDataStoreLife
     @Override
     public void updateStoragePool(StoragePool storagePool, Map<String, String> details) {
     }
+
+    @Override
+    public void enableStoragePool(DataStore store) {
+    }
+
+    @Override
+    public void disableStoragePool(DataStore store) {
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java
index 7c36416..4b38f22 100644
--- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java
+++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFirePrimaryDataStoreLifeCycle.java
@@ -287,4 +287,14 @@ public class SolidFirePrimaryDataStoreLifeCycle implements PrimaryDataStoreLifeC
             }
         }
     }
+
+    @Override
+    public void enableStoragePool(DataStore dataStore) {
+        dataStoreHelper.enable(dataStore);
+    }
+
+    @Override
+    public void disableStoragePool(DataStore dataStore) {
+        dataStoreHelper.disable(dataStore);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java
----------------------------------------------------------------------
diff --git a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java
index 4fa49ef..bc22ac7 100644
--- a/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java
+++ b/plugins/storage/volume/solidfire/src/org/apache/cloudstack/storage/datastore/lifecycle/SolidFireSharedPrimaryDataStoreLifeCycle.java
@@ -659,4 +659,14 @@ public class SolidFireSharedPrimaryDataStoreLifeCycle implements PrimaryDataStor
 
         SolidFireUtil.updateCsDbWithSolidFireIopsInfo(storagePool.getId(), _primaryDataStoreDao, _storagePoolDetailsDao, minIops, maxIops, burstIops);
     }
+
+    @Override
+    public void enableStoragePool(DataStore dataStore) {
+        _primaryDataStoreHelper.enable(dataStore);
+    }
+
+    @Override
+    public void disableStoragePool(DataStore dataStore) {
+        _primaryDataStoreHelper.disable(dataStore);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/a99c9d0e/server/src/com/cloud/storage/StorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java
index f31095b..e725ce3 100644
--- a/server/src/com/cloud/storage/StorageManagerImpl.java
+++ b/server/src/com/cloud/storage/StorageManagerImpl.java
@@ -116,6 +116,8 @@ import com.cloud.dc.ClusterVO;
 import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.dao.ClusterDao;
 import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
 import com.cloud.exception.AgentUnavailableException;
 import com.cloud.exception.ConnectionException;
 import com.cloud.exception.DiscoveryException;
@@ -732,6 +734,32 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C
         return details;
     }
 
+    @ActionEvent(eventType = EventTypes.EVENT_DISABLE_PRIMARY_STORAGE, eventDescription = "disable storage pool")
+    private void disablePrimaryStoragePool(StoragePoolVO primaryStorage) {
+        if (!primaryStorage.getStatus().equals(StoragePoolStatus.Up)) {
+            throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be disabled. Storage pool state : " +
+                    primaryStorage.getStatus().toString());
+        }
+
+        DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
+        DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle();
+        DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
+        ((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).disableStoragePool(store);
+    }
+
+    @ActionEvent(eventType = EventTypes.EVENT_ENABLE_PRIMARY_STORAGE, eventDescription = "enable storage pool")
+    private void enablePrimaryStoragePool(StoragePoolVO primaryStorage) {
+        if (!primaryStorage.getStatus().equals(StoragePoolStatus.Disabled)) {
+            throw new InvalidParameterValueException("Primary storage with id " + primaryStorage.getId() + " cannot be enabled. Storage pool state : " +
+                    primaryStorage.getStatus().toString());
+        }
+
+        DataStoreProvider provider = _dataStoreProviderMgr.getDataStoreProvider(primaryStorage.getStorageProviderName());
+        DataStoreLifeCycle dataStoreLifeCycle = provider.getDataStoreLifeCycle();
+        DataStore store = _dataStoreMgr.getDataStore(primaryStorage.getId(), DataStoreRole.Primary);
+        ((PrimaryDataStoreLifeCycle)dataStoreLifeCycle).enableStoragePool(store);
+    }
+
     @Override
     public PrimaryDataStoreInfo updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException {
         // Input validation
@@ -816,7 +844,14 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C
             }
         }
 
-        if (updatedDetails.size() >= 0) {
+        Boolean enabled = cmd.getEnabled();
+        if (enabled != null) {
+            if (enabled) {
+                enablePrimaryStoragePool(pool);
+            } else {
+                disablePrimaryStoragePool(pool);
+            }
+        } else if (updatedDetails.size() >= 0) {
             _storagePoolDao.updateDetails(id, updatedDetails);
         }
 


[02/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtPingTestCommandWrapper
  - 3 unit tests added
  - KVM hypervisor plugin with 11.2% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/be1e5176
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/be1e5176
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/be1e5176

Branch: refs/heads/CLOUDSTACK-8301
Commit: be1e5176156d9b7eb78e53c703b48d679ad52f56
Parents: 28e5546
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Apr 23 13:57:13 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:20:42 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 44 ++-----------
 .../wrapper/LibvirtPingTestCommandWrapper.java  | 65 ++++++++++++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  2 +
 .../resource/LibvirtComputingResourceTest.java  | 39 ++++++++++--
 4 files changed, 107 insertions(+), 43 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be1e5176/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 893f82d..1c7aa24 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -135,7 +135,6 @@ import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
-import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PlugNicAnswer;
 import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PvlanSetupCommand;
@@ -405,6 +404,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _migrateSpeed;
     }
 
+    public String getPingTestPath() {
+        return _pingTestPath;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1311,9 +1314,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof PingTestCommand) {
-                return execute((PingTestCommand)cmd);
-            } else if (cmd instanceof CheckVirtualMachineCommand) {
+            if (cmd instanceof CheckVirtualMachineCommand) {
                 return execute((CheckVirtualMachineCommand)cmd);
             } else if (cmd instanceof ReadyCommand) {
                 return execute((ReadyCommand)cmd);
@@ -3029,41 +3030,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final 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();
-    }
-
     public String networkUsage(final String privateIpAddress, final String option, final String vif) {
         final Script getUsage = new Script(_routerProxyPath, s_logger);
         getUsage.add("netusage.sh");

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be1e5176/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPingTestCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPingTestCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPingTestCommandWrapper.java
new file mode 100644
index 0000000..3ef9e2c
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPingTestCommandWrapper.java
@@ -0,0 +1,65 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.PingTestCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtPingTestCommandWrapper extends CommandWrapper<PingTestCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtPingTestCommandWrapper.class);
+
+    @Override
+    public Answer execute(final PingTestCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        String result = null;
+        final String computingHostIp = command.getComputingHostIp(); // TODO, split the command into 2 types
+
+        if (computingHostIp != null) {
+            result = doPingTest(libvirtComputingResource, computingHostIp);
+        } else if (command.getRouterIp() != null && command.getPrivateIp() != null) {
+            result = doPingTest(libvirtComputingResource, command.getRouterIp(), command.getPrivateIp());
+        } else {
+            return new Answer(command, false, "routerip and private ip is null");
+        }
+
+        if (result != null) {
+            return new Answer(command, false, result);
+        }
+        return new Answer(command);
+    }
+
+    protected String doPingTest(final LibvirtComputingResource libvirtComputingResource, final String computingHostIp) {
+        final Script command = new Script(libvirtComputingResource.getPingTestPath(), 10000, s_logger);
+        command.add("-h", computingHostIp);
+        return command.execute();
+    }
+
+    protected String doPingTest(final LibvirtComputingResource libvirtComputingResource, final String domRIp, final String vmIp) {
+        final Script command = new Script(libvirtComputingResource.getPingTestPath(), 10000, s_logger);
+        command.add("-i", domRIp);
+        command.add("-p", vmIp);
+        return command.execute();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be1e5176/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index ee444b8..aeac43c 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -27,6 +27,7 @@ import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.MigrateCommand;
+import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
@@ -62,6 +63,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CheckHealthCommand.class, new LibvirtCheckHealthCommandWrapper());
         linbvirtCommands.put(PrepareForMigrationCommand.class, new LibvirtPrepareForMigrationCommandWrapper());
         linbvirtCommands.put(MigrateCommand.class, new LibvirtMigrateCommandWrapper());
+        linbvirtCommands.put(PingTestCommand.class, new LibvirtPingTestCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/be1e5176/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 4aa249e..50c8ca6 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -68,6 +68,7 @@ import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.MigrateCommand;
+import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
@@ -596,7 +597,7 @@ public class LibvirtComputingResourceTest {
 
     @Test(expected = NumberFormatException.class)
     public void testGetHostStatsCommand() {
-        // A bit difficult top test due to the logger being passed and the parser itself relying on the connection.
+        // A bit difficult to test due to the logger being passed and the parser itself relying on the connection.
         // Have to spend some more time afterwards in order to refactor the wrapper itself.
 
         final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
@@ -611,9 +612,6 @@ public class LibvirtComputingResourceTest {
 
     @Test
     public void testCheckHealthCommand() {
-        // A bit difficult top test due to the logger being passed and the parser itself relying on the connection.
-        // Have to spend some more time afterwards in order to refactor the wrapper itself.
-
         final CheckHealthCommand command = new CheckHealthCommand();
 
         final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
@@ -743,4 +741,37 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testPingTestHostIpCommand() {
+        final PingTestCommand command = new PingTestCommand("172.1.10.10");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @Test
+    public void testPingTestPvtIpCommand() {
+        final PingTestCommand command = new PingTestCommand("169.17.1.10", "192.168.10.10");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
+
+    @Test
+    public void testPingOnlyOneIpCommand() {
+        final PingTestCommand command = new PingTestCommand("169.17.1.10", null);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+    }
 }
\ No newline at end of file


[31/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Merge branch 'refactor/libvirt_resource' of https://github.com/schubergphilis/cloudstack

This closes #233


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/45c0fa2f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/45c0fa2f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/45c0fa2f

Branch: refs/heads/CLOUDSTACK-8301
Commit: 45c0fa2faa7b5f0b2b2f2863cde7ad5e786115fa
Parents: 60b6dc1 f575206
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 13 11:23:12 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 13 11:23:12 2015 +0200

----------------------------------------------------------------------
 .../com/cloud/agent/api/SnapshotCommand.java    |    8 +-
 core/src/com/cloud/resource/CommandWrapper.java |   65 -
 core/src/com/cloud/resource/RequestWrapper.java |   79 +
 .../storage/command/AttachCommand.java          |   13 +-
 .../command/AttachPrimaryDataStoreCmd.java      |    7 +-
 .../cloudstack/storage/command/CopyCommand.java |   31 +-
 .../storage/command/CreateObjectCommand.java    |    7 +-
 .../command/CreatePrimaryDataStoreCmd.java      |   11 +-
 .../storage/command/DeleteCommand.java          |    7 +-
 .../storage/command/DettachCommand.java         |   19 +-
 .../storage/command/ForgetObjectCmd.java        |    9 +-
 .../storage/command/IntroduceObjectCmd.java     |    9 +-
 .../storage/command/SnapshotAndCopyCommand.java |   14 +-
 .../command/StorageSubSystemCommand.java        |    8 +-
 .../kvm-compute/spring-kvm-compute-context.xml  |    3 +
 .../kvm/resource/LibvirtComputingResource.java  | 3475 +++----------
 .../kvm/resource/MigrateKVMAsync.java           |   38 +
 .../wrapper/LibvirtAttachIsoCommandWrapper.java |   52 +
 .../LibvirtAttachVolumeCommandWrapper.java      |   58 +
 .../LibvirtBackupSnapshotCommandWrapper.java    |  204 +
 ...virtCheckConsoleProxyLoadCommandWrapper.java |   41 +
 .../LibvirtCheckHealthCommandWrapper.java       |   34 +
 .../LibvirtCheckNetworkCommandWrapper.java      |   57 +
 .../LibvirtCheckOnHostCommandWrapper.java       |   64 +
 .../wrapper/LibvirtCheckSshCommandWrapper.java  |   56 +
 ...ibvirtCheckVirtualMachineCommandWrapper.java |   51 +
 ...ibvirtCleanupNetworkRulesCommandWrapper.java |   34 +
 .../LibvirtConsoleProxyLoadCommandWrapper.java  |   78 +
 .../LibvirtCopyVolumeCommandWrapper.java        |   98 +
 .../wrapper/LibvirtCreateCommandWrapper.java    |   83 +
 ...ivateTemplateFromSnapshotCommandWrapper.java |  113 +
 ...PrivateTemplateFromVolumeCommandWrapper.java |  176 +
 .../LibvirtCreateStoragePoolCommandWrapper.java |   33 +
 ...tCreateVolumeFromSnapshotCommandWrapper.java |   68 +
 .../LibvirtDeleteStoragePoolCommandWrapper.java |   43 +
 .../wrapper/LibvirtDestroyCommandWrapper.java   |   50 +
 .../wrapper/LibvirtFenceCommandWrapper.java     |   67 +
 .../LibvirtGetHostStatsCommandWrapper.java      |   80 +
 .../LibvirtGetStorageStatsCommandWrapper.java   |   43 +
 .../LibvirtGetVmDiskStatsCommandWrapper.java    |   62 +
 .../LibvirtGetVmStatsCommandWrapper.java        |   63 +
 .../LibvirtGetVncPortCommandWrapper.java        |   45 +
 .../wrapper/LibvirtMaintainCommandWrapper.java  |   34 +
 .../LibvirtManageSnapshotCommandWrapper.java    |  167 +
 .../wrapper/LibvirtMigrateCommandWrapper.java   |  183 +
 .../LibvirtModifySshKeysCommandWrapper.java     |  119 +
 .../LibvirtModifyStoragePoolCommandWrapper.java |   51 +
 .../LibvirtNetworkElementCommandWrapper.java    |   35 +
 ...bvirtNetworkRulesSystemVmCommandWrapper.java |   49 +
 ...NetworkRulesVmSecondaryIpCommandWrapper.java |   49 +
 .../LibvirtNetworkUsageCommandWrapper.java      |   57 +
 .../LibvirtOvsCreateTunnelCommandWrapper.java   |   68 +
 .../LibvirtOvsDestroyBridgeCommandWrapper.java  |   43 +
 .../LibvirtOvsDestroyTunnelCommandWrapper.java  |   58 +
 .../LibvirtOvsFetchInterfaceCommandWrapper.java |   53 +
 .../LibvirtOvsSetupBridgeCommandWrapper.java    |   47 +
 ...VpcPhysicalTopologyConfigCommandWrapper.java |   53 +
 ...OvsVpcRoutingPolicyConfigCommandWrapper.java |   53 +
 .../wrapper/LibvirtPingTestCommandWrapper.java  |   65 +
 .../wrapper/LibvirtPlugNicCommandWrapper.java   |   85 +
 ...ibvirtPrepareForMigrationCommandWrapper.java |   91 +
 ...irtPrimaryStorageDownloadCommandWrapper.java |   88 +
 .../LibvirtPvlanSetupCommandWrapper.java        |  105 +
 .../wrapper/LibvirtReadyCommandWrapper.java     |   34 +
 .../wrapper/LibvirtRebootCommandWrapper.java    |   59 +
 .../LibvirtRebootRouterCommandWrapper.java      |   47 +
 .../resource/wrapper/LibvirtRequestWrapper.java |  184 +
 .../LibvirtResizeVolumeCommandWrapper.java      |  136 +
 ...LibvirtSecurityGroupRulesCommandWrapper.java |   67 +
 .../wrapper/LibvirtStartCommandWrapper.java     |  151 +
 .../wrapper/LibvirtStopCommandWrapper.java      |   87 +
 .../LibvirtStorageSubSystemCommandWrapper.java  |   36 +
 .../wrapper/LibvirtUnPlugNicCommandWrapper.java |   80 +
 .../LibvirtUpgradeSnapshotCommandWrapper.java   |   33 +
 .../wrapper/LibvirtUtilitiesHelper.java         |   85 +
 ...virtWatchConsoleProxyLoadCommandWrapper.java |   41 +
 .../resource/LibvirtComputingResourceTest.java  | 4860 +++++++++++++++++-
 ...trixCheckConsoleProxyLoadCommandWrapper.java |   17 +-
 .../CitrixConsoleProxyLoadCommandWrapper.java   |   83 +
 .../resource/wrapper/CitrixRequestWrapper.java  |   74 -
 ...trixWatchConsoleProxyLoadCommandWrapper.java |   17 +-
 .../wrapper/CitrixRequestWrapperTest.java       |    4 +-
 82 files changed, 10150 insertions(+), 3054 deletions(-)
----------------------------------------------------------------------



[16/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtNetworkUsageCommandWrapper, LibvirtPlugNicCommandWrapper and LibvirtUnPlugNicCommandWrapper
  - 9 unit tests added
  - KVM hypervisor plugin with 18.3% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/52d9f0c2
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/52d9f0c2
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/52d9f0c2

Branch: refs/heads/CLOUDSTACK-8301
Commit: 52d9f0c20624e74dd2852038cd3912e1756d11e3
Parents: ff7ae9c
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue May 5 10:39:50 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:13 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 120 +----
 .../LibvirtNetworkUsageCommandWrapper.java      |  57 +++
 .../wrapper/LibvirtPlugNicCommandWrapper.java   |  85 ++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   6 +
 .../wrapper/LibvirtUnPlugNicCommandWrapper.java |  80 +++
 .../resource/LibvirtComputingResourceTest.java  | 481 +++++++++++++++++++
 6 files changed, 713 insertions(+), 116 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 6f24b31..3c40c90 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -87,13 +87,9 @@ import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
-import com.cloud.agent.api.NetworkUsageAnswer;
-import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
-import com.cloud.agent.api.PlugNicAnswer;
-import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PvlanSetupCommand;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.StartAnswer;
@@ -101,8 +97,6 @@ import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupRoutingCommand;
 import com.cloud.agent.api.StartupStorageCommand;
-import com.cloud.agent.api.UnPlugNicAnswer;
-import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.VmDiskStatsEntry;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.routing.IpAssocCommand;
@@ -1277,14 +1271,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
             } else if (cmd instanceof StartCommand) {
                 return execute((StartCommand)cmd);
-            } else if (cmd instanceof PlugNicCommand) {
-                return execute((PlugNicCommand)cmd);
-            } else if (cmd instanceof UnPlugNicCommand) {
-                return execute((UnPlugNicCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
-            } else if (cmd instanceof NetworkUsageCommand) {
-                return execute((NetworkUsageCommand)cmd);
             } else if (cmd instanceof CopyVolumeCommand) {
                 return execute((CopyVolumeCommand)cmd);
             } else if (cmd instanceof ResizeVolumeCommand) {
@@ -1702,79 +1690,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private PlugNicAnswer execute(final PlugNicCommand cmd) {
-        final NicTO nic = cmd.getNic();
-        final String vmName = cmd.getVmName();
-        Domain vm = null;
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(vmName);
-            vm = getDomain(conn, vmName);
-            final List<InterfaceDef> pluggedNics = getInterfaces(conn, vmName);
-            Integer nicnum = 0;
-            for (final InterfaceDef pluggedNic : pluggedNics) {
-                if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
-                    s_logger.debug("found existing nic for mac " + pluggedNic.getMacAddress() + " at index " + nicnum);
-                    return new PlugNicAnswer(cmd, true, "success");
-                }
-                nicnum++;
-            }
-            vm.attachDevice(getVifDriver(nic.getType()).plug(nic, "Other PV", "").toString());
-            return new PlugNicAnswer(cmd, true, "success");
-        } catch (final LibvirtException e) {
-            final String msg = " Plug Nic failed due to " + e.toString();
-            s_logger.warn(msg, e);
-            return new PlugNicAnswer(cmd, false, msg);
-        } catch (final InternalErrorException e) {
-            final String msg = " Plug Nic failed due to " + e.toString();
-            s_logger.warn(msg, e);
-            return new PlugNicAnswer(cmd, false, msg);
-        } finally {
-            if (vm != null) {
-                try {
-                    vm.free();
-                } catch (final LibvirtException l) {
-                    s_logger.trace("Ignoring libvirt error.", l);
-                }
-            }
-        }
-    }
-
-    private UnPlugNicAnswer execute(final UnPlugNicCommand cmd) {
-        Connect conn;
-        final NicTO nic = cmd.getNic();
-        final String vmName = cmd.getVmName();
-        Domain vm = null;
-        try {
-            conn = LibvirtConnection.getConnectionByVmName(vmName);
-            vm = getDomain(conn, vmName);
-            final List<InterfaceDef> pluggedNics = getInterfaces(conn, vmName);
-            for (final InterfaceDef pluggedNic : pluggedNics) {
-                if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
-                    vm.detachDevice(pluggedNic.toString());
-                    // We don't know which "traffic type" is associated with
-                    // each interface at this point, so inform all vif drivers
-                    for (final VifDriver vifDriver : getAllVifDrivers()) {
-                        vifDriver.unplug(pluggedNic);
-                    }
-                    return new UnPlugNicAnswer(cmd, true, "success");
-                }
-            }
-            return new UnPlugNicAnswer(cmd, true, "success");
-        } catch (final LibvirtException e) {
-            final String msg = " Unplug Nic failed due to " + e.toString();
-            s_logger.warn(msg, e);
-            return new UnPlugNicAnswer(cmd, false, msg);
-        } finally {
-            if (vm != null) {
-                try {
-                    vm.free();
-                } catch (final LibvirtException l) {
-                    s_logger.trace("Ignoring libvirt error.", l);
-                }
-            }
-        }
-    }
-
     private ExecutionResult prepareNetworkElementCommand(final SetupGuestNetworkCommand cmd) {
         Connect conn;
         final NicTO nic = cmd.getNic();
@@ -2445,7 +2360,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return usageParser.getLine();
     }
 
-    protected long[] getNetworkStats(final String privateIP) {
+    public long[] getNetworkStats(final String privateIP) {
         final String result = networkUsage(privateIP, "get", null);
         final long[] stats = new long[2];
         if (result != null) {
@@ -2459,7 +2374,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return stats;
     }
 
-    protected String VPCNetworkUsage(final String privateIpAddress, final String publicIp, final String option, final String vpcCIDR) {
+    public String configureVPCNetworkUsage(final String privateIpAddress, final String publicIp, final String option, final String vpcCIDR) {
         final Script getUsage = new Script(_routerProxyPath, s_logger);
         getUsage.add("vpc_netusage.sh");
         getUsage.add(privateIpAddress);
@@ -2487,8 +2402,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return usageParser.getLine();
     }
 
-    protected long[] getVPCNetworkStats(final String privateIP, final String publicIp, final String option) {
-        final String result = VPCNetworkUsage(privateIP, publicIp, option, null);
+    public long[] getVPCNetworkStats(final String privateIP, final String publicIp, final String option) {
+        final String result = configureVPCNetworkUsage(privateIP, publicIp, option, null);
         final long[] stats = new long[2];
         if (result != null) {
             final String[] splitResult = result.split(":");
@@ -2501,33 +2416,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return stats;
     }
 
-    private Answer execute(final NetworkUsageCommand cmd) {
-        if (cmd.isForVpc()) {
-            if (cmd.getOption() != null && cmd.getOption().equals("create")) {
-                final String result = VPCNetworkUsage(cmd.getPrivateIP(), cmd.getGatewayIP(), "create", cmd.getVpcCIDR());
-                final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
-                return answer;
-            } else if (cmd.getOption() != null && (cmd.getOption().equals("get") || cmd.getOption().equals("vpn"))) {
-                final long[] stats = getVPCNetworkStats(cmd.getPrivateIP(), cmd.getGatewayIP(), cmd.getOption());
-                final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
-                return answer;
-            } else {
-                final String result = VPCNetworkUsage(cmd.getPrivateIP(), cmd.getGatewayIP(), cmd.getOption(), cmd.getVpcCIDR());
-                final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
-                return answer;
-            }
-        } else {
-            if (cmd.getOption() != null && cmd.getOption().equals("create")) {
-                final String result = networkUsage(cmd.getPrivateIP(), "create", null);
-                final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L);
-                return answer;
-            }
-            final long[] stats = getNetworkStats(cmd.getPrivateIP());
-            final NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]);
-            return answer;
-        }
-    }
-
     protected void handleVmStartFailure(final Connect conn, final String vmName, final LibvirtVMDef vm) {
         if (vm != null && vm.getDevices() != null) {
             cleanupVMNetworks(conn, vm.getDevices().getInterfaces());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkUsageCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkUsageCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkUsageCommandWrapper.java
new file mode 100644
index 0000000..3ac2182
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkUsageCommandWrapper.java
@@ -0,0 +1,57 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.NetworkUsageAnswer;
+import com.cloud.agent.api.NetworkUsageCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtNetworkUsageCommandWrapper extends CommandWrapper<NetworkUsageCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final NetworkUsageCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        if (command.isForVpc()) {
+            if (command.getOption() != null && command.getOption().equals("create")) {
+                final String result = libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR());
+                final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, result, 0L, 0L);
+                return answer;
+            } else if (command.getOption() != null && (command.getOption().equals("get") || command.getOption().equals("vpn"))) {
+                final long[] stats = libvirtComputingResource.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption());
+                final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, "", stats[0], stats[1]);
+                return answer;
+            } else {
+                final String result = libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR());
+                final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, result, 0L, 0L);
+                return answer;
+            }
+        } else {
+            if (command.getOption() != null && command.getOption().equals("create")) {
+                final String result = libvirtComputingResource.networkUsage(command.getPrivateIP(), "create", null);
+                final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, result, 0L, 0L);
+                return answer;
+            }
+            final long [] stats = libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+            final NetworkUsageAnswer answer = new NetworkUsageAnswer(command, "", stats[0], stats[1]);
+            return answer;
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
new file mode 100644
index 0000000..7e6f642
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
@@ -0,0 +1,85 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.Domain;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.PlugNicAnswer;
+import com.cloud.agent.api.PlugNicCommand;
+import com.cloud.agent.api.to.NicTO;
+import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
+import com.cloud.hypervisor.kvm.resource.VifDriver;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtPlugNicCommandWrapper extends CommandWrapper<PlugNicCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtPlugNicCommandWrapper.class);
+
+    @Override
+    public Answer execute(final PlugNicCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final NicTO nic = command.getNic();
+        final String vmName = command.getVmName();
+        Domain vm = null;
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            vm = libvirtComputingResource.getDomain(conn, vmName);
+
+            final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);
+            Integer nicnum = 0;
+            for (final InterfaceDef pluggedNic : pluggedNics) {
+                if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
+                    s_logger.debug("found existing nic for mac " + pluggedNic.getMacAddress() + " at index " + nicnum);
+                    return new PlugNicAnswer(command, true, "success");
+                }
+                nicnum++;
+            }
+            VifDriver vifDriver = libvirtComputingResource.getVifDriver(nic.getType());
+            InterfaceDef interfaceDef = vifDriver.plug(nic, "Other PV", "");
+            vm.attachDevice(interfaceDef.toString());
+
+            return new PlugNicAnswer(command, true, "success");
+        } catch (final LibvirtException e) {
+            final String msg = " Plug Nic failed due to " + e.toString();
+            s_logger.warn(msg, e);
+            return new PlugNicAnswer(command, false, msg);
+        } catch (final InternalErrorException e) {
+            final String msg = " Plug Nic failed due to " + e.toString();
+            s_logger.warn(msg, e);
+            return new PlugNicAnswer(command, false, msg);
+        } finally {
+            if (vm != null) {
+                try {
+                    vm.free();
+                } catch (final LibvirtException l) {
+                    s_logger.trace("Ignoring libvirt error.", l);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 23248c4..148075b 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -44,6 +44,7 @@ import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
+import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
@@ -52,12 +53,14 @@ import com.cloud.agent.api.OvsSetupBridgeCommand;
 import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
 import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingTestCommand;
+import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.StopCommand;
+import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
@@ -130,6 +133,9 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CreateVolumeFromSnapshotCommand.class, new LibvirtCreateVolumeFromSnapshotCommandWrapper());
         linbvirtCommands.put(FenceCommand.class, new LibvirtFenceCommandWrapper());
         linbvirtCommands.put(SecurityGroupRulesCmd.class, new LibvirtSecurityGroupRulesCommandWrapper());
+        linbvirtCommands.put(PlugNicCommand.class, new LibvirtPlugNicCommandWrapper());
+        linbvirtCommands.put(UnPlugNicCommand.class, new LibvirtUnPlugNicCommandWrapper());
+        linbvirtCommands.put(NetworkUsageCommand.class, new LibvirtNetworkUsageCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
new file mode 100644
index 0000000..4ce14f2
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
@@ -0,0 +1,80 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.Domain;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.UnPlugNicAnswer;
+import com.cloud.agent.api.UnPlugNicCommand;
+import com.cloud.agent.api.to.NicTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
+import com.cloud.hypervisor.kvm.resource.VifDriver;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtUnPlugNicCommandWrapper extends CommandWrapper<UnPlugNicCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtUnPlugNicCommandWrapper.class);
+
+    @Override
+    public Answer execute(final UnPlugNicCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final NicTO nic = command.getNic();
+        final String vmName = command.getVmName();
+        Domain vm = null;
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(vmName);
+            vm = libvirtComputingResource.getDomain(conn, vmName);
+            final List<InterfaceDef> pluggedNics = libvirtComputingResource.getInterfaces(conn, vmName);
+
+            for (final InterfaceDef pluggedNic : pluggedNics) {
+                if (pluggedNic.getMacAddress().equalsIgnoreCase(nic.getMac())) {
+                    vm.detachDevice(pluggedNic.toString());
+                    // We don't know which "traffic type" is associated with
+                    // each interface at this point, so inform all vif drivers
+                    for (final VifDriver vifDriver : libvirtComputingResource.getAllVifDrivers()) {
+                        vifDriver.unplug(pluggedNic);
+                    }
+                    return new UnPlugNicAnswer(command, true, "success");
+                }
+            }
+            return new UnPlugNicAnswer(command, true, "success");
+        } catch (final LibvirtException e) {
+            final String msg = " Unplug Nic failed due to " + e.toString();
+            s_logger.warn(msg, e);
+            return new UnPlugNicAnswer(command, false, msg);
+        } finally {
+            if (vm != null) {
+                try {
+                    vm.free();
+                } catch (final LibvirtException l) {
+                    s_logger.trace("Ignoring libvirt error.", l);
+                }
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/52d9f0c2/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 15ba52b..9b0be08 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -86,6 +86,7 @@ import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
+import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
@@ -98,6 +99,7 @@ import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand.Vm;
 import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand.Acl;
 import com.cloud.agent.api.PingTestCommand;
+import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
@@ -105,6 +107,7 @@ import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
 import com.cloud.agent.api.StopCommand;
+import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.check.CheckSshCommand;
@@ -2928,4 +2931,482 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testPlugNicCommandMatchMack() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+        final Type vmtype = Type.DomainRouter;
+
+        final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final Domain vm = Mockito.mock(Domain.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
+        nics.add(intDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+
+        when(intDef.getDevName()).thenReturn("eth0");
+        when(intDef.getBrName()).thenReturn("br0");
+        when(intDef.getMacAddress()).thenReturn("00:00:00:00");
+
+        when(nic.getMac()).thenReturn("00:00:00:00");
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testPlugNicCommandNoMatchMack() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+        final Type vmtype = Type.DomainRouter;
+
+        final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+        final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
+        nics.add(intDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+
+        when(intDef.getDevName()).thenReturn("eth0");
+        when(intDef.getBrName()).thenReturn("br0");
+        when(intDef.getMacAddress()).thenReturn("00:00:00:00");
+
+        when(nic.getMac()).thenReturn("00:00:00:01");
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
+
+            when(libvirtComputingResource.getVifDriver(nic.getType())).thenReturn(vifDriver);
+
+            when(vifDriver.plug(nic, "Other PV", "")).thenReturn(interfaceDef);
+            when(interfaceDef.toString()).thenReturn("Interface");
+
+            final String interfaceDefStr = interfaceDef.toString();
+            doNothing().when(vm).attachDevice(interfaceDefStr);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
+            verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType());
+            verify(vifDriver, times(1)).plug(nic, "Other PV", "");
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPlugNicCommandLibvirtException() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+        final Type vmtype = Type.DomainRouter;
+
+        final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testPlugNicCommandInternalError() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+        final Type vmtype = Type.DomainRouter;
+
+        final PlugNicCommand command = new PlugNicCommand(nic, instanceName, vmtype);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
+        nics.add(intDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+
+        when(intDef.getDevName()).thenReturn("eth0");
+        when(intDef.getBrName()).thenReturn("br0");
+        when(intDef.getMacAddress()).thenReturn("00:00:00:00");
+
+        when(nic.getMac()).thenReturn("00:00:00:01");
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
+
+            when(libvirtComputingResource.getVifDriver(nic.getType())).thenReturn(vifDriver);
+
+            when(vifDriver.plug(nic, "Other PV", "")).thenThrow(InternalErrorException.class);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
+            verify(libvirtComputingResource, times(1)).getVifDriver(nic.getType());
+            verify(vifDriver, times(1)).plug(nic, "Other PV", "");
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testUnPlugNicCommandMatchMack() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+
+        final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef intDef = Mockito.mock(InterfaceDef.class);
+        nics.add(intDef);
+
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+        final List<VifDriver> drivers = new ArrayList<VifDriver>();
+        drivers.add(vifDriver);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+
+        when(intDef.getDevName()).thenReturn("eth0");
+        when(intDef.getBrName()).thenReturn("br0");
+        when(intDef.getMacAddress()).thenReturn("00:00:00:00");
+
+        when(nic.getMac()).thenReturn("00:00:00:00");
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
+
+            when(interfaceDef.toString()).thenReturn("Interface");
+
+            final String interfaceDefStr = interfaceDef.toString();
+            doNothing().when(vm).detachDevice(interfaceDefStr);
+
+            when(libvirtComputingResource.getAllVifDrivers()).thenReturn(drivers);
+
+            doNothing().when(vifDriver).unplug(intDef);
+
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
+            verify(libvirtComputingResource, times(1)).getAllVifDrivers();
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testUnPlugNicCommandNoNics() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+
+        final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final Domain vm = Mockito.mock(Domain.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+
+        final VifDriver vifDriver = Mockito.mock(VifDriver.class);
+        final List<VifDriver> drivers = new ArrayList<VifDriver>();
+        drivers.add(vifDriver);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, instanceName)).thenReturn(vm);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+            verify(libvirtComputingResource, times(1)).getDomain(conn, instanceName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testUnPlugNicCommandLibvirtException() {
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final String instanceName = "Test";
+
+        final UnPlugNicCommand command = new UnPlugNicCommand(nic, instanceName);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testNetworkUsageCommandNonVpc() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = false;
+        final String gatewayIP = "10.1.1.1";
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.getNetworkStats(command.getPrivateIP())).thenReturn(new long[]{10l, 10l});
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(2)).getNetworkStats(command.getPrivateIP());
+    }
+
+    @Test
+    public void testNetworkUsageCommandNonVpcCreate() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = false;
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, "create", forVpc);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.networkUsage(command.getPrivateIP(), "create", null)).thenReturn("SUCCESS");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(1)).networkUsage(command.getPrivateIP(), "create", null);
+    }
+
+    @Test
+    public void testNetworkUsageCommandVpcCreate() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = true;
+        final String gatewayIP = "10.1.1.1";
+        final String vpcCidr = "10.1.1.0/24";
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP, vpcCidr);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR())).thenReturn("SUCCESS");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), "create", command.getVpcCIDR());
+    }
+
+    @Test
+    public void testNetworkUsageCommandVpcGet() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = true;
+        final String gatewayIP = "10.1.1.1";
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, forVpc, gatewayIP);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l});
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption());
+    }
+
+    @Test
+    public void testNetworkUsageCommandVpcVpn() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = true;
+        final String gatewayIP = "10.1.1.1";
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, "vpn", forVpc, gatewayIP);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption())).thenReturn(new long[]{10l, 10l});
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(1)).getVPCNetworkStats(command.getPrivateIP(), command.getGatewayIP(), command.getOption());
+    }
+
+    @Test
+    public void testNetworkUsageCommandVpcNoOption() {
+        final String privateIP = "169.16.16.16";
+        final String domRName = "domR";
+        final boolean forVpc = true;
+        final String gatewayIP = "10.1.1.1";
+
+        final NetworkUsageCommand command = new NetworkUsageCommand(privateIP, domRName, null, forVpc, gatewayIP);
+
+        libvirtComputingResource.getNetworkStats(command.getPrivateIP());
+
+        when(libvirtComputingResource.configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR())).thenReturn("FAILURE");
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        //Being called twice, although I did not find the second place yet.
+        verify(libvirtComputingResource, times(1)).configureVPCNetworkUsage(command.getPrivateIP(), command.getGatewayIP(), command.getOption(), command.getVpcCIDR());
+    }
 }
\ No newline at end of file


[49/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8471:Automation for feature Enable configuring local storage use for system VMs at zone level

Signed-off-by: Koushik Das <ko...@apache.org>

This closes #253


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b776cbc2
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b776cbc2
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b776cbc2

Branch: refs/heads/CLOUDSTACK-8301
Commit: b776cbc2144869e4fda9801fe84a4cf5a71dd067
Parents: d423df6
Author: nitt10prashant <ni...@gmail.com>
Authored: Thu May 14 17:02:23 2015 +0530
Committer: Koushik Das <ko...@apache.org>
Committed: Tue May 19 21:32:14 2015 +0530

----------------------------------------------------------------------
 .../test_zone_level_local_storage_setting.py    | 734 +++++++++++++++++++
 1 file changed, 734 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b776cbc2/test/integration/component/maint/test_zone_level_local_storage_setting.py
----------------------------------------------------------------------
diff --git a/test/integration/component/maint/test_zone_level_local_storage_setting.py b/test/integration/component/maint/test_zone_level_local_storage_setting.py
new file mode 100644
index 0000000..466f1f9
--- /dev/null
+++ b/test/integration/component/maint/test_zone_level_local_storage_setting.py
@@ -0,0 +1,734 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Test cases for zone level settings "system.vm.use.local.storage"
+"""
+# Import Local Modules
+from marvin.cloudstackTestCase import *
+from marvin.lib.utils import *
+from marvin.lib.base import *
+from marvin.lib.common import *
+from marvin.codes import FAILED, PASS
+from requests.exceptions import ConnectionError
+
+import time
+from nose.plugins.attrib import attr
+from ddt import ddt, data
+
+
+def destroy_systemvm(self, type):
+    """
+    Destroy system vms
+    #1-List  system vms for current zone
+    #2-Destroy system vm
+    #3-Check if system vm came up after destroy
+    #4-check  system vm storage type in disk offering
+    """
+    list_response = list_ssvms(
+        self.apiclient,
+        systemvmtype=type,
+        zoneid=self.zone.id
+    )
+
+    self.assertEqual(
+        validateList(list_response)[0],
+        PASS,
+        "Check List ssvm response for  %s" %
+        type)
+
+    response = list_response[0]
+    self.debug("Destroying CPVM: %s" % response.id)
+    cmd = destroySystemVm.destroySystemVmCmd()
+    cmd.id = response.id
+    self.apiclient.destroySystemVm(cmd)
+
+    timeout = self.testdata["timeout"]
+    while True:
+        time.sleep(self.testdata["sleep"])
+        list_response = list_ssvms(
+            self.apiclient,
+            systemvmtype=type,
+            zoneid=self.zone.id
+        )
+        if validateList(list_response)[0] == PASS:
+            if list_response[0].state == 'Running':
+                break
+        if timeout == 0:
+            raise Exception("List %s call failed!" % type)
+        timeout = timeout - 1
+
+
+def storage_check(self, type, value):
+    """test if system vms are using local or shared storage
+    #1-Get zone id from db using self.zone.id
+    #2-Get service offering id from vm_instance table for running system vms
+    #3-Get use_local_storage value from disk_offering table
+    #4-Verify storage type"""
+    query_zone_id = self.dbclient.execute(
+        "select id from data_center where uuid= '%s';" % self.zone.id
+    )
+    query_so_id = self.dbclient.execute(
+        "select service_offering_id from vm_instance where type='%s'and "
+        "state='Running' and data_center_id= '%s';" %
+        (type, query_zone_id[0][0]))
+
+    query_disk_offering = self.dbclient.execute(
+        "select use_local_storage from disk_offering  where id= '%s';" %
+        query_so_id[0][0])
+
+    if value == 1:
+        self.assertEqual(query_disk_offering[0][0],
+                         1,
+                         "system vm is not using local storage"
+                         )
+    elif value == 0:
+        self.assertEqual(query_disk_offering[0][0],
+                         0,
+                         "system vm is not using shared storage"
+                         )
+    else:
+        # evil ValueError that doesn't tell you what the wrong value was
+        raise ValueError
+
+
+def create_system_so(self, offering_type, storage_type):
+    """Create system offerings """
+    self.testdata["service_offerings"]["issystem"] = "true"
+    self.testdata["service_offerings"]["systemvmtype"] = offering_type
+    self.testdata["service_offerings"]["storagetype"] = storage_type
+
+    service_offering = ServiceOffering.create(
+        self.apiclient,
+        self.testdata["service_offerings"]
+    )
+
+    if service_offering is None:
+        raise Exception("service offering not created")
+
+    list_service_response = list_service_offering(
+        self.apiclient,
+        id=service_offering.id,
+        issystem='true'
+    )
+    self.assertEqual(
+        validateList(list_service_response)[0],
+        PASS,
+        "Check List srvice offering response for  %s" %
+        type)
+
+    self.debug(
+        "Created service offering with ID: %s" %
+        service_offering.id)
+
+    self.assertEqual(
+        list_service_response[0].cpunumber,
+        self.testdata["service_offerings"]["cpunumber"],
+        "Check server id in createServiceOffering"
+    )
+    self.assertEqual(
+        list_service_response[0].cpuspeed,
+        self.testdata["service_offerings"]["cpuspeed"],
+        "Check cpuspeed in createServiceOffering"
+    )
+    self.assertEqual(
+        list_service_response[0].displaytext,
+        self.testdata["service_offerings"]["displaytext"],
+        "Check server displaytext in createServiceOfferings"
+    )
+    self.assertEqual(
+        list_service_response[0].memory,
+        self.testdata["service_offerings"]["memory"],
+        "Check memory in createServiceOffering"
+    )
+    self.assertEqual(
+        list_service_response[0].name,
+        self.testdata["service_offerings"]["name"],
+        "Check name in createServiceOffering"
+    )
+    self.assertEqual(
+        list_service_response[0].storagetype,
+        self.testdata["service_offerings"]["storagetype"],
+        "Check storagetype in createServiceOffering"
+    )
+    self._cleanup.append(service_offering)
+    return service_offering.id
+
+
+def restart_ms(self):
+    """Restart MS
+    #1-ssh into m/c running MS
+    #2-restart ms
+    #3-verify the response
+    #4-loop unitl you get list_zone api answer """
+    sshClient = SshClient(
+        self.mgtSvrDetails["mgtSvrIp"],
+        22,
+        self.mgtSvrDetails["user"],
+        self.mgtSvrDetails["passwd"]
+    )
+    command = "service cloudstack-management restart"
+    ms_restart_response = sshClient.execute(command)
+    self.assertEqual(
+        validateList(ms_restart_response)[0],
+        PASS,
+        "Check the MS restart response")
+    self.assertEqual(
+        ms_restart_response[0],
+        'Stopping cloudstack-management:[  OK  ]',
+        "MS i not stopped"
+    )
+    self.assertEqual(
+        ms_restart_response[1],
+        'Starting cloudstack-management: [  OK  ]',
+        "MS not started"
+    )
+    timeout = self.testdata["timeout"]
+    while True:
+        time.sleep(self.testdata["sleep"])
+        try:
+            list_response = Zone.list(
+                self.apiclient
+            )
+            if validateList(list_response)[0] == PASS:
+                break
+        except ConnectionError as e:
+            self.debug("list zone response is not available due to  %s" % e)
+
+        if timeout == 0:
+            raise Exception("Ms is not comming up !")
+        timeout = timeout - 1
+
+
+def update_global_settings(self, value, name, zoneid=None):
+    """Update Gloabal/zonelevel settings and verify
+    #1-Update configuration
+    #2-Restart ms if zone id is None"""
+    Configurations.update(self.apiclient,
+                          name=name,
+                          zoneid=zoneid,
+                          value=value
+                          )
+    if zoneid is None:
+        restart_ms(self)
+
+    list_conf = Configurations.list(self.apiclient,
+                                    name=name,
+                                    zoneid=zoneid)
+
+    self.assertEqual(
+        validateList(list_conf)[0],
+        PASS,
+        "Check List configuration  response for  %s" % name)
+
+    self.assertEqual(
+        str(list_conf[0].value),
+        str(value),
+        "Check if configuration values are equal"
+    )
+
+
+def str_to_bool(s):
+    """Converts str "True/False to Boolean TRUE/FALSE"""
+    if s == 'true':
+        return True
+    elif s == 'false':
+        return False
+    else:
+        # evil ValueError that doesn't tell you what the wrong value was
+        raise ValueError
+
+
+@ddt
+class TestSystemVmLocalStorage(cloudstackTestCase):
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestSystemVmLocalStorage, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.dbclient = cls.testClient.getDbConnection()
+        cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__
+        cls.testdata = testClient.getParsedTestDataConfig()
+        # Get Zone, and template Domain
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient)
+        cls.testdata["mode"] = cls.zone.networktype
+        cls.hypervisor = testClient.getHypervisorInfo()
+        cls._cleanup = []
+
+        list_local_storage_pool = StoragePool.list(
+            cls.apiclient,
+            scope='HOST',
+            zoneid=cls.zone.id,
+
+        )
+
+        if list_local_storage_pool is None:
+
+            Configurations.update(
+                cls.apiclient,
+                value='true',
+                name='system.vm.use.local.storage',
+                zoneid=cls.zone.id
+            )
+
+            # Restart MS
+            sshClient = SshClient(
+                cls.mgtSvrDetails["mgtSvrIp"],
+                22,
+                cls.mgtSvrDetails["user"],
+                cls.mgtSvrDetails["passwd"]
+            )
+            command = "service cloudstack-management restart"
+            ms_restart_response = sshClient.execute(command)
+
+            if validateList(ms_restart_response)[0] != PASS:
+                raise Exception("Check the MS restart response")
+            if ms_restart_response[
+                    0] != 'Stopping cloudstack-management:[  OK  ]':
+                raise Exception("MS i not stopped")
+
+            if ms_restart_response[
+                    1] != 'Starting cloudstack-management: [  OK  ]':
+                raise Exception("MS not started")
+
+            timeout = cls.testdata["timeout"]
+            while True:
+                # time.sleep(cls.testdata["sleep"])
+                try:
+                    list_response = Zone.list(
+                        cls.apiclient
+                    )
+                    if validateList(list_response)[0] == PASS:
+                        break
+                except ConnectionError as e:
+                    cls.debug(
+                        "list zone response is not available due to  %s" %
+                        e)
+
+                if timeout == 0:
+                    raise Exception("Ms is not comming up !")
+
+                time.sleep(cls.testdata["sleep"])
+                timeout = timeout - 1
+
+            list_local_storage_pool = StoragePool.list(
+                cls.apiclient,
+                scope='HOST',
+                zoneid=cls.zone.id,
+
+            )
+            if list_local_storage_pool is None:
+                raise Exception("Could not discover local storage pool")
+
+        try:
+            cls.account = Account.create(cls.apiclient,
+                                         cls.testdata["account"],
+                                         domainid=cls.domain.id
+                                         )
+            cls._cleanup.append(cls.account)
+
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+
+        return
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception("Warning:Exception during cleanup: %s" % e)
+
+    @attr(tags=["advanced", "basic"])
+    @data(
+        'consoleproxy',
+        'secondarystoragevm',
+        'domainrouter',
+        'internalloadbalancervm')
+    def test_01_list_system_offerngs(self, value):
+        """List service offerings for systemvms and verify there should be two
+        (local and shared) SO  for each system vm"""
+
+        list_custom_so = ServiceOffering.list(self.apiclient,
+                                              issystem='true',
+                                              listall='true',
+                                              systemvmtype=value
+                                              )
+
+        self.assertEqual(
+            validateList(list_custom_so)[0],
+            PASS,
+            "Check List service offerings response for  %s" %
+            value)
+
+        local_custom_so = []
+        for item in list_custom_so:
+            if(str(item.defaultuse) == 'True'):
+                local_custom_so.append(item.storagetype)
+
+        self.assertEqual(
+            len(local_custom_so),
+            2,
+            "Check default system offering for system vm type %s" % value)
+        if 'local' in local_custom_so and 'shared' in local_custom_so:
+            self.debug(
+                "there are exactly to Service offerings{share,local} are "
+                "there for system vm %s" %
+                value)
+        else:
+            raise Exception(
+                "check local and shared service offerings for %s" %
+                value)
+
+    @attr(tags=["advanced", "basic"])
+    @data('consoleproxy', 'secondarystoragevm')
+    def test_02_system_vm_storage(self, value):
+        """ Check if system vms are honouring zone level setting
+        system.vm.use.local.storage
+        1-List zone level config
+        2-update the zone level config with service offering uuid
+        3-destroy system vms
+        4-check used storage by system vms
+        """
+        # 1 List zone level config
+        if value == "consoleproxy":
+            update_global_settings(
+                self,
+                value=None,
+                name="consoleproxy.service.offering")
+
+        if value == "secondarystoragevm":
+            update_global_settings(
+                self,
+                value=None,
+                name="secstorage.service.offering")
+
+        list_conf = Configurations.list(self.apiclient,
+                                        name="system.vm.use.local.storage",
+                                        zoneid=self.zone.id)
+        self.assertEqual(
+            validateList(list_conf)[0],
+            PASS,
+            "Check List configuration response for "
+            "system.vm.use.local.storage")
+
+        val = str_to_bool(list_conf[0].value)
+        # 2 update the zone level config with service offering uuid
+        update_global_settings(self,
+                               value=((str(not(val)).lower())),
+                               name='system.vm.use.local.storage',
+                               zoneid=self.zone.id)
+
+        # 3,4 for cpvm
+        destroy_systemvm(self, value)
+        storage_check(self, value, int(not(val)))
+
+        # 2 update the zone level config with service offering uuid
+        update_global_settings(
+            self,
+            value=(
+                str(val).lower()),
+            name='system.vm.use.local.storage',
+            zoneid=self.zone.id)
+        # 3,4 for cpvm
+        destroy_systemvm(self, value)
+        storage_check(self, value, int(val))
+
+        # 1 List zone level config
+        if value == "consoleproxy":
+            update_global_settings(
+                self,
+                value=None,
+                name="consoleproxy.service.offering")
+
+        if value == "secondarystoragevm":
+            update_global_settings(
+                self,
+                value=None,
+                name="secstorage.service.offering")
+
+    @attr(tags=["advanced", "basic"])
+    @data('consoleproxy', 'secondarystoragevm')
+    def test_03_custom_so(self, value):
+        """
+        update global setting with system offering and check if it is being
+        honoured
+        1-update zone level settings "system.vm.use.local.storage={true,false}}
+        to use local storage
+        2-create system offerings{shared,local}
+        3-update global settings with system offering uuid and restart ms
+        4-destroy system vms
+        5-Check if new system vms are using offering  updated in global
+        settings
+        """
+
+        # 1-update zone level settings "system.vm.use.local.storage"
+        # to use local storage
+        update_global_settings(
+            self,
+            value='true',
+            name='system.vm.use.local.storage',
+            zoneid=self.zone.id)
+        # 2-create system offerings
+
+        created_so_id = create_system_so(self, value, "shared")
+
+        if value == "consoleproxy":
+            name = "consoleproxy.service.offering"
+        elif value == 'secondarystoragevm':
+            name = 'secstorage.service.offering'
+        else:
+            raise Exception(
+                "type paramter is not correct it should be  system vm "
+                "type{console proxy,secsroragevm}")
+
+        # 3-update global settings with system offering uuid
+        update_global_settings(self, value=created_so_id, name=name)
+
+        # 4-destroy system vms
+        destroy_systemvm(self, value)
+
+        # 5-Check if new system vms are using offering  updated in global
+        # settings
+
+        query_zone_id = self.dbclient.execute(
+            "select id from data_center where uuid= '%s';" % self.zone.id
+        )
+        query_so_id = self.dbclient.execute(
+            "select service_offering_id from vm_instance where type='%s'and "
+            "state='Running' and data_center_id= '%s';" %
+            (value, query_zone_id[0][0]))
+        query_disk_offering = self.dbclient.execute(
+            "select uuid from disk_offering  where id= '%s';" %
+            query_so_id[0][0])
+
+        self.assertEqual(
+            created_so_id,
+            query_disk_offering[0][0],
+            "system vms are not using service offering mentioned in "
+            "global settings")
+
+        # 6-repeate 1 with system.vm.use.local.storage=false
+        update_global_settings(
+            self,
+            value='false',
+            name='system.vm.use.local.storage',
+            zoneid=self.zone.id)
+        # 7-repeate 2 with storage type local
+        created_so_id = create_system_so(self, value, "local")
+        # 8-repeate 3
+        update_global_settings(self, value=created_so_id, name=name)
+
+        # 9-repeate 4
+        destroy_systemvm(self, value)
+        # repeate 5
+        query_zone_id = self.dbclient.execute(
+            "select id from data_center where uuid= '%s';" % self.zone.id
+        )
+        query_so_id = self.dbclient.execute(
+            "select service_offering_id from vm_instance where type='%s'and "
+            "state='Running' and data_center_id= '%s';" %
+            (value, query_zone_id[0][0]))
+        query_disk_offering = self.dbclient.execute(
+            "select uuid from disk_offering  where id= '%s';" %
+            query_so_id[0][0])
+
+        self.assertEqual(
+            created_so_id,
+            query_disk_offering[0][0],
+            "system vms are not using service offering mentioned in"
+            " global settings")
+
+    @attr(tags=["advanced"])
+    def test_04_router_vms(self):
+        """ Check if router  vm is honouring zone level setting
+        system.vm.use.local.storage"""
+
+        # 1-list configurations
+        list_conf = Configurations.list(self.apiclient,
+                                        name="system.vm.use.local.storage",
+                                        zoneid=self.zone.id)
+        self.assertEqual(
+            validateList(list_conf)[0],
+            PASS,
+            "Check List configuration response for "
+            "system.vm.use.local.storage")
+
+        # 2-create network offering
+        self.network_offering = NetworkOffering.create(
+            self.apiclient,
+            self.testdata["network_offering"],
+            ispersistent='true'
+        )
+
+        # 3-list netwrok offerings
+        list_nw_of = NetworkOffering.list(self.apiclient,
+                                          id=self.network_offering.id)
+        self.assertEqual(
+            validateList(list_nw_of)[0],
+            PASS,
+            "Check the list network response"
+        )
+        self.assertEqual(
+            str(list_nw_of[0].id),
+            str(self.network_offering.id),
+            "Check the created network offering id and "
+            "listed network offering id"
+        )
+        self._cleanup.append(self.network_offering)
+
+        # 4-Enable network offering
+        self.network_offering.update(self.apiclient, state='Enabled')
+
+        # 5-List network offering
+        list_nw_of1 = NetworkOffering.list(self.apiclient,
+                                           id=self.network_offering.id)
+        self.assertEqual(
+            validateList(list_nw_of1)[0],
+            PASS,
+            "Check the list network response"
+        )
+        self.assertEqual(
+            str(list_nw_of1[0].state),
+            "Enabled",
+            "Check the created network state"
+        )
+
+        # 6-crete network using network offering
+        self.network = Network.create(
+            self.apiclient,
+            self.testdata["network"],
+            networkofferingid=self.network_offering.id,
+            zoneid=self.zone.id,
+            accountid=self.account.name,
+            domainid=self.account.domainid
+        )
+        # 7-List network
+        list_network = Network.list(self.apiclient,
+                                    accountid=self.account.name,
+                                    domainid=self.account.domainid,
+                                    id=self.network.id)
+        self.assertEqual(validateList(list_network)[0],
+                         PASS,
+                         "check list netwok response ")
+        self.assertEqual(
+            list_network[0].id,
+            self.network.id,
+            "List network id %s and created network id %s  does not match" %
+            (list_network[0].id,
+             self.network.id))
+
+        # 8-List router
+        list_router = Router.list(self.apiclient,
+                                  networkid=self.network.id,
+                                  accountid=self.account.name,
+                                  domainid=self.account.domainid)
+
+        self.assertEqual(
+            validateList(list_router)[0],
+            PASS,
+            "check list router response")
+
+        # 9-List service offerings
+        list_so = ServiceOffering.list(self.apiclient,
+                                       issystem='true',
+                                       id=list_router[0].serviceofferingid
+                                       )
+        self.assertEqual(
+            validateList(list_so)[0],
+            PASS,
+            "check list service offering response")
+        if list_conf[0].value == 'true':
+            storage_type = 'local'
+            value1 = 'false'
+        elif list_conf[0].value == 'false':
+            storage_type = 'shared'
+            value1 = 'true'
+        else:
+            raise Exception("check list_conf[0].value")
+        self.assertEqual(
+            list_so[0].storagetype,
+            storage_type,
+            "Check VR storage type and zone level settig"
+        )
+
+        # 10-Update zone level setting
+        update_global_settings(
+            self,
+            value=value1,
+            name="system.vm.use.local.storage",
+            zoneid=self.zone.id)
+
+        # 11-List configurations
+        list_conf1 = Configurations.list(self.apiclient,
+                                         name="system.vm.use.local.storage",
+                                         zoneid=self.zone.id)
+        self.assertEqual(
+            validateList(list_conf1)[0],
+            PASS,
+            "Check List configuration response for "
+            "system.vm.use.local.storage")
+
+        self.assertEqual(
+            list_conf1[0].value,
+            value1,
+            "Check the system.vm.use.local.storage value"
+        )
+        self.network.restart(self.apiclient,
+                             cleanup='true'
+                             )
+        # 12-List network
+        list_network1 = Network.list(self.apiclient,
+                                     accountid=self.account.name,
+                                     domainid=self.account.domainid,
+                                     id=self.network.id)
+        self.assertEqual(validateList(list_network1)[0],
+                         PASS,
+                         "check list netwok response ")
+
+        # 13-list VR
+        list_router1 = Router.list(self.apiclient,
+                                   networkid=list_network1[0].id,
+                                   accountid=self.account.name,
+                                   domainid=self.account.domainid)
+        self.assertEqual(
+            validateList(list_router1)[0],
+            PASS,
+            "check list router response"
+        )
+        # 14-list service offerings
+        list_so1 = ServiceOffering.list(self.apiclient,
+                                        issystem='true',
+                                        id=list_router1[0].serviceofferingid
+                                        )
+        self.assertEqual(
+            validateList(list_so1)[0],
+            PASS,
+            "check list service offering response"
+        )
+        if list_conf1[0].value == 'true':
+            storage_type1 = 'local'
+        elif list_conf1[0].value == 'false':
+            storage_type1 = 'shared'
+        else:
+            raise Exception("check list_conf[0].value")
+        self.assertEqual(
+            list_so1[0].storagetype,
+            storage_type1,
+            "Check VR storage type and zone level settings"
+        )


[47/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8301: Enable configuring local storage use for system VMs at zone level
Code cleanup, added helper method to get default system offering based on "system.vm.use.local.storage".


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/d423df66
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/d423df66
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/d423df66

Branch: refs/heads/CLOUDSTACK-8301
Commit: d423df66cc73c47d363736b7762e820d85f05b93
Parents: 3f7e31e
Author: Koushik Das <ko...@apache.org>
Authored: Thu May 14 17:30:19 2015 +0530
Committer: Koushik Das <ko...@apache.org>
Committed: Tue May 19 21:32:14 2015 +0530

----------------------------------------------------------------------
 .../com/cloud/service/dao/ServiceOfferingDao.java    |  2 ++
 .../cloud/service/dao/ServiceOfferingDaoImpl.java    | 15 +++++++++++++++
 .../com/cloud/network/lb/LoadBalanceRuleHandler.java | 12 +-----------
 .../lb/InternalLoadBalancerVMManagerImpl.java        | 12 +-----------
 .../cloud/consoleproxy/ConsoleProxyManagerImpl.java  | 12 +-----------
 .../deployment/RouterDeploymentDefinition.java       | 10 +---------
 .../deployment/RouterDeploymentDefinitionTest.java   |  2 +-
 .../VpcRouterDeploymentDefinitionTest.java           |  2 +-
 .../SecondaryStorageManagerImpl.java                 | 12 +-----------
 9 files changed, 24 insertions(+), 55 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
index 98dc317..aae61a1 100644
--- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
+++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
@@ -55,4 +55,6 @@ public interface ServiceOfferingDao extends GenericDao<ServiceOfferingVO, Long>
     boolean isDynamic(long serviceOfferingId);
 
     ServiceOfferingVO getcomputeOffering(ServiceOfferingVO serviceOffering, Map<String, String> customParameters);
+
+    ServiceOfferingVO findDefaultSystemOffering(String offeringName, Boolean useLocalStorage);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
index a3ffbc1..4a5a8b5 100644
--- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
+++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
@@ -276,4 +276,19 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase<ServiceOfferingVO, Lo
 
         return list;
     }
+
+    @Override
+    public ServiceOfferingVO findDefaultSystemOffering(String offeringName, Boolean useLocalStorage) {
+        String name = offeringName;
+        if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+            name += "-Local";
+        }
+        ServiceOfferingVO serviceOffering = findByName(name);
+        if (serviceOffering == null) {
+            String message = "System service offering " + name + " not found";
+            s_logger.error(message);
+            throw new CloudRuntimeException(message);
+        }
+        return serviceOffering;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
index f2c4685..e90af37 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
@@ -282,17 +282,7 @@ public class LoadBalanceRuleHandler {
                     userId =  _userDao.listByAccount(owner.getAccountId()).get(0).getId();
                 }
 
-                String offeringName = ServiceOffering.elbVmDefaultOffUniqueName;
-                Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
-                if (useLocalStorage != null && useLocalStorage.booleanValue()) {
-                    offeringName += "-Local";
-                }
-                ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findByName(offeringName);
-                if (elasticLbVmOffering == null) {
-                    String message = "System service offering " + offeringName + " not found";
-                    s_logger.error(message);
-                    throw new CloudRuntimeException(message);
-                }
+                ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.elbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
                 elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX),
                         template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN,
                         elasticLbVmOffering.getOfferHA(), false, null);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index 818ad88..4bd852d 100644
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@ -623,17 +623,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
             final LinkedHashMap<Network, List<? extends NicProfile>> networks = createInternalLbVmNetworks(guestNetwork, plan, requestedGuestIp);
             long internalLbVmOfferingId = _internalLbVmOfferingId;
             if (internalLbVmOfferingId == 0L) {
-                String offeringName = ServiceOffering.internalLbVmDefaultOffUniqueName;
-                Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
-                if (useLocalStorage != null && useLocalStorage.booleanValue()) {
-                    offeringName += "-Local";
-                }
-                ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(offeringName);
-                if (serviceOffering == null) {
-                    String message = "System service offering " + offeringName + " not found";
-                    s_logger.error(message);
-                    throw new CloudRuntimeException(message);
-                }
+                ServiceOfferingVO serviceOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.internalLbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
                 internalLbVmOfferingId = serviceOffering.getId();
             }
             //Pass startVm=false as we are holding the network lock that needs to be released at the end of vm allocation

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
index f8d7474..476cc8e 100644
--- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
+++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
@@ -718,17 +718,7 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
 
         ServiceOfferingVO serviceOffering = _serviceOffering;
         if (serviceOffering == null) {
-            String offeringName = ServiceOffering.consoleProxyDefaultOffUniqueName;
-            Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
-            if (useLocalStorage != null && useLocalStorage.booleanValue()) {
-                offeringName += "-Local";
-            }
-            serviceOffering = _offeringDao.findByName(offeringName);
-            if (serviceOffering == null) {
-                String message = "System service offering " + offeringName + " not found";
-                s_logger.error(message);
-                throw new CloudRuntimeException(message);
-            }
+            serviceOffering = _offeringDao.findDefaultSystemOffering(ServiceOffering.consoleProxyDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
         }
         ConsoleProxyVO proxy =
             new ConsoleProxyVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
----------------------------------------------------------------------
diff --git a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
index 569200c..2d04a7e 100644
--- a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
+++ b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
@@ -360,15 +360,7 @@ public class RouterDeploymentDefinition {
     }
 
     protected void findDefaultServiceOfferingId() {
-        String offeringName = ServiceOffering.routerDefaultOffUniqueName;
-        Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
-        if (useLocalStorage != null && useLocalStorage.booleanValue()) {
-            offeringName += "-Local";
-        }
-        ServiceOfferingVO serviceOffering = serviceOfferingDao.findByName(offeringName);
-        if (serviceOffering == null) {
-            throw new CloudRuntimeException("System service offering " + offeringName + " not found");
-        }
+        ServiceOfferingVO serviceOffering = serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.routerDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId()));
         serviceOfferingId = serviceOffering.getId();
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
index b266f88..1570a2e 100644
--- a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
+++ b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
@@ -658,7 +658,7 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
         when(mockNw.getNetworkOfferingId()).thenReturn(OFFERING_ID);
         when(mockNetworkOfferingDao.findById(OFFERING_ID)).thenReturn(mockNwOfferingVO);
         when(mockNwOfferingVO.getServiceOfferingId()).thenReturn(null);
-        when(mockServiceOfferingDao.findByName(Matchers.anyString())).thenReturn(mockSvcOfferingVO);
+        when(mockServiceOfferingDao.findDefaultSystemOffering(Matchers.anyString(), Matchers.anyBoolean())).thenReturn(mockSvcOfferingVO);
         when(mockSvcOfferingVO.getId()).thenReturn(DEFAULT_OFFERING_ID);
 
         // Execute

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java b/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
index 5a34ebf..13c20ae 100644
--- a/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
+++ b/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
@@ -184,7 +184,7 @@ public class VpcRouterDeploymentDefinitionTest extends RouterDeploymentDefinitio
         final VpcOfferingVO vpcOffering = mock(VpcOfferingVO.class);
         when(mockVpcOffDao.findById(VPC_OFFERING_ID)).thenReturn(vpcOffering);
         when(vpcOffering.getServiceOfferingId()).thenReturn(null);
-        when(mockServiceOfferingDao.findByName(Matchers.anyString())).thenReturn(mockSvcOfferingVO);
+        when(mockServiceOfferingDao.findDefaultSystemOffering(Matchers.anyString(), Matchers.anyBoolean())).thenReturn(mockSvcOfferingVO);
         when(mockSvcOfferingVO.getId()).thenReturn(DEFAULT_OFFERING_ID);
 
         // Execute

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/d423df66/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java b/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
index 445852d..453a4cb 100644
--- a/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
+++ b/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
@@ -578,17 +578,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
 
         ServiceOfferingVO serviceOffering = _serviceOffering;
         if (serviceOffering == null) {
-            String offeringName = ServiceOffering.ssvmDefaultOffUniqueName;
-            Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
-            if (useLocalStorage != null && useLocalStorage.booleanValue()) {
-                offeringName += "-Local";
-            }
-            serviceOffering = _offeringDao.findByName(offeringName);
-            if (serviceOffering == null) {
-                String message = "System service offering " + offeringName + " not found";
-                s_logger.error(message);
-                throw new CloudRuntimeException(message);
-            }
+            serviceOffering = _offeringDao.findDefaultSystemOffering(ServiceOffering.ssvmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
         }
         SecondaryStorageVmVO secStorageVm =
             new SecondaryStorageVmVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,


[07/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtModifySshKeysCommandWrapper
  - 1 unit test added
  - KVM hypervisor plugin with 12.3% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/6f757c6b
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/6f757c6b
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/6f757c6b

Branch: refs/heads/CLOUDSTACK-8301
Commit: 6f757c6bf062d75c726f12dac49548dad9104cd0
Parents: f14c7c2
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed Apr 29 15:24:18 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:10 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 210 +++++++------------
 .../LibvirtModifySshKeysCommandWrapper.java     | 112 ++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../resource/LibvirtComputingResourceTest.java  |  16 ++
 4 files changed, 201 insertions(+), 139 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6f757c6b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 788a3e4..62c7148 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -105,7 +105,6 @@ import com.cloud.agent.api.MaintainAnswer;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
-import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolAnswer;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
@@ -279,19 +278,82 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
     private long _hvVersion;
     private long _kernelVersion;
+    private int _timeout;
+
     private KVMHAMonitor _monitor;
-    private static final String SSHKEYSPATH = "/root/.ssh";
-    private static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud";
-    private static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud";
+    public static final String SSHKEYSPATH = "/root/.ssh";
+    public static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud";
+    public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud";
+
     private String _mountPoint = "/mnt";
     StorageLayer _storage;
     private KVMStoragePoolManager _storagePoolMgr;
 
     private VifDriver _defaultVifDriver;
     private Map<TrafficType, VifDriver> _trafficTypeVifDrivers;
+
     protected static final String DEFAULT_OVS_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.OvsVifDriver";
     protected static final String DEFAULT_BRIDGE_VIF_DRIVER_CLASS_NAME = "com.cloud.hypervisor.kvm.resource.BridgeVifDriver";
 
+    protected HypervisorType _hypervisorType;
+    protected String _hypervisorURI;
+    protected long _hypervisorLibvirtVersion;
+    protected long _hypervisorQemuVersion;
+    protected String _hypervisorPath;
+    protected String _networkDirectSourceMode;
+    protected String _networkDirectDevice;
+    protected String _sysvmISOPath;
+    protected String _privNwName;
+    protected String _privBridgeName;
+    protected String _linkLocalBridgeName;
+    protected String _publicBridgeName;
+    protected String _guestBridgeName;
+    protected String _privateIp;
+    protected String _pool;
+    protected String _localGateway;
+    private boolean _canBridgeFirewall;
+    protected String _localStoragePath;
+    protected String _localStorageUUID;
+    protected boolean _noMemBalloon = false;
+    protected String _guestCpuMode;
+    protected String _guestCpuModel;
+    protected boolean _noKvmClock;
+    protected String _videoHw;
+    protected int _videoRam;
+    protected Pair<Integer,Integer> hostOsVersion;
+    protected int _migrateSpeed;
+    protected int _migrateDowntime;
+    protected int _migratePauseAfter;
+
+    private final Map <String, String> _pifs = new HashMap<String, String>();
+    private final Map<String, VmStats> _vmStats = new ConcurrentHashMap<String, VmStats>();
+
+    protected static final MessageFormat SnapshotXML = new MessageFormat("   <domainsnapshot>" + "       <name>{0}</name>" + "          <domain>"
+            + "            <uuid>{1}</uuid>" + "        </domain>" + "    </domainsnapshot>");
+
+    protected static final HashMap<DomainState, PowerState> s_powerStatesTable;
+    static {
+        s_powerStatesTable = new HashMap<DomainState, PowerState>();
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTOFF, PowerState.PowerOff);
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_PAUSED, PowerState.PowerOn);
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_RUNNING, PowerState.PowerOn);
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_BLOCKED, PowerState.PowerOn);
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_NOSTATE, PowerState.PowerUnknown);
+        s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTDOWN, PowerState.PowerOff);
+    }
+
+    protected List<String> _vmsKilled = new ArrayList<String>();
+
+    private VirtualRoutingResource _virtRouterResource;
+
+    private String _pingTestPath;
+
+    private int _dom0MinMem;
+
+    protected boolean _disconnected = true;
+    protected int _cmdsTimeout;
+    protected int _stopTimeout;
+
     @Inject
     private LibvirtConnectionWrapper libvirtConnectionWrapper;
 
@@ -392,6 +454,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _pingTestPath;
     }
 
+    public int getTimeout() {
+        return _timeout;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -424,66 +490,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return null;
     }
 
-    protected static final MessageFormat SnapshotXML = new MessageFormat("   <domainsnapshot>" + "       <name>{0}</name>" + "          <domain>"
-            + "            <uuid>{1}</uuid>" + "        </domain>" + "    </domainsnapshot>");
-
-    protected HypervisorType _hypervisorType;
-    protected String _hypervisorURI;
-    protected long _hypervisorLibvirtVersion;
-    protected long _hypervisorQemuVersion;
-    protected String _hypervisorPath;
-    protected String _networkDirectSourceMode;
-    protected String _networkDirectDevice;
-    protected String _sysvmISOPath;
-    protected String _privNwName;
-    protected String _privBridgeName;
-    protected String _linkLocalBridgeName;
-    protected String _publicBridgeName;
-    protected String _guestBridgeName;
-    protected String _privateIp;
-    protected String _pool;
-    protected String _localGateway;
-    private boolean _canBridgeFirewall;
-    protected String _localStoragePath;
-    protected String _localStorageUUID;
-    protected boolean _noMemBalloon = false;
-    protected String _guestCpuMode;
-    protected String _guestCpuModel;
     protected List<String> _cpuFeatures;
-    protected boolean _noKvmClock;
-    protected String _videoHw;
-    protected int _videoRam;
-    protected Pair<Integer,Integer> hostOsVersion;
-    protected int _migrateSpeed;
-    protected int _migrateDowntime;
-    protected int _migratePauseAfter;
-
-    private final Map <String, String> _pifs = new HashMap<String, String>();
-    private final Map<String, VmStats> _vmStats = new ConcurrentHashMap<String, VmStats>();
-
-    protected boolean _disconnected = true;
-    protected int _timeout;
-    protected int _cmdsTimeout;
-    protected int _stopTimeout;
-
-    protected static final HashMap<DomainState, PowerState> s_powerStatesTable;
-    static {
-        s_powerStatesTable = new HashMap<DomainState, PowerState>();
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTOFF, PowerState.PowerOff);
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_PAUSED, PowerState.PowerOn);
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_RUNNING, PowerState.PowerOn);
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_BLOCKED, PowerState.PowerOn);
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_NOSTATE, PowerState.PowerUnknown);
-        s_powerStatesTable.put(DomainState.VIR_DOMAIN_SHUTDOWN, PowerState.PowerOff);
-    }
-
-    protected List<String> _vmsKilled = new ArrayList<String>();
-
-    private VirtualRoutingResource _virtRouterResource;
-
-    private String _pingTestPath;
-
-    private int _dom0MinMem;
 
     protected enum BridgeType {
         NATIVE, OPENVSWITCH
@@ -1298,9 +1305,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof ModifySshKeysCommand) {
-                return execute((ModifySshKeysCommand)cmd);
-            } else if (cmd instanceof MaintainCommand) {
+            if (cmd instanceof MaintainCommand) {
                 return execute((MaintainCommand)cmd);
             } else if (cmd instanceof CreateCommand) {
                 return execute((CreateCommand)cmd);
@@ -3001,79 +3006,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected Answer execute(final ModifySshKeysCommand cmd) {
-        final File sshKeysDir = new File(SSHKEYSPATH);
-        String result = null;
-        if (!sshKeysDir.exists()) {
-            // Change permissions for the 700
-            final Script script = new Script("mkdir", _timeout, s_logger);
-            script.add("-m", "700");
-            script.add(SSHKEYSPATH);
-            script.execute();
-
-            if (!sshKeysDir.exists()) {
-                s_logger.debug("failed to create directory " + SSHKEYSPATH);
-            }
-        }
-
-        final File pubKeyFile = new File(SSHPUBKEYPATH);
-        if (!pubKeyFile.exists()) {
-            try {
-                pubKeyFile.createNewFile();
-            } catch (final IOException e) {
-                result = "Failed to create file: " + e.toString();
-                s_logger.debug(result);
-            }
-        }
-
-        if (pubKeyFile.exists()) {
-            try (FileOutputStream pubkStream = new FileOutputStream(pubKeyFile)) {
-                pubkStream.write(cmd.getPubKey().getBytes());
-            } catch (final FileNotFoundException e) {
-                result = "File" + SSHPUBKEYPATH + "is not found:"
-                        + e.toString();
-                s_logger.debug(result);
-            } catch (final IOException e) {
-                result = "Write file " + SSHPUBKEYPATH + ":" + e.toString();
-                s_logger.debug(result);
-            }
-        }
-
-        final File prvKeyFile = new File(SSHPRVKEYPATH);
-        if (!prvKeyFile.exists()) {
-            try {
-                prvKeyFile.createNewFile();
-            } catch (final IOException e) {
-                result = "Failed to create file: " + e.toString();
-                s_logger.debug(result);
-            }
-        }
-
-        if (prvKeyFile.exists()) {
-            final String prvKey = cmd.getPrvKey();
-            try (FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);){
-                if ( prvKStream != null) {
-                    prvKStream.write(prvKey.getBytes());
-                }
-            } catch (final FileNotFoundException e) {
-                result = "File" + SSHPRVKEYPATH + "is not found:" + e.toString();
-                s_logger.debug(result);
-            } catch (final IOException e) {
-                result = "Write file " + SSHPRVKEYPATH + ":" + e.toString();
-                s_logger.debug(result);
-            }
-            final 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(final Connect conn, final String vmName, final LibvirtVMDef vm) {
         if (vm != null && vm.getDevices() != null) {
             cleanupVMNetworks(conn, vm.getDevices().getInterfaces());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6f757c6b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
new file mode 100644
index 0000000..d5943c5
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifySshKeysCommandWrapper.java
@@ -0,0 +1,112 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ModifySshKeysCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtModifySshKeysCommandWrapper extends CommandWrapper<ModifySshKeysCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtModifySshKeysCommandWrapper.class);
+
+    @Override
+    public Answer execute(final ModifySshKeysCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final File sshKeysDir = new File(LibvirtComputingResource.SSHKEYSPATH);
+        String result = null;
+        if (!sshKeysDir.exists()) {
+            // Change permissions for the 700
+            final Script script = new Script("mkdir", libvirtComputingResource.getTimeout(), s_logger);
+            script.add("-m", "700");
+            script.add(LibvirtComputingResource.SSHKEYSPATH);
+            script.execute();
+
+            if (!sshKeysDir.exists()) {
+                s_logger.debug("failed to create directory " + LibvirtComputingResource.SSHKEYSPATH);
+            }
+        }
+
+        final File pubKeyFile = new File(LibvirtComputingResource.SSHPUBKEYPATH);
+        if (!pubKeyFile.exists()) {
+            try {
+                pubKeyFile.createNewFile();
+            } catch (final IOException e) {
+                result = "Failed to create file: " + e.toString();
+                s_logger.debug(result);
+            }
+        }
+
+        if (pubKeyFile.exists()) {
+            try (FileOutputStream pubkStream = new FileOutputStream(pubKeyFile)) {
+                pubkStream.write(command.getPubKey().getBytes());
+            } catch (final FileNotFoundException e) {
+                result = "File" + LibvirtComputingResource.SSHPUBKEYPATH + "is not found:"
+                        + e.toString();
+                s_logger.debug(result);
+            } catch (final IOException e) {
+                result = "Write file " + LibvirtComputingResource.SSHPUBKEYPATH + ":" + e.toString();
+                s_logger.debug(result);
+            }
+        }
+
+        final File prvKeyFile = new File(LibvirtComputingResource.SSHPRVKEYPATH);
+        if (!prvKeyFile.exists()) {
+            try {
+                prvKeyFile.createNewFile();
+            } catch (final IOException e) {
+                result = "Failed to create file: " + e.toString();
+                s_logger.debug(result);
+            }
+        }
+
+        if (prvKeyFile.exists()) {
+            final String prvKey = command.getPrvKey();
+            try (FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);){
+                if ( prvKStream != null) {
+                    prvKStream.write(prvKey.getBytes());
+                }
+            } catch (final FileNotFoundException e) {
+                result = "File" + LibvirtComputingResource.SSHPRVKEYPATH + "is not found:" + e.toString();
+                s_logger.debug(result);
+            } catch (final IOException e) {
+                result = "Write file " + LibvirtComputingResource.SSHPRVKEYPATH + ":" + e.toString();
+                s_logger.debug(result);
+            }
+            final Script script = new Script("chmod", libvirtComputingResource.getTimeout(), s_logger);
+            script.add("600", LibvirtComputingResource.SSHPRVKEYPATH);
+            script.execute();
+        }
+
+        if (result != null) {
+            return new Answer(command, false, result);
+        } else {
+            return new Answer(command, true, null);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6f757c6b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index daa5a0c..c5001c4 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -31,6 +31,7 @@ import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MigrateCommand;
+import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -78,6 +79,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(WatchConsoleProxyLoadCommand.class, new LibvirtWatchConsoleProxyLoadCommandWrapper());
         linbvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
         linbvirtCommands.put(GetVncPortCommand.class, new LibvirtGetVncPortCommandWrapper());
+        linbvirtCommands.put(ModifySshKeysCommand.class, new LibvirtModifySshKeysCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/6f757c6b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 09a9e36..a2b3b7f 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -73,6 +73,7 @@ import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MigrateCommand;
+import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -1201,4 +1202,19 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testModifySshKeysCommand() {
+        final ModifySshKeysCommand command = new ModifySshKeysCommand("", "");
+
+        when(libvirtComputingResource.getTimeout()).thenReturn(0);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getTimeout();
+    }
 }
\ No newline at end of file


[36/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
listPortForwardingRules: fix typo in doc

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #248


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/e8f8e0e3
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/e8f8e0e3
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/e8f8e0e3

Branch: refs/heads/CLOUDSTACK-8301
Commit: e8f8e0e3f23732559a2664b3b9573be8ef76f479
Parents: 7451f13
Author: Rene Moser <re...@apache.org>
Authored: Wed May 13 01:13:00 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Wed May 13 15:43:53 2015 +0200

----------------------------------------------------------------------
 .../api/command/user/firewall/ListPortForwardingRulesCmd.java      | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/e8f8e0e3/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java
index cde2563..5d44815 100644
--- a/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java
@@ -57,7 +57,7 @@ public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd {
     @Parameter(name = ApiConstants.NETWORK_ID,
                type = CommandType.UUID,
                entityType = NetworkResponse.class,
-               description = "list port forwarding rules for ceratin network",
+               description = "list port forwarding rules for certain network",
                since = "4.3")
     private Long networkId;
 


[17/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCreateVolumeFromSnapshotCommandWrapper, LibvirtFenceCommandWrapper and LibvirtSecurityGroupRulesCommandWrapper
  - 6 unit tests added
  - KVM hypervisor plugin with 17.2% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/ff7ae9ca
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/ff7ae9ca
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/ff7ae9ca

Branch: refs/heads/CLOUDSTACK-8301
Commit: ff7ae9ca0c9714dca684f3972eacae56254b76fd
Parents: 3c8b217
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Sat May 2 09:37:59 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:13 2015 +0200

----------------------------------------------------------------------
 .../com/cloud/agent/api/SnapshotCommand.java    |   8 +-
 .../kvm/resource/LibvirtComputingResource.java  |  86 +-----
 ...tCreateVolumeFromSnapshotCommandWrapper.java |  68 +++++
 .../wrapper/LibvirtFenceCommandWrapper.java     |  67 +++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   6 +
 ...LibvirtSecurityGroupRulesCommandWrapper.java |  67 +++++
 .../resource/LibvirtComputingResourceTest.java  | 296 ++++++++++++++++++-
 7 files changed, 498 insertions(+), 100 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/core/src/com/cloud/agent/api/SnapshotCommand.java
----------------------------------------------------------------------
diff --git a/core/src/com/cloud/agent/api/SnapshotCommand.java b/core/src/com/cloud/agent/api/SnapshotCommand.java
index a4975e6..cf4eeb5 100644
--- a/core/src/com/cloud/agent/api/SnapshotCommand.java
+++ b/core/src/com/cloud/agent/api/SnapshotCommand.java
@@ -53,9 +53,9 @@ public class SnapshotCommand extends Command {
      *            is the value of that field If you have better ideas on how to
      *            get it, you are welcome.
      */
-    public SnapshotCommand(StoragePool pool, String secondaryStorageUrl, String snapshotUuid, String snapshotName, Long dcId, Long accountId, Long volumeId) {
-        // this.primaryStoragePoolNameLabel = pool.getUuid();
-        //this.primaryPool = new StorageFilerTO(pool);
+    public SnapshotCommand(final StoragePool pool, final String secondaryStorageUrl, final String snapshotUuid, final String snapshotName, final Long dcId, final Long accountId, final Long volumeId) {
+        primaryStoragePoolNameLabel = pool.getUuid();
+        primaryPool = new StorageFilerTO(pool);
         this.snapshotUuid = snapshotUuid;
         this.secondaryStorageUrl = secondaryStorageUrl;
         this.dcId = dcId;
@@ -112,7 +112,7 @@ public class SnapshotCommand extends Command {
         return volumePath;
     }
 
-    public void setVolumePath(String path) {
+    public void setVolumePath(final String path) {
         volumePath = path;
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 6d13ce6..6f24b31 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -44,10 +44,6 @@ import java.util.Properties;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -88,10 +84,6 @@ import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
-import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
-import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
-import com.cloud.agent.api.FenceAnswer;
-import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
@@ -103,8 +95,6 @@ import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
 import com.cloud.agent.api.PlugNicAnswer;
 import com.cloud.agent.api.PlugNicCommand;
 import com.cloud.agent.api.PvlanSetupCommand;
-import com.cloud.agent.api.SecurityGroupRuleAnswer;
-import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
 import com.cloud.agent.api.StartAnswer;
 import com.cloud.agent.api.StartCommand;
@@ -138,7 +128,6 @@ import com.cloud.dc.Vlan;
 import com.cloud.exception.InternalErrorException;
 import com.cloud.host.Host.Type;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
-import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ClockDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ConsoleDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuModeDef;
@@ -1284,14 +1273,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((ManageSnapshotCommand)cmd);
             } else if (cmd instanceof BackupSnapshotCommand) {
                 return execute((BackupSnapshotCommand)cmd);
-            } else if (cmd instanceof CreateVolumeFromSnapshotCommand) {
-                return execute((CreateVolumeFromSnapshotCommand)cmd);
             } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                 return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
-            } else if (cmd instanceof SecurityGroupRulesCmd) {
-                return execute((SecurityGroupRulesCmd)cmd);
-            } else if (cmd instanceof FenceCommand) {
-                return execute((FenceCommand)cmd);
             } else if (cmd instanceof StartCommand) {
                 return execute((StartCommand)cmd);
             } else if (cmd instanceof PlugNicCommand) {
@@ -1450,28 +1433,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected FenceAnswer execute(final FenceCommand cmd) {
-        final ExecutorService executors = Executors.newSingleThreadExecutor();
-        final List<NfsStoragePool> pools = _monitor.getStoragePools();
-        final KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHostIp());
-        final Future<Boolean> future = executors.submit(ha);
-        try {
-            final Boolean result = future.get();
-            if (result) {
-                return new FenceAnswer(cmd, false, "Heart is still beating...");
-            } else {
-                return new FenceAnswer(cmd);
-            }
-        } catch (final InterruptedException e) {
-            s_logger.warn("Unable to fence", e);
-            return new FenceAnswer(cmd, false, e.getMessage());
-        } catch (final ExecutionException e) {
-            s_logger.warn("Unable to fence", e);
-            return new FenceAnswer(cmd, false, e.getMessage());
-        }
-
-    }
-
     protected Storage.StorageResourceType getStorageResourceType() {
         return Storage.StorageResourceType.STORAGE_POOL;
     }
@@ -2265,25 +2226,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new BackupSnapshotAnswer(cmd, true, null, snapshotRelPath + File.separator + snapshotName, true);
     }
 
-    protected CreateVolumeFromSnapshotAnswer execute(final CreateVolumeFromSnapshotCommand cmd) {
-        try {
-
-            String snapshotPath = cmd.getSnapshotUuid();
-            final int index = snapshotPath.lastIndexOf("/");
-            snapshotPath = snapshotPath.substring(0, index);
-            final KVMStoragePool secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd.getSecondaryStorageUrl() + snapshotPath);
-            final KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(cmd.getSnapshotName());
-
-            final String primaryUuid = cmd.getPrimaryStoragePoolNameLabel();
-            final KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd.getPool().getType(), primaryUuid);
-            final String volUuid = UUID.randomUUID().toString();
-            final KVMPhysicalDisk disk = _storagePoolMgr.copyPhysicalDisk(snapshot, volUuid, primaryPool, 0);
-            return new CreateVolumeFromSnapshotAnswer(cmd, true, "", disk.getName());
-        } catch (final CloudRuntimeException e) {
-            return new CreateVolumeFromSnapshotAnswer(cmd, false, e.toString(), null);
-        }
-    }
-
     protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) {
         final String templateFolder = cmd.getAccountId() + File.separator + cmd.getNewTemplateId();
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
@@ -2450,32 +2392,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final SecurityGroupRulesCmd cmd) {
-        String vif = null;
-        String brname = null;
-        try {
-            final Connect conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
-            final List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
-            vif = nics.get(0).getDevName();
-            brname = nics.get(0).getBrName();
-        } catch (final LibvirtException e) {
-            return new SecurityGroupRuleAnswer(cmd, false, e.toString());
-        }
-
-        final 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, cmd.getSecIpsString());
-
-        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);
-        }
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;
@@ -4101,7 +4017,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private boolean add_network_rules(final String vmName, final String vmId, final String guestIP, final String sig, final String seq, final String mac, final String rules, final String vif, final String brname,
+    public boolean addNetworkRules(final String vmName, final String vmId, final String guestIP, final String sig, final String seq, final String mac, final String rules, final String vif, final String brname,
             final String secIps) {
         if (!_canBridgeFirewall) {
             return false;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateVolumeFromSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateVolumeFromSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateVolumeFromSnapshotCommandWrapper.java
new file mode 100644
index 0000000..b30c3f8
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateVolumeFromSnapshotCommandWrapper.java
@@ -0,0 +1,68 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.UUID;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
+import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtCreateVolumeFromSnapshotCommandWrapper extends CommandWrapper<CreateVolumeFromSnapshotCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CreateVolumeFromSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+
+            String snapshotPath = command.getSnapshotUuid();
+            final int index = snapshotPath.lastIndexOf("/");
+            snapshotPath = snapshotPath.substring(0, index);
+
+            final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            final KVMStoragePool secondaryPool = storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+            final KVMPhysicalDisk snapshot = secondaryPool.getPhysicalDisk(command.getSnapshotName());
+
+            final String primaryUuid = command.getPrimaryStoragePoolNameLabel();
+
+            final StorageFilerTO pool = command.getPool();
+            final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(pool.getType(), primaryUuid);
+
+            final String volUuid = UUID.randomUUID().toString();
+            final KVMPhysicalDisk disk = storagePoolMgr.copyPhysicalDisk(snapshot, volUuid, primaryPool, 0);
+
+            if (disk == null) {
+                throw new NullPointerException("Disk was not successfully copied to the new storage.");
+            }
+
+            return new CreateVolumeFromSnapshotAnswer(command, true, "", disk.getName());
+        } catch (final CloudRuntimeException e) {
+            return new CreateVolumeFromSnapshotAnswer(command, false, e.toString(), null);
+        } catch (final Exception e) {
+            return new CreateVolumeFromSnapshotAnswer(command, false, e.toString(), null);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtFenceCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtFenceCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtFenceCommandWrapper.java
new file mode 100644
index 0000000..53e3845
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtFenceCommandWrapper.java
@@ -0,0 +1,67 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.FenceAnswer;
+import com.cloud.agent.api.FenceCommand;
+import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
+import com.cloud.hypervisor.kvm.resource.KVMHAChecker;
+import com.cloud.hypervisor.kvm.resource.KVMHAMonitor;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtFenceCommandWrapper extends CommandWrapper<FenceCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtFenceCommandWrapper.class);
+
+    @Override
+    public Answer execute(final FenceCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final ExecutorService executors = Executors.newSingleThreadExecutor();
+        final KVMHAMonitor monitor = libvirtComputingResource.getMonitor();
+
+        final List<NfsStoragePool> pools = monitor.getStoragePools();
+        final KVMHAChecker ha = new KVMHAChecker(pools, command.getHostIp());
+
+        final Future<Boolean> future = executors.submit(ha);
+        try {
+            final Boolean result = future.get();
+            if (result) {
+                return new FenceAnswer(command, false, "Heart is still beating...");
+            } else {
+                return new FenceAnswer(command);
+            }
+        } catch (final InterruptedException e) {
+            s_logger.warn("Unable to fence", e);
+            return new FenceAnswer(command, false, e.getMessage());
+        } catch (final ExecutionException e) {
+            s_logger.warn("Unable to fence", e);
+            return new FenceAnswer(command, false, e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index af2f544..23248c4 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -30,7 +30,9 @@ import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreateStoragePoolCommand;
+import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
+import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
@@ -54,6 +56,7 @@ import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
+import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.check.CheckSshCommand;
@@ -124,6 +127,9 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(OvsDestroyTunnelCommand.class, new LibvirtOvsDestroyTunnelCommandWrapper());
         linbvirtCommands.put(CheckOnHostCommand.class, new LibvirtCheckOnHostCommandWrapper());
         linbvirtCommands.put(OvsCreateTunnelCommand.class, new LibvirtOvsCreateTunnelCommandWrapper());
+        linbvirtCommands.put(CreateVolumeFromSnapshotCommand.class, new LibvirtCreateVolumeFromSnapshotCommandWrapper());
+        linbvirtCommands.put(FenceCommand.class, new LibvirtFenceCommandWrapper());
+        linbvirtCommands.put(SecurityGroupRulesCmd.class, new LibvirtSecurityGroupRulesCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
new file mode 100644
index 0000000..5bdafe7
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
@@ -0,0 +1,67 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.SecurityGroupRuleAnswer;
+import com.cloud.agent.api.SecurityGroupRulesCmd;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtSecurityGroupRulesCommandWrapper extends CommandWrapper<SecurityGroupRulesCmd, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtSecurityGroupRulesCommandWrapper.class);
+
+    @Override
+    public Answer execute(final SecurityGroupRulesCmd command, final LibvirtComputingResource libvirtComputingResource) {
+        String vif = null;
+        String brname = null;
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());
+
+            vif = nics.get(0).getDevName();
+            brname = nics.get(0).getBrName();
+        } catch (final LibvirtException e) {
+            return new SecurityGroupRuleAnswer(command, false, e.toString());
+        }
+
+        final boolean result = libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getSignature(),
+                Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString());
+
+        if (!result) {
+            s_logger.warn("Failed to program network rules for vm " + command.getVmName());
+            return new SecurityGroupRuleAnswer(command, false, "programming network rules failed");
+        } else {
+            s_logger.debug("Programmed network rules for vm " + command.getVmName() + " guestIp=" + command.getGuestIp() + ",ingress numrules="
+                    + command.getIngressRuleSet().length + ",egress numrules=" + command.getEgressRuleSet().length);
+            return new SecurityGroupRuleAnswer(command);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ff7ae9ca/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index f01ad7a..15ba52b 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -72,7 +72,9 @@ import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.CreateStoragePoolCommand;
+import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
+import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
@@ -100,6 +102,8 @@ import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
+import com.cloud.agent.api.SecurityGroupRulesCmd;
+import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmStatsEntry;
@@ -117,6 +121,7 @@ import com.cloud.agent.api.to.VirtualMachineTO;
 import com.cloud.agent.api.to.VolumeTO;
 import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
 import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtConnectionWrapper;
@@ -1863,17 +1868,17 @@ public class LibvirtComputingResourceTest {
 
     @Test
     public void testUpgradeSnapshotCommand() {
-        final StoragePool pool = null;
-        final String secondaryStoragePoolURL = null;
-        final Long dcId = null;
-        final Long accountId = null;
-        final Long volumeId = null;
-        final Long templateId = null;
-        final Long tmpltAccountId = null;
-        final String volumePath = null;
-        final String snapshotUuid = null;
-        final String snapshotName = null;
-        final String version = null;
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final String secondaryStoragePoolURL = "url";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final Long templateId = 1l;
+        final Long tmpltAccountId = 1l;
+        final String volumePath = "/opt/path";
+        final String snapshotUuid = "uuid:/8edb1156-a851-4914-afc6-468ee52ac861/";
+        final String snapshotName = "uuid:/8edb1156-a851-4914-afc6-468ee52ac861/";
+        final String version = "1";
 
         final UpgradeSnapshotCommand command = new UpgradeSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, templateId, tmpltAccountId, volumePath, snapshotUuid, snapshotName, version);
 
@@ -2654,4 +2659,273 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
                 command.getNetworkName());
     }
+
+    @Test
+    public void testCreateVolumeFromSnapshotCommand() {
+        // This tests asserts to False because there will be a NPE due to UUID static method calls.
+
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "/opt/storage/";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "uuid:/8edb1156-a851-4914-afc6-468ee52ac861/";
+        final String backedUpSnapshotName = "uuid:/8edb1156-a851-4914-afc6-468ee52ac862/";
+        final int wait = 0;
+
+        final CreateVolumeFromSnapshotCommand command = new CreateVolumeFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        final String primaryUuid = command.getPrimaryStoragePoolNameLabel();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(secondaryPool);
+        when(secondaryPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), primaryUuid)).thenReturn(primaryPool);
+
+        //when(storagePoolMgr.copyPhysicalDisk(snapshot, volUuid, primaryPool, 0)).thenReturn(disk);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(secondaryPool, times(1)).getPhysicalDisk(command.getSnapshotName());
+        verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), primaryUuid);
+        //verify(storagePoolMgr, times(1)).copyPhysicalDisk(snapshot, volUuid, primaryPool, 0);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreateVolumeFromSnapshotCommandCloudException() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "/opt/storage/";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "uuid:/8edb1156-a851-4914-afc6-468ee52ac861/";
+        final String backedUpSnapshotName = "uuid:/8edb1156-a851-4914-afc6-468ee52ac862/";
+        final int wait = 0;
+
+        final CreateVolumeFromSnapshotCommand command = new CreateVolumeFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        final String primaryUuid = command.getPrimaryStoragePoolNameLabel();
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(secondaryPool);
+        when(secondaryPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), primaryUuid)).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(secondaryPool, times(1)).getPhysicalDisk(command.getSnapshotName());
+        verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), primaryUuid);
+    }
+
+    @Test
+    public void testFenceCommand() {
+        final VirtualMachine vm = Mockito.mock(VirtualMachine.class);;
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);
+
+        final FenceCommand command = new FenceCommand(vm, host);
+
+        final KVMHAMonitor monitor = Mockito.mock(KVMHAMonitor.class);
+
+        final NfsStoragePool storagePool = Mockito.mock(NfsStoragePool.class);
+        final List<NfsStoragePool> pools = new ArrayList<NfsStoragePool>();
+        pools.add(storagePool);
+
+        when(libvirtComputingResource.getMonitor()).thenReturn(monitor);
+        when(monitor.getStoragePools()).thenReturn(pools);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getMonitor();
+        verify(monitor, times(1)).getStoragePools();
+    }
+
+    @Test
+    public void testSecurityGroupRulesCmdFalse() {
+        final String guestIp = "172.16.16.16";
+        final String guestMac = "00:00:00:00";
+        final String vmName = "Test";
+        final Long vmId = 1l;
+        final String signature = "signature";
+        final Long seqNum = 1l;
+        final IpPortAndProto[] ingressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+        final IpPortAndProto[] egressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+
+        final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
+        nics.add(interfaceDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(ingressRuleSet[0].getProto()).thenReturn("tcp");
+        when(ingressRuleSet[0].getStartPort()).thenReturn(22);
+        when(ingressRuleSet[0].getEndPort()).thenReturn(22);
+        when(ingressRuleSet[0].getAllowedCidrs()).thenReturn(new String[]{"0.0.0.0/0"});
+
+        when(egressRuleSet[0].getProto()).thenReturn("tcp");
+        when(egressRuleSet[0].getStartPort()).thenReturn(22);
+        when(egressRuleSet[0].getEndPort()).thenReturn(22);
+        when(egressRuleSet[0].getAllowedCidrs()).thenReturn(new String[]{"0.0.0.0/0"});
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testSecurityGroupRulesCmdTrue() {
+        final String guestIp = "172.16.16.16";
+        final String guestMac = "00:00:00:00";
+        final String vmName = "Test";
+        final Long vmId = 1l;
+        final String signature = "signature";
+        final Long seqNum = 1l;
+        final IpPortAndProto[] ingressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+        final IpPortAndProto[] egressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+
+        final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
+        nics.add(interfaceDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(interfaceDef.getDevName()).thenReturn("eth0");
+        when(interfaceDef.getBrName()).thenReturn("br0");
+
+        final String vif = nics.get(0).getDevName();
+        final String brname = nics.get(0).getBrName();
+
+        when(ingressRuleSet[0].getProto()).thenReturn("tcp");
+        when(ingressRuleSet[0].getStartPort()).thenReturn(22);
+        when(ingressRuleSet[0].getEndPort()).thenReturn(22);
+        when(ingressRuleSet[0].getAllowedCidrs()).thenReturn(new String[]{"0.0.0.0/0"});
+
+        when(egressRuleSet[0].getProto()).thenReturn("tcp");
+        when(egressRuleSet[0].getStartPort()).thenReturn(22);
+        when(egressRuleSet[0].getEndPort()).thenReturn(22);
+        when(egressRuleSet[0].getAllowedCidrs()).thenReturn(new String[]{"0.0.0.0/0"});
+
+        when(libvirtComputingResource.addNetworkRules(command.getVmName(), Long.toString(command.getVmId()), command.getGuestIp(), command.getSignature(),
+                Long.toString(command.getSeqNum()), command.getGuestMac(), command.stringifyRules(), vif, brname, command.getSecIpsString())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testSecurityGroupRulesCmdException() {
+        final String guestIp = "172.16.16.16";
+        final String guestMac = "00:00:00:00";
+        final String vmName = "Test";
+        final Long vmId = 1l;
+        final String signature = "signature";
+        final Long seqNum = 1l;
+        final IpPortAndProto[] ingressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+        final IpPortAndProto[] egressRuleSet = new IpPortAndProto[]{Mockito.mock(IpPortAndProto.class)};
+
+        final SecurityGroupRulesCmd command = new SecurityGroupRulesCmd(guestIp, guestMac, vmName, vmId, signature, seqNum, ingressRuleSet, egressRuleSet);
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        final List<InterfaceDef> nics = new ArrayList<InterfaceDef>();
+        final InterfaceDef interfaceDef = Mockito.mock(InterfaceDef.class);
+        nics.add(interfaceDef);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtComputingResource.getInterfaces(conn, command.getVmName())).thenReturn(nics);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
 }
\ No newline at end of file


[35/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
debian: allow tomcat7 as optional dependency

This closes #247

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/7451f13f
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/7451f13f
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/7451f13f

Branch: refs/heads/CLOUDSTACK-8301
Commit: 7451f13f911e0044d0981046bcde31a18f77db83
Parents: 256e227
Author: Rene Moser <re...@apache.org>
Authored: Wed May 13 01:06:13 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Wed May 13 15:40:52 2015 +0200

----------------------------------------------------------------------
 debian/control | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7451f13f/debian/control
----------------------------------------------------------------------
diff --git a/debian/control b/debian/control
index 2d2c125..f6e9be0 100644
--- a/debian/control
+++ b/debian/control
@@ -15,7 +15,7 @@ Description: A common package which contains files which are shared by several C
 
 Package: cloudstack-management
 Architecture: all
-Depends: ${misc:Depends}, ${python:Depends}, cloudstack-common (= ${source:Version}), tomcat6,  sudo, jsvc, python-mysqldb, libmysql-java, python-paramiko, augeas-tools, mysql-client, adduser
+Depends: ${misc:Depends}, ${python:Depends}, cloudstack-common (= ${source:Version}), tomcat6 | tomcat7 | tomcat8, sudo, jsvc, python-mysqldb, libmysql-java, python-paramiko, augeas-tools, mysql-client, adduser
 Conflicts: cloud-server, cloud-client, cloud-client-ui
 Description: CloudStack server library
  The CloudStack management server


[46/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8482: Enhacing recurring snapshots test cases

Signed-off-by: Gaurav Aradhye <ga...@clogeny.com>
This closes #260


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/dacdf974
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/dacdf974
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/dacdf974

Branch: refs/heads/CLOUDSTACK-8301
Commit: dacdf97427f17ea80695898c40565da3be188e47
Parents: a99c9d0
Author: Gaurav Aradhye <ga...@clogeny.com>
Authored: Tue May 19 16:55:05 2015 +0530
Committer: Gaurav Aradhye <ga...@clogeny.com>
Committed: Tue May 19 16:57:37 2015 +0530

----------------------------------------------------------------------
 .../component/test_recurring_snapshots.py       | 29 ++++++++++----------
 1 file changed, 15 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/dacdf974/test/integration/component/test_recurring_snapshots.py
----------------------------------------------------------------------
diff --git a/test/integration/component/test_recurring_snapshots.py b/test/integration/component/test_recurring_snapshots.py
index 58dd769..9912fda 100644
--- a/test/integration/component/test_recurring_snapshots.py
+++ b/test/integration/component/test_recurring_snapshots.py
@@ -104,7 +104,7 @@ class Services:
             "recurring_snapshot": {
                 "intervaltype": 'HOURLY',
                 # Frequency of snapshots
-                "maxsnaps": 1,  # Should be min 2
+                "maxsnaps": 2,  # Should be min 2
                 "schedule": 1,
                 "timezone": 'US/Arizona',
                 # Timezone Formats -
@@ -182,15 +182,14 @@ class TestRecurringSnapshots(cloudstackTestCase):
             cls.api_client,
             cls.services["service_offering"]
         )
-        cls.virtual_machine = cls.virtual_machine_with_disk = \
+        cls.virtual_machine_with_disk = \
             VirtualMachine.create(
                 cls.api_client,
                 cls.services["server_with_disk"],
                 templateid=template.id,
                 accountid=cls.account.name,
                 domainid=cls.account.domainid,
-                serviceofferingid=cls.service_offering.id,
-                mode=cls.services["mode"]
+                serviceofferingid=cls.service_offering.id
             )
         cls.virtual_machine_without_disk = \
             VirtualMachine.create(
@@ -199,8 +198,7 @@ class TestRecurringSnapshots(cloudstackTestCase):
                 templateid=template.id,
                 accountid=cls.account.name,
                 domainid=cls.account.domainid,
-                serviceofferingid=cls.service_offering.id,
-                mode=cls.services["mode"]
+                serviceofferingid=cls.service_offering.id
             )
         cls._cleanup = [
             cls.service_offering,
@@ -233,7 +231,7 @@ class TestRecurringSnapshots(cloudstackTestCase):
         return
 
     @attr(speed="slow")
-    @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="false")
+    @attr(tags=["advanced", "advancedns", "basic"], required_hardware="true")
     def test_recurring_snapshot_root_disk(self):
         """Test Recurring Snapshot Root Disk
         """
@@ -243,7 +241,7 @@ class TestRecurringSnapshots(cloudstackTestCase):
 
         volume = list_volumes(
             self.apiclient,
-            virtualmachineid=self.virtual_machine_with_disk.id,
+            virtualmachineid=self.virtual_machine_without_disk.id,
             type='ROOT',
             listall=True
         )
@@ -286,10 +284,12 @@ class TestRecurringSnapshots(cloudstackTestCase):
             self.services["recurring_snapshot"]["maxsnaps"],
             "Check interval type in list resources call"
         )
-        # Sleep for (maxsnaps+1) hours to verify
+
+        max_snapshots = self.services["recurring_snapshot"]["maxsnaps"]
+        # Sleep for (max_snapshots*2) hours to verify
         # only maxsnaps snapshots are retained
         time.sleep(
-            (self.services["recurring_snapshot"]["maxsnaps"]) * 3600
+            (max_snapshots * 2) * 3600
         )
 
         timeout = self.services["timeout"]
@@ -319,13 +319,13 @@ class TestRecurringSnapshots(cloudstackTestCase):
 
         self.assertEqual(
             len(snapshots),
-            self.services["recurring_snapshot"]["maxsnaps"],
+            max_snapshots,
             "Check maximum number of recurring snapshots retained"
         )
         return
 
     @attr(speed="slow")
-    @attr(tags=["advanced", "advancedns", "smoke"], required_hardware="false")
+    @attr(tags=["advanced", "advancedns", "basic"], required_hardware="true")
     def test_recurring_snapshot_data_disk(self):
         """Test Recurring Snapshot data Disk
         """
@@ -382,10 +382,11 @@ class TestRecurringSnapshots(cloudstackTestCase):
             "Check interval type in list resources call"
         )
 
+        max_snapshots = self.services["recurring_snapshot"]["maxsnaps"]
         # Sleep for (maxsnaps) hours to verify only maxsnaps snapshots are
         # retained
         time.sleep(
-            (self.services["recurring_snapshot"]["maxsnaps"]) * 3600
+            (max_snapshots * 2) * 3600
         )
 
         timeout = self.services["timeout"]
@@ -414,7 +415,7 @@ class TestRecurringSnapshots(cloudstackTestCase):
         )
         self.assertEqual(
             len(snapshots),
-            self.services["recurring_snapshot"]["maxsnaps"],
+            max_snapshots,
             "Check maximum number of recurring snapshots retained"
         )
         return


[44/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Tests for Disable Storage Provisioning

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #257


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/bab4e3a6
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/bab4e3a6
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/bab4e3a6

Branch: refs/heads/CLOUDSTACK-8301
Commit: bab4e3a6af5ff5f8c20063d8ba82ac1dd021493f
Parents: 19c436f
Author: Sowmya Krishnan <so...@apache.org>
Authored: Wed May 6 16:04:51 2015 +0530
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Tue May 19 11:16:44 2015 +0100

----------------------------------------------------------------------
 .../testpaths/testpath_disablestoragepool.py    | 1285 ++++++++++++++++++
 1 file changed, 1285 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/bab4e3a6/test/integration/testpaths/testpath_disablestoragepool.py
----------------------------------------------------------------------
diff --git a/test/integration/testpaths/testpath_disablestoragepool.py b/test/integration/testpaths/testpath_disablestoragepool.py
new file mode 100644
index 0000000..3d34ac3
--- /dev/null
+++ b/test/integration/testpaths/testpath_disablestoragepool.py
@@ -0,0 +1,1285 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Utilities functions
+"""
+#All tests inherit from cloudstackTestCase
+
+from marvin.cloudstackTestCase import cloudstackTestCase
+from marvin.cloudstackTestCase import cloudstackTestCase, unittest
+from marvin.codes import FAILED, PASS
+from marvin.lib.base import (Account,
+                             VirtualMachine,
+                             ServiceOffering,
+                             User,
+                             DiskOffering,
+                             Volume,
+                             Template,
+                             VmSnapshot,
+                             StoragePool,
+                             Host,
+                             Capacities)
+from marvin.lib.utils import cleanup_resources, validateList
+from marvin.lib.common import get_zone, get_domain, list_clusters, get_template, list_volumes, list_virtual_machines
+from nose.plugins.attrib import attr
+from ddt import ddt, data
+
+def verify_vm_state(self, vmid, state):
+    list_vm = list_virtual_machines(self.userapiclient, account=self.account.name, domainid=self.account.domainid, id=vmid)
+    self.assertEqual(validateList(list_vm)[0], PASS, 'Check List vm response for vmid: %s' % vmid)
+    self.assertGreater(len(list_vm), 0, 'Check the list vm response for vm id:  %s' % vmid)
+    vm = list_vm[0]
+    self.assertEqual(vm.id, str(vmid), 'Vm deployed is different from the test')
+    self.assertEqual(vm.state, state, 'VM is not in %s state' % state)
+    self.debug('VM is in is %s state' % state)
+
+
+
+def verify_pool_state(self, poolid, state):
+    list_storage_pool_response = StoragePool.list(self.userapiclient, id=poolid)
+    self.assertGreater(len(list_storage_pool_response), 0, 'Check list pool response is greater than 0')
+    self.assertEqual(list_storage_pool_response[0].state, state, 'Storage pool is not in %s state' % state)
+
+
+
+def verify_vm_storage_pool(self, vmid, storageid):
+    root_volume = Volume.list(self.userapiclient, virtualmachineid=vmid, type='ROOT')[0]
+    list_volume = Volume.list(self.userapiclient, id=root_volume.id)
+    self.assertEqual(list_volume[0].storageid, storageid, 'check list volume response for Storage id:  % s ' % storageid)
+
+
+
+@ddt
+class TestPathDisableStorage_Basic(cloudstackTestCase):
+    """
+        # Tests in this path requires to be run independently (not to be run in parallel  with any other tests since it involves disabling/enabling storage pools and may cause unexpected failures in other tests
+        # The test also requires to have 2 Cluster-wide and 2 zone-wide storage pools available in the setup.
+        # For running the tests on local storage, ensure there are 2 local storage pools set up on each host
+
+        """
+
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestPathDisableStorage_Basic, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient)
+        cls.testdata['mode'] = cls.zone.networktype
+        cls.template = get_template(cls.apiclient, cls.zone.id, cls.testdata['ostype'])
+        cls.testdata['template']['ostypeid'] = cls.template.ostypeid
+        if cls.template == FAILED:
+            cls.fail('get_template() failed to return template with description %s' % cls.testdata['ostype'])
+        cls._cleanup = []
+        cls.disabled_list = []
+        cls.testdata['template_2']['zoneid'] = cls.zone.id
+        cls.testdata['template_2']['ostypeid'] = cls.template.ostypeid
+        cls.hypervisor = testClient.getHypervisorInfo()
+        try:
+            cls.debug('Creating account')
+            cls.account = Account.create(cls.apiclient,
+                                         cls.testdata['account'],
+                                         admin=True
+                                         )
+            cls._cleanup.append(cls.account)
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+
+        # Create shared storage offerings
+        cls.service_offering_shared = ServiceOffering.create(cls.apiclient,
+                                                      cls.testdata['service_offering']
+                                                      )
+        cls._cleanup.append(cls.service_offering_shared)
+        cls.disk_offering_shared = DiskOffering.create(cls.apiclient,
+                                                cls.testdata['disk_offering']
+                                                )
+        cls.resized_disk_offering = DiskOffering.create(cls.apiclient,
+                                                        cls.testdata['resized_disk_offering']
+                                                        )
+        cls._cleanup.append(cls.disk_offering_shared)
+
+        # Create offerings for local storage if local storage is enabled
+        if cls.zone.localstorageenabled:
+            cls.testdata["service_offerings"]["storagetype"] = 'local'
+            cls.service_offering_local = ServiceOffering.create(cls.apiclient,
+                                                            cls.testdata["service_offerings"]
+                                                            )
+            cls._cleanup.append(cls.service_offering_local)
+            cls.testdata["disk_offering"]["storagetype"] = 'local'
+            cls.disk_offering_local = DiskOffering.create(cls.apiclient,
+                                                          cls.testdata["disk_offering"]
+                                                          )
+            cls._cleanup.append(cls.disk_offering_local)
+            cls.testdata["disk_offering"]["storagetype"] = ' '
+            cls.testdata["service_offerings"]["storagetype"] = ' '
+        else:
+            cls.debug("No local storage found")
+
+        cls.userapiclient = testClient.getUserApiClient(UserName=cls.account.name,
+                                                        DomainName=cls.account.domain
+                                                        )
+        response = User.login(cls.userapiclient,
+                              username=cls.account.name,
+                              password=cls.testdata['account']['password']
+                              )
+        assert response.sessionkey is not None
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception('Warning:Exception during cleanup: %s' % e)
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.cleanup = []
+
+    def tearDown(self):
+        if self.disabled_list:
+            for poolid in self.disabled_list:
+                if StoragePool.list(self.userapiclient, id=poolid)[0].state != 'Up':
+                    try:
+                        StoragePool.update(self.userapiclient, id=poolid, enabled=True)
+                        self.debug('Enabling: % s ' % poolid)
+                    except Exception as e:
+                        self.fail("Couldn't enable storage % s" % id)
+
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            self.fail('Warning: Exception during cleanup : %s' % e)
+
+
+    @data('host', 'CLUSTER', 'ZONE')
+    @attr(tags=['advanced', 'advancedsg', 'basic'], required_hardware='false')
+    def test_01_disable_enable_pool(self, value):
+        """
+
+                Test Steps:
+                =========
+                1. Deploy 2 VMs
+                2. Stop VM2
+                3. Disable storage pool SP1
+                4. Try to deploy a new VM, should fail
+                5. Start VM2 which was stopped, should run from same pool
+                6. Remove disabled Storage pool SP1, should fail
+                7. Enable storage pool SP1
+                8. Deploy new VM, VM4 - should succeed
+                9. Create and attach new disk to VM4
+                10. Disable storage pool SP1 again and enable new pool
+                11. Deploy new VM, VM5 - should succeed
+                12. Stop VM1 which is running from disabled pool
+                13. Migrate ROOT volume of VM1 to another enabled storage pool - should succeed
+                14. findStoragePoolsforMigration should not list the disabled pool
+                """
+
+        # Choose appropriate service offering depending on the scope the test is being run on
+        self.disabled_list = []
+        if value == 'CLUSTER':
+            other_scope = 'ZONE'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        elif value == 'ZONE':
+            other_scope = 'CLUSTER'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        else:
+            # local storage
+            other_scope = None
+            self.service_offering = self.service_offering_local
+            self.disk_offering = self.disk_offering_local
+
+        # Keep only one pool active and disable the rest
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, scope=value)
+            count_st_pools = len(self.list_storage)
+            if count_st_pools > 1:
+                self.debug('Found % s storage pools, keeping one and disabling rest' % count_st_pools)
+                for pool in self.list_storage[1:]:
+                    self.disabled_pool_1 = self.list_storage[1]
+                    if pool.state == 'Up':
+                        self.debug('Trying to disable storage %s' % pool.id)
+                        try:
+                            StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                            self.disabled_list.append(pool.id)
+                            self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                        except Exception as e:
+                            raise e
+            elif count_st_pools == 1:
+                self.debug('Only one % s wide storage found - will not be able to complete all tests' % value)
+            else:
+                self.fail('No % s  storage pools found' % value)
+        except Exception as e:
+            raise e
+
+        # Disable the other scope shared storage pools while we are testing on one - applicable for only shared storage
+        if value != 'host':
+            try:
+                self.list_storage = StoragePool.list(self.userapiclient, scope=other_scope)
+                if self.list_storage:
+                    for pool in self.list_storage:
+                        if pool.state == 'Up':
+                            self.debug('Trying to disable storage % s' % pool.id)
+                            try:
+                                StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                                self.disabled_list.append(pool.id)
+                                self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                            except Exception as e:
+                                self.fail("Couldn't disable storage % s" % pool.id)
+                else:
+                    self.debug('No % s wide storage pools found' % other_scope)
+            except Exception as e:
+                raise e
+
+        # Step 1: Deploy 2 VMs
+        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+        self.virtual_machine_2 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_2.id, 'Running')
+
+        # Step 2: Keep one VM in stopped state while other keeps running
+        try:
+            self.debug('Step 2: Stopping one of the VMs')
+            self.virtual_machine_2.stop(self.userapiclient)
+            verify_vm_state(self, self.virtual_machine_2.id, 'Stopped')
+        except Exception as e:
+            self.fail('Step 2: Failed to stop VM: %s' % e)
+
+        # Step 3: Disable the Storage Pool, verify VMs are in same state as before
+        self.storage_pools_list = StoragePool.list(self.userapiclient, scope=value, state='Up')
+        self.storage_pool_1 = self.storage_pools_list[0]
+        try:
+            self.debug('Step 3: Disabling Storage Pool: %s' % self.storage_pool_1.id)
+            StoragePool.update(self.userapiclient, id=self.storage_pool_1.id, enabled=False)
+        except Exception as e:
+            self.debug("Step 3: Couldn't disable pool %s" % e)
+
+        verify_pool_state(self, self.storage_pool_1.id, 'Disabled')
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+        verify_vm_state(self, self.virtual_machine_2.id, 'Stopped')
+
+        # Step 4: Deploying new VM on disabled pool should fail
+        self.debug('Step 4: Trying to deploy VM on disabled storage - should fail')
+        with self.assertRaises(Exception):
+            VirtualMachine.create(self.userapiclient,
+                                  self.testdata['small'],
+                                  templateid=self.template.id,
+                                  accountid=self.account.name,
+                                  domainid=self.account.domainid,
+                                  serviceofferingid=self.service_offering.id,
+                                  zoneid=self.zone.id)
+
+        # Step 5: Should be able to start VM on disabled pool
+        try:
+            self.virtual_machine_2.start(self.userapiclient)
+            verify_vm_state(self, self.virtual_machine_2.id, 'Running')
+            verify_vm_storage_pool(self, self.virtual_machine_2.id, self.storage_pool_1.id)
+        except Exception as e:
+            self.fail('Step 5: Failed to start VM: %s' % e)
+
+        # Step 6: Removing disabled pool should fail
+        self.debug('Step 6: Trying to remove disabled storage pool')
+        with self.assertRaises(Exception):
+            StoragePool.delete(self.userapiclient, self.storage_pool_1.id)
+
+        # Step 7: Enable Storage pool
+        try:
+            self.debug('Step 7: Enabling Storage Pool: %s' % self.storage_pool_1.id)
+            StoragePool.update(self.userapiclient, id=self.storage_pool_1.id, enabled=True)
+        except Exception as e:
+            self.debug("Step 7: Couldn't enable pool %s" % e)
+        verify_pool_state(self, self.storage_pool_1.id, 'Up')
+
+        # Step 8: Deploy a VM on the pool
+        self.virtual_machine_3 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_3.id, 'Running')
+
+        # Step 9: Create and attach new disk to VM
+        self.volume = Volume.create(self.userapiclient,
+                                    services=self.testdata['volume'],
+                                    diskofferingid=self.disk_offering.id,
+                                    zoneid=self.zone.id)
+        list_volume = Volume.list(self.userapiclient, id=self.volume.id, accountid=self.account.name, domainid=self.account.domainid)
+        self.assertEqual(validateList(list_volume)[0],
+                         PASS,
+                         'Step 9: Check List volume response for volume %s' % self.volume.id)
+        self.assertEqual(list_volume[0].id,
+                         self.volume.id,
+                         'Step 9: check list volume response for volume id:  %s' % self.volume.id)
+        self.debug('Step 9: volume id %s got created successfully' % list_volume[0].id)
+
+        self.virtual_machine_3.attach_volume(self.userapiclient, self.volume)
+        list_volume = Volume.list(self.userapiclient, id=self.volume.id)
+        self.assertEqual(list_volume[0].virtualmachineid,
+                         self.virtual_machine_3.id,
+                         'Step 9: Check if volume state (attached) is reflected')
+        self.debug('Step 9: volume id:%s successfully attached to vm id%s' % (self.volume.id, self.virtual_machine_3.id))
+        if self.disabled_pool_1:
+            newpoolid = self.disabled_pool_1.id
+        else:
+            self.fail('Step 9: Could not find a second storage pool to complete the remaining tests')
+
+        # Step 10: Disable storage pool SP1 again and enable new pool
+        try:
+            StoragePool.update(self.userapiclient, id=newpoolid, enabled=True)
+        except Exception as e:
+            self.fail('Step 10: Enable storage pool %s' % e, 'failed')
+        verify_pool_state(self, newpoolid, 'Up')
+        try:
+            self.debug('Step 10: Disabling Storage Pool: %s' % self.storage_pool_1.id)
+            StoragePool.update(self.userapiclient, id=self.storage_pool_1.id, enabled=False)
+            self.disabled_list.append(self.storage_pool_1.id)
+            self.debug('Step 10: Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+        except Exception as e:
+            self.debug("Step 10: Couldn't disable pool %s" % e)
+        verify_pool_state(self, self.storage_pool_1.id, 'Disabled')
+
+        # Step 11: Deploy new VM, VM5 - should succeed
+        self.virtual_machine_4 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_4.id, 'Running')
+
+        # Step 12: Stop VM1 which is running from disabled pool
+        self.virtual_machine_1.stop(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+
+        # Step 13: Migrate ROOT volume of VM1 to another enabled storage pool - should succeed
+        if value != 'host':
+            root_volume = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='ROOT')
+            try:
+                Volume.migrate(self.userapiclient, volumeid=root_volume[0].id, storageid=newpoolid)
+            except Exception as e:
+                raise e
+            list_volume = list_volumes(self.userapiclient, id=root_volume[0].id)
+            self.assertEqual(isinstance(list_volume, list), True, 'Step 13: Check list volumes response for valid list')
+
+        # Step 14: findStoragePoolsforMigration should not list the disabled pool
+        if value != 'host':
+            pools_for_migration = StoragePool.listForMigration(self.userapiclient, id=root_volume[0].id)
+            self.debug('Step 14: List of pools suitable for migration: % s ' % pools_for_migration)
+            if pools_for_migration:
+                if self.storage_pool_1 in pools_for_migration:
+                    self.fail('Step 14: Storage pool % s is supposed to be disabled and not suitable for migration, \
+                    but found in the list of pools suitable for migration' % self.storage_pool_1.id)
+
+
+    @data('host', 'CLUSTER', 'ZONE')
+    @attr(tags=['advanced', 'advancedsg', 'basic', 'debug'], required_hardware='false')
+    def test_02_vm_operations_on_disabled_pool(self, value):
+
+        """
+        Test Steps:
+        =========
+
+        1. Deploy a VM and attach volume
+        2. Create Template from root volume of the VM
+        3. Deploy a VM using the template
+        4. Disable the storage pool
+        5. Attach a new volume - should fail
+        6. Resize DATA disk to a higher value
+        7. Take VM Snapshot of the VM (for supported hypervisors)
+        8. Destroy the VM and immediately restore the VM
+        9. Enable a new storage pool
+        10. Re-install the VM with same template
+        11. Re-install the VM with the new template created earlier
+        12. Repeat tests with enabled pool, Attach new Volume to VM2
+        13. Resize disk to a higher value
+        14. Reboot the VM
+        15. Take VM Snapshot of the VM
+        16. Destroy the VM and immediately restore the VM
+
+        """
+
+        # Choose appropriate service offering depending on the scope the test is being run on
+        self.disabled_list = []
+        if value == 'CLUSTER':
+            other_scope = 'ZONE'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        elif value == 'ZONE':
+            other_scope = 'CLUSTER'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        else:
+            # local storage
+            other_scope = None
+            self.service_offering = self.service_offering_local
+            self.disk_offering = self.disk_offering_local
+
+        # Keep one storage pool active and disable the rest
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, scope=value)
+            count_st_pools = len(self.list_storage)
+            if count_st_pools > 1:
+                self.debug('Found % s storage pools, keeping one and disabling rest' % count_st_pools)
+                for pool in self.list_storage[1:]:
+                    self.disabled_pool_1 = self.list_storage[1]
+                    if pool.state == 'Up':
+                        self.debug('Trying to disable storage %s' % pool.id)
+                        try:
+                            StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                            self.disabled_list.append(pool.id)
+                            self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                        except Exception as e:
+                            raise e
+            elif count_st_pools == 1:
+                self.debug('Only one % s wide storage found - will not be able to complete all tests' % value)
+            else:
+                self.fail('No % s wide storage pools found' % value)
+        except Exception as e:
+            raise e
+
+         # Disable the other scope shared storage pools while we are testing on one - applicable for only shared storage
+        if value != 'host':
+            try:
+                self.list_storage = StoragePool.list(self.userapiclient, scope=other_scope)
+                if self.list_storage:
+                    for pool in self.list_storage:
+                        if pool.state == 'Up':
+                            self.debug('Trying to disable storage % s' % pool.id)
+                            try:
+                                StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                                self.disabled_list.append(pool.id)
+                                self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                            except Exception as e:
+                                self.fail("Couldn't disable storage % s" % pool.id)
+                else:
+                    self.debug('No % s wide storage pools found' % other_scope)
+            except Exception as e:
+                raise e
+
+        # Step 1: Deploy a VM and attach data disk to one VM
+        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+
+        self.volume_1 = Volume.create(self.userapiclient,
+                                      services=self.testdata['volume'],
+                                      diskofferingid=self.disk_offering.id,
+                                      zoneid=self.zone.id)
+        self.virtual_machine_1.attach_volume(self.userapiclient, self.volume_1)
+        list_volume = Volume.list(self.userapiclient, id=self.volume_1.id)
+        self.assertEqual(list_volume[0].virtualmachineid,
+                         self.virtual_machine_1.id, ''
+                                                    'Check if volume state (attached) is reflected')
+        self.debug('Step 1: volume id:%s successfully attached to vm id%s' % (self.volume_1.id, self.virtual_machine_1.id))
+
+        # Step 2: Create Template from root volume of  VM1
+        root_volume_1 = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='ROOT')[0]
+        self.virtual_machine_1.stop(self.userapiclient)
+        try:
+            template_2 = Template.create(self.userapiclient,
+                                         self.testdata['template_2'],
+                                         volumeid=root_volume_1.id,
+                                         account=self.account.name,
+                                         domainid=self.account.domainid)
+            self.cleanup.append(template_2)
+            self.debug('Step 2: Created template with ID: %s' % template_2.id)
+            list_template = Template.list(self.userapiclient, templatefilter='self', id=template_2.id)
+        except Exception as e:
+            self.fail('Step 2: Template from volume failed')
+
+        # Step 3: Deploy a VM using the template
+        self.debug("Step 3: Deploying VM using template created")
+        self.virtual_machine_2 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=template_2.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+
+        verify_vm_state(self, self.virtual_machine_2.id, 'Running')
+
+        # Step 4: Disable the storage pool
+        self.storage_pools_list = StoragePool.list(self.userapiclient, scope=value, state='Up')
+        self.storage_pool_1 = self.storage_pools_list[0]
+        try:
+            self.debug('Step 4: Disabling Storage Pool: %s' % self.storage_pool_1.id)
+            StoragePool.update(self.userapiclient, id=self.storage_pool_1.id, enabled=False)
+            self.disabled_list.append(self.storage_pool_1.id)
+        except Exception as e:
+            self.debug("Step 4: Couldn't disable pool %s" % e)
+        verify_pool_state(self, self.storage_pool_1.id, 'Disabled')
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+        verify_vm_state(self, self.virtual_machine_2.id, 'Running')
+
+        # Step 5: Attach a new volume - should fail
+        self.volume_2 = Volume.create(self.userapiclient,
+                                      services=self.testdata['volume'],
+                                      diskofferingid=self.disk_offering.id,
+                                      zoneid=self.zone.id)
+        self.debug('Step 5: Trying to attach new volume to VM on disabled storage - should fail')
+        with self.assertRaises(Exception):
+            self.virtual_machine_2.attach_volume(self.userapiclient, self.volume_2)
+
+        # Step 6: Resize DATA disk to a higher value for attached disk
+        try:
+            self.volume_1.resize(self.userapiclient, diskofferingid=self.resized_disk_offering.id)
+            list_volume_1 = Volume.list(self.userapiclient, id=self.volume_1.id)
+            self.assertEqual(list_volume_1[0].diskofferingid,
+                             self.resized_disk_offering.id,
+                             'check list volume response for volume id:  %s' % self.volume_1.id)
+            self.debug('Step 6: volume id %s got resized successfully' % list_volume_1[0].id)
+        except Exception as e:
+            self.fail('Step 6: Volume resize on disabled pool failed: % s' % e)
+
+        # Step 7: Take VM Snapshot
+        if self.hypervisor.lower() not in ('kvm', 'hyperv', 'lxc'):
+            try:
+                self.debug("Step 7: Taking VM Snapshot for vm id % s" % self.virtual_machine_1.id)
+                vm_snapshot = VmSnapshot.create(self.userapiclient,
+                                                self.virtual_machine_1.id,
+                                                'false',
+                                                'TestSnapshot',
+                                                'Display Text')
+                self.assertEqual(vm_snapshot.state, 'Ready', 'Check VM snapshot is ready')
+            except Exception as e:
+                self.fail('Step 7: VM Snapshot on disabled pool failed: % s' % e)
+
+        # Step 8: Destroy VM and immediately restore the VM
+        self.debug("Step 8: Deleting and restoring the VM, should continue to run from same storage pool")
+        self.virtual_machine_1.delete(self.userapiclient, expunge=False)
+        self.virtual_machine_1.recover(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+        self.virtual_machine_1.start(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, self.storage_pool_1.id)
+
+        # Step 9: Enable new pool
+        if self.disabled_pool_1:
+            try:
+                newpoolid = self.disabled_pool_1.id
+                StoragePool.update(self.userapiclient, id=newpoolid, enabled=True)
+                self.debug("Step 9: Enabling new pool % s " % newpoolid)
+                if newpoolid in self.disabled_list:
+                    self.disabled_list.remove(newpoolid)
+            except Exception as e:
+                self.fail('Step 9: Enable storage pool %s' % e, 'failed')
+        else:
+            self.debug('Step 9: Could not find a second storage pool, so enabling the first storage pool and running the tests')
+            try:
+                self.debug('Step 9: Enabling Storage Pool: %s' % self.storage_pool_1.id)
+                StoragePool.update(self.userapiclient, id=self.storage_pool_1.id, enabled=True)
+                if self.storage_pool_1.id in self.disabled_list:
+                    self.disabled_list.remove(self.storage_pool_1.id)
+                newpoolid = self.storage_pool_1.id
+            except Exception as e:
+                self.fail("Step 9: Couldn't enable pool %s" % e)
+        verify_pool_state(self, newpoolid, 'Up')
+
+        # Step 10: Re-install the VM with same template
+        self.debug("Step 10: Re-installing VM 1")
+        vm_restore = self.virtual_machine_1.restore(self.userapiclient, templateid=self.template.id)
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, newpoolid)
+
+        # Step 11 : Re-install VM with different template
+        self.debug("Step 11: re-installing VM with different template")
+        vm_restore = self.virtual_machine_1.restore(self.userapiclient, templateid=template_2.id)
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, newpoolid)
+
+        # Step 12, Repeat tests with enabled pool. Start with attach VM
+        self.debug("Step 12: Attach volume to VM")
+        self.virtual_machine_1.attach_volume(self.userapiclient, self.volume_2)
+        list_volume_2 = Volume.list(self.userapiclient, id=self.volume_2.id)
+        self.assertEqual(list_volume_2[0].virtualmachineid,
+                         self.virtual_machine_1.id,
+        'Check if volume state (attached) is reflected')
+        self.debug('Step 12: volume id:% s successfully attached to vm id % s' % (self.volume_2.id, self.virtual_machine_1.id))
+
+        # Step 13: Re-size Volume to higher disk offering
+        try:
+            self.virtual_machine_1.stop(self.userapiclient)
+            self.volume_2.resize(self.userapiclient, diskofferingid=self.resized_disk_offering.id)
+            list_volume_2 = Volume.list(self.userapiclient, id=self.volume_2.id)
+            self.assertEqual(list_volume_2[0].diskofferingid, self.resized_disk_offering.id, 'check list volume response for volume id:  %s' % self.volume_2.id)
+            self.debug('Step 13: volume id %s got resized successfully' % list_volume_2[0].id)
+        except Exception as e:
+            self.fail('Step 13: Failed to resize volume % s ' % e)
+        self.virtual_machine_1.start(self.userapiclient)
+
+        # Step 14: Reboot VM
+        self.virtual_machine_1.reboot(self.userapiclient)
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, newpoolid)
+
+        # Step 15: Take Snapshot of VM
+        if self.hypervisor.lower() not in ('kvm', 'hyperv', 'lxc'):
+            try:
+                vm_snapshot = VmSnapshot.create(self.userapiclient, self.virtual_machine_1.id, 'false', 'TestSnapshot2', 'Display Text')
+                self.assertEqual(vm_snapshot.state, 'Ready', 'Check the snapshot of vm is ready!')
+            except Exception as e:
+                self.fail('Step 15: Snapshot failed post enabling new storage pool')
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, newpoolid)
+
+        # Step 16: Delete and recover VM
+        self.debug("Step 16: Deleting and recovering VM")
+        self.virtual_machine_1.delete(self.userapiclient, expunge=False)
+        self.virtual_machine_1.recover(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+        self.virtual_machine_1.start(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, newpoolid)
+
+
+@ddt
+class TestPathDisableStorage_Maint_Tags(cloudstackTestCase):
+    """
+        # Tests in this path requires to be run independently (not to be run in parallel  with any other tests since it involves disabling/enabling storage pools and may cause unexpected failures in other tests
+        # The test also requires to have 2 Cluster-wide and 2 zone-wide storage pools available in the setup.
+        # For running the tests on local storage, ensure there are 2 local storage pools set up on each host or different hosts
+
+        """
+
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestPathDisableStorage_Maint_Tags, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient)
+        cls.testdata['mode'] = cls.zone.networktype
+        cls.template = get_template(cls.apiclient, cls.zone.id, cls.testdata['ostype'])
+        cls.testdata['template']['ostypeid'] = cls.template.ostypeid
+        if cls.template == FAILED:
+            cls.fail('get_template() failed to return template with description %s' % cls.testdata['ostype'])
+        cls._cleanup = []
+        cls.disabled_list = []
+        cls.maint_list = []
+        cls.testdata['template_2']['zoneid'] = cls.zone.id
+        cls.testdata['template_2']['ostypeid'] = cls.template.ostypeid
+        cls.hypervisor = testClient.getHypervisorInfo()
+        try:
+            cls.account = Account.create(cls.apiclient,
+                                         cls.testdata['account'],
+                                         admin=True)
+            cls.debug('Creating account')
+            cls._cleanup.append(cls.account)
+
+
+            # Create shared storage offerings
+            cls.service_offering_shared = ServiceOffering.create(cls.apiclient,
+                                                          cls.testdata['service_offering']
+                                                          )
+            cls._cleanup.append(cls.service_offering_shared)
+            cls.disk_offering_shared = DiskOffering.create(cls.apiclient,
+                                                    cls.testdata['disk_offering']
+                                                    )
+            cls.resized_disk_offering = DiskOffering.create(cls.apiclient,
+                                                            cls.testdata['resized_disk_offering']
+                                                            )
+            cls._cleanup.append(cls.disk_offering_shared)
+
+            # Create offerings for local storage if local storage is enabled
+            if cls.zone.localstorageenabled:
+                cls.testdata["service_offerings"]["storagetype"] = 'local'
+                cls.debug("Creating local storage offering")
+                cls.service_offering_local = ServiceOffering.create(cls.apiclient,
+                                                                cls.testdata["service_offerings"]
+                                                                )
+                cls._cleanup.append(cls.service_offering_local)
+                cls.testdata["disk_offering"]["storagetype"] = 'local'
+                cls.debug("Creating local storage disk offering")
+                cls.disk_offering_local = DiskOffering.create(cls.apiclient,
+                                                              cls.testdata["disk_offering"]
+                                                              )
+                cls._cleanup.append(cls.disk_offering_local)
+                cls.testdata["disk_offering"]["storagetype"] = ' '
+                cls.testdata["service_offerings"]["storagetype"] = ' '
+            else:
+                cls.debug("No local storage found")
+
+            cls.userapiclient = testClient.getUserApiClient(UserName=cls.account.name, DomainName=cls.account.domain)
+            response = User.login(cls.userapiclient,
+                                  username=cls.account.name,
+                                  password=cls.testdata['account']['password'])
+            assert response.sessionkey is not None
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception('Warning:Exception during cleanup: %s' % e)
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.cleanup = []
+
+    def tearDown(self):
+        if self.disabled_list:
+            for poolid in self.disabled_list:
+                if StoragePool.list(self.userapiclient, id=poolid)[0].state == 'Disabled':
+                    try:
+                        StoragePool.update(self.userapiclient, id=poolid, enabled=True)
+                        self.debug('Enabling: % s ' % poolid)
+                    except Exception as e:
+                        self.fail("Couldn't enable storage % s" % id)
+
+        if self.maint_list:
+            for poolid in self.maint_list:
+                if StoragePool.list(self.userapiclient, id=poolid)[0].state == 'Maintenance':
+                    try:
+                        StoragePool.cancelMaintenance(self.userapiclient, id=poolid)
+                        self.debug('Cancelled Maintenance mode for % s' % poolid)
+                    except Exception as e:
+                        self.fail("Couldn't cancel Maintenance mode for storage % s " % poolid)
+
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            self.fail('Warning: Exception during cleanup : %s' % e)
+
+
+    @data('host','CLUSTER', 'ZONE')
+    @attr(tags=['advanced', 'advancedsg', 'debug', 'basic'], required_hardware='false')
+    def test_01_maint_capacity_tags(self, value):
+        """
+
+        Test Steps:
+        ========
+
+        1. Deploy VM
+        2. Add storage to maintenance
+        3. Cancel Maintenance
+        4. Disable pool and then Start the VM - verify it runs off the same pool
+        5. Perform more VM operations - reboot
+        6. Add tags to pool
+        7. Create tagged offering with same tags
+        8. Enable pool
+        9. Deploy VM using the tagged offering
+        10. Disable storage pool again
+        11. Calculate current capacity used so far for the storage pool
+        12. Delete VM and check capacity is re-calculated in the disabled pool
+        13. Perform VM deploy - should fail since pool is disabled
+        14. Re-calculate Capacity, should not be altered
+
+
+            """
+
+        # Choose appropriate service offering depending on the scope the test is being run on
+        self.disabled_list = []
+        if value == 'CLUSTER':
+            other_scope = 'ZONE'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        elif value == 'ZONE':
+            other_scope = 'CLUSTER'
+            self.service_offering = self.service_offering_shared
+            self.disk_offering = self.disk_offering_shared
+        else:
+            # local storage
+            other_scope = None
+            self.service_offering = self.service_offering_local
+            self.disk_offering = self.disk_offering_local
+
+        # Keep 2 storage pools active and disable the rest. If only one storage pool is present, then skip the test
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, scope=value)
+            count_st_pools = len(self.list_storage)
+            if count_st_pools <= 1:
+                raise unittest.SkipTest('Found 1 or less storage pools in % s wide scope- cannot proceed' % value)
+            elif count_st_pools > 2:
+                for pool in self.list_storage[2:]:
+                    if pool.state == 'Up':
+                        self.debug('Trying to disable storage %s' % pool.id)
+                        try:
+                            StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                            self.disabled_list.append(pool.id)
+                            self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                        except Exception as e:
+                            raise e
+            elif count_st_pools == 2:
+                for pool in self.list_storage:
+                    if pool.state != 'Up':
+                        raise unittest.SkipTest('Found storage pool % s not in Up State.. cannot proceed' % pool.id)
+        except Exception as e:
+            raise e
+
+
+         # Disable the other scope shared storage pools while we are testing on one - applicable for only shared storage
+        if value != 'host':
+            try:
+                self.list_storage = StoragePool.list(self.userapiclient, scope=other_scope)
+                if self.list_storage:
+                    for pool in self.list_storage:
+                        if pool.state == 'Up':
+                            self.debug('Trying to disable storage % s' % pool.id)
+                            try:
+                                StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                                self.disabled_list.append(pool.id)
+                                self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                            except Exception as e:
+                                self.fail("Couldn't disable storage % s" % pool.id)
+                else:
+                    self.debug('No % s wide storage pools found' % other_scope)
+            except Exception as e:
+                raise e
+
+        self.debug("Step 1: Deploy VM")
+        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+
+        # Step 2: Add storage to Maintenance mode
+        self.debug("Step 2: Adding storage to maintenance mode ")
+        root_volume = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='ROOT')[0]
+        list_volume = Volume.list(self.userapiclient, id=root_volume.id)
+        storage_id = list_volume[0].storageid
+        try:
+            StoragePool.enableMaintenance(self.userapiclient, id=storage_id)
+            self.debug('Step 2: Added % s to Maintenance mode')
+            self.maint_list.append(storage_id)
+        except Exception as e:
+            self.fail('Step 2: Failed to add Storage pool % s to Maintenance mode' % storage_id)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+
+        #Step 3: Cancel maintenance mode
+        try:
+            StoragePool.cancelMaintenance(self.userapiclient, id=storage_id)
+            self.debug('Step 3: Cancelled Maintenance mode for % s' % storage_id)
+            self.maint_list.remove(storage_id)
+        except Exception as e:
+            self.fail("Step 3: Couldn't cancel Maintenance mode for storage % s " % storage_id)
+
+        # Step 4: Start the VM after disabling pool and verify it's running from same pool
+        try:
+            self.debug("Step 4: Starting VM after disabling pool")
+            self.list_storage = StoragePool.list(self.userapiclient, id=storage_id)
+            if self.list_storage[0].state == 'Up':
+                StoragePool.update(self.userapiclient, id=storage_id, enabled=False)
+                self.debug("Step 4: Disabled pool % s" % storage_id)
+                self.disabled_list.append(storage_id)
+        except Exception as e:
+            raise e
+
+        list_vm = list_virtual_machines(self.userapiclient, account=self.account.name, domainid=self.account.domainid, id=self.virtual_machine_1.id)
+        vm = list_vm[0]
+        if vm.state != 'Running':
+            self.virtual_machine_1.start(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, storage_id)
+
+        # Step 5: Perform some VM operations - reboot
+        self.debug("Step 5: Performing reboot of VM % s" % self.virtual_machine_1.id)
+        self.virtual_machine_1.reboot(self.userapiclient)
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, storage_id)
+
+        # TO BE REMOVED
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, id=storage_id)
+            if self.list_storage[0].state == 'Disabled':
+                StoragePool.update(self.userapiclient, id=storage_id, enabled=True)
+                self.disabled_list.remove(storage_id)
+        except Exception as e:
+            raise e
+
+
+        # Step 6: Add tags to the storage pool
+        self.debug("Step 6: Adding tags to storage pool")
+        StoragePool.update(self.userapiclient, id=storage_id, tags='disable_prov')
+
+        # Step 7: Add tagged service offering
+        self.testdata['service_offerings']['tags'] = 'disable_prov'
+        self.testdata["service_offerings"]["storagetype"] = 'local'
+        self.tagged_so = ServiceOffering.create(self.userapiclient, self.testdata['service_offerings'])
+        self.testdata['service_offerings']['tags'] = ' '
+        self.testdata["service_offerings"]["storagetype"] = ' '
+        self.cleanup.append(self.tagged_so)
+
+        # Step 8: Enable the pool
+        try:
+            self.debug("Step 8: Enabling pool")
+            self.list_storage = StoragePool.list(self.userapiclient, id=storage_id)
+            if self.list_storage[0].state == 'Disabled':
+                StoragePool.update(self.userapiclient, id=storage_id, enabled=True)
+                self.disabled_list.remove(storage_id)
+        except Exception as e:
+            raise e
+
+        # Step 9: Deploy VM using the tagged offering
+        self.debug("Step 9: Deploying VM using tagged offering")
+        self.virtual_machine_2 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.tagged_so.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_2.id, 'Running')
+        verify_vm_storage_pool(self, self.virtual_machine_2.id, storage_id)
+
+        # Step 10: Disable storage Pool
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, id=storage_id)
+            if self.list_storage[0].state == 'Up':
+                StoragePool.update(self.userapiclient, id=storage_id, enabled=False)
+                if storage_id not in self.disabled_list:
+                    self.disabled_list.append(storage_id)
+        except Exception as e:
+            raise e
+
+        if value != 'host':
+            capacity_type = 2
+        else:
+            capacity_type = 9
+
+        # Step 11: View current capacity of storage pool
+        self.debug("Step 11: Getting current capacity...")
+        list_capacity_allocated = Capacities.list(self.userapiclient, fetchlatest='true', type=capacity_type)
+        capacity_1 = list_capacity_allocated[0].capacityused
+        self.debug("Capacity 1: % s" % capacity_1)
+
+        # Step 12: Delete VM and check capacity is recalculated in disabled pool
+        self.debug("Step 12: Deleting Vm and re-calculating capacity")
+        self.virtual_machine_2.delete(self.userapiclient)
+        list_capacity_allocated = Capacities.list(self.userapiclient, fetchlatest='true', type=capacity_type)
+        capacity_2 = list_capacity_allocated[0].capacityused
+        self.debug("Capacity 2: % s" % capacity_2)
+        self.assertGreater(capacity_1,
+                           capacity_2,
+                           'Step 12: Capacity Used should be greater after VM delete although Storage is not enabled')
+
+        # Step 13: Deploy new VM with tagged offering again - should fail
+        with self.assertRaises(Exception):
+            self.virtual_machine_3 = VirtualMachine.create(self.userapiclient,
+                                                           self.testdata['small'],
+                                                           templateid=self.template.id,
+                                                           accountid=self.account.name,
+                                                           domainid=self.account.domainid,
+                                                           serviceofferingid=self.tagged_so.id,
+                                                           zoneid=self.zone.id)
+
+        # Step 14: Capacity should not be altered in disabled pool since deploy VM failed
+        self.debug("Step 14: Checking capacity is not altered after deploy VM fails")
+        list_capacity_allocated = Capacities.list(self.userapiclient, fetchlatest='true', type=capacity_type)
+        capacity_3 = list_capacity_allocated[0].capacityused
+        self.assertEqual(capacity_2, capacity_3, "Step 14: Capacity Used shouldn't be altered since VM deployment failed")
+
+
+class TestPathDisableStorage_Cross_Cluster(cloudstackTestCase):
+    """
+        # Tests in this path requires to be run independently (not to be run in parallel  with any other tests \
+        since it involves disabling/enabling storage pools and may cause unexpected failures in other tests
+        # This test atleast 2 Clusters in the set up wiht suitable hosts for migration.
+        # For running the tests on local storage, ensure there are 2 local storage pools set up on each host
+
+        """
+
+
+    @classmethod
+    def setUpClass(cls):
+        testClient = super(TestPathDisableStorage_Cross_Cluster, cls).getClsTestClient()
+        cls.apiclient = testClient.getApiClient()
+        cls.testdata = testClient.getParsedTestDataConfig()
+        cls.domain = get_domain(cls.apiclient)
+        cls.zone = get_zone(cls.apiclient)
+        cls.testdata['mode'] = cls.zone.networktype
+        cls.template = get_template(cls.apiclient, cls.zone.id, cls.testdata['ostype'])
+        cls.testdata['template']['ostypeid'] = cls.template.ostypeid
+        if cls.template == FAILED:
+            cls.fail('get_template() failed to return template with description %s' % cls.testdata['ostype'])
+
+        cls._cleanup = []
+        cls.disabled_list = []
+        cls.maint_list = []
+        cls.testdata['template_2']['zoneid'] = cls.zone.id
+        cls.testdata['template_2']['ostypeid'] = cls.template.ostypeid
+        cls.hypervisor = testClient.getHypervisorInfo()
+
+        try:
+            cls.account = Account.create(cls.apiclient, cls.testdata['account'], admin=True)
+            cls.debug('Creating account')
+            cls._cleanup.append(cls.account)
+            cls.service_offering = ServiceOffering.create(cls.apiclient,
+                                                          cls.testdata['service_offering'])
+            cls._cleanup.append(cls.service_offering)
+            cls.disk_offering = DiskOffering.create(cls.apiclient,
+                                                    cls.testdata['disk_offering'])
+            cls.resized_disk_offering = DiskOffering.create(cls.apiclient,
+                                                            cls.testdata['resized_disk_offering'])
+            cls._cleanup.append(cls.disk_offering)
+
+            cls.userapiclient = testClient.getUserApiClient(UserName=cls.account.name,
+                                                            DomainName=cls.account.domain)
+            response = User.login(cls.userapiclient,
+                                  username=cls.account.name,
+                                  password=cls.testdata['account']['password'])
+            assert response.sessionkey is not None
+        except Exception as e:
+            cls.tearDownClass()
+            raise e
+
+
+    @classmethod
+    def tearDownClass(cls):
+        try:
+            cleanup_resources(cls.apiclient, cls._cleanup)
+        except Exception as e:
+            raise Exception('Warning:Exception during cleanup: %s' % e)
+
+
+    def setUp(self):
+        self.apiclient = self.testClient.getApiClient()
+        self.cleanup = []
+
+    def tearDown(self):
+        if self.disabled_list:
+            for poolid in self.disabled_list:
+                if StoragePool.list(self.userapiclient, id=poolid)[0].state == 'Disabled':
+                    try:
+                        StoragePool.update(self.userapiclient, id=poolid, enabled=True)
+                        self.debug('Enabling: % s ' % poolid)
+                    except Exception as e:
+                        self.fail("Couldn't enable storage % s" % id)
+        try:
+            cleanup_resources(self.apiclient, self.cleanup)
+        except Exception as e:
+            self.fail('Warning: Exception during cleanup : %s' % e)
+
+    @attr(tags=['advanced', 'advancedsg', 'basic'], required_hardware='false')
+    def test_01_cross_cluster_attach_disk(self):
+        """
+            Test Steps:
+            ========
+
+            1. Deploy VM in one cluster
+            2. Migrate to other cluster
+            3. Add data disk, Attach to VM
+            4. Disable first storage pool
+            5. List for migration should not list the first pool anymore
+            6. Stop VM and detach disk
+            7. Enable first Pool
+            8. Migrate root to first pool
+            9. Now disable first pool again
+            10. Attach the disk which is running from enabled pool - Should fail
+            11.Enable pool again
+            12. Attach disk should now pass
+
+            """
+        cluster_id_list = []
+        clusters = list_clusters(self.userapiclient, listall='true')
+        if len(clusters) == 1:
+            raise unittest.SkipTest('Found only one cluster... skipping test')
+        for cluster in clusters:
+            try:
+                self.debug('Processing for cluster % s ' % cluster.id)
+                self.list_storage = StoragePool.list(self.userapiclient, clusterid=cluster.id, scope='CLUSTER')
+                count_st_pools = len(self.list_storage)
+                if count_st_pools > 1:
+                    self.debug('Found % s storage pools in cluster % s, keeping one and disabling rest' % (count_st_pools, cluster.id))
+                    for pool in self.list_storage[1:]:
+                        self.disabled_pool_1 = self.list_storage[1]
+                        if pool.state == 'Up':
+                            self.debug('Trying to disable storage %s' % pool.id)
+                            try:
+                                StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                                self.disabled_list.append(pool.id)
+                                self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                            except Exception as e:
+                                raise e
+                elif count_st_pools == 1:
+                    self.debug('Only one cluster wide storage found')
+                else:
+                    self.fail('No cluster wide storage pools found')
+            except Exception as e:
+                raise e
+
+        try:
+            self.list_storage = StoragePool.list(self.userapiclient, scope='ZONE')
+            if self.list_storage:
+                for pool in self.list_storage:
+                    if pool.state == 'Up':
+                        self.debug('Trying to disable storage % s' % pool.id)
+                        try:
+                            StoragePool.update(self.userapiclient, id=pool.id, enabled=False)
+                            self.disabled_list.append(pool.id)
+                            self.debug('Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+                        except Exception as e:
+                            self.fail("Couldn't disable storage % s" % pool.id)
+            else:
+                self.debug('No zone wide storage pools found')
+        except Exception as e:
+            raise e
+
+        # Step 1: Deploy VM in a cluster
+        self.virtual_machine_1 = VirtualMachine.create(self.userapiclient,
+                                                       self.testdata['small'],
+                                                       templateid=self.template.id,
+                                                       accountid=self.account.name,
+                                                       domainid=self.account.domainid,
+                                                       serviceofferingid=self.service_offering.id,
+                                                       zoneid=self.zone.id)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+
+        root_vol = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='ROOT')[0]
+        storage_1 = root_vol.storageid
+        host_1 = self.virtual_machine_1.hostid
+        self.debug("Step 1: VM1 is running on % s host and % s storage pool" % (host_1, storage_1))
+
+        # Step 2: Live Migrate VM to another cluster
+        hosts_for_migration = Host.listForMigration(self.userapiclient, virtualmachineid=self.virtual_machine_1.id)
+        self.debug('Step 2: List of hosts suitable for migration: % s ' % hosts_for_migration)
+        host_2 = None
+        for host in hosts_for_migration:
+            self.debug('Step 2: Host Requires storage motion is % s ' % host.requiresStorageMotion)
+            if host.requiresStorageMotion == True:
+                host_2 = host.id
+
+        if host_2:
+            self.debug('Step 2: Migrating VM % s to Host % s' % (self.virtual_machine_1.id, host_2))
+            self.virtual_machine_1.migrate_vm_with_volume(self.userapiclient, hostid=host_2)
+        else:
+            self.fail('Step 2: No host found suitable for migration')
+
+        # Step 3: Add data disk and attach to VM
+        self.volume_1 = Volume.create(self.userapiclient,
+                                      services=self.testdata['volume'],
+                                      diskofferingid=self.disk_offering.id,
+                                      zoneid=self.zone.id)
+        self.virtual_machine_1.attach_volume(self.userapiclient, self.volume_1)
+        list_volume = Volume.list(self.userapiclient, id=self.volume_1.id)
+
+
+        self.assertEqual(list_volume[0].virtualmachineid,
+                         self.virtual_machine_1.id,
+                         'Step 3: Check if volume state (attached) is reflected')
+        self.debug('Step 3: volume id:% s successfully attached to vm id % s' % (self.volume_1.id, self.virtual_machine_1.id))
+
+        root_vol = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='ROOT')[0]
+        storage_2 = root_vol.storageid
+        data_vol = Volume.list(self.userapiclient, virtualmachineid=self.virtual_machine_1.id, type='DATA')[0]
+        self.debug("Step 3: Data Volume is in storage pool: % s" % data_vol.storageid)
+        self.assertEqual(data_vol.storageid,
+                         root_vol.storageid,
+                         "Step 3: Root and Data disk should be running from 2nd storage pool where the VM was live migrated")
+
+        # Step 4: Disable first Storage Pool and verify it is not listed in hosts suitable for migration
+        try:
+            StoragePool.update(self.userapiclient, id=storage_1, enabled=False)
+            self.disabled_list.append(storage_1)
+            self.debug('Step 4: Appended to list of disabled pools. List is now: % s ' % self.disabled_list)
+        except Exception as e:
+            self.fail("Step 4: Couldn't disable storage % s" % storage_1)
+
+        # Step 5: Disabled pool shouldn't be listed in hostsforMigration since all pools in the cluster are disabled
+        hosts_for_migration = Host.listForMigration(self.userapiclient, virtualmachineid=self.virtual_machine_1.id)
+        self.debug("Step 5: List of Hosts For Migration is % s" % hosts_for_migration)
+        if hosts_for_migration:
+            for host in hosts_for_migration:
+                if host_1 == host.id:
+                    self.fail("Step 5: All pools in the cluster are disabled, hence host should not be listed for migration")
+
+        # Step 6: Stop VM and Detach Disk
+        self.virtual_machine_1.stop(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Stopped')
+        verify_vm_storage_pool(self, self.virtual_machine_1.id, storage_2)
+        self.debug("Step 6: Stopping VM and detaching disk")
+        self.virtual_machine_1.detach_volume(self.userapiclient, volume=self.volume_1)
+
+        # Step 7, 8: Enable Pool for Migrating VM and disable again
+        try:
+            StoragePool.update(self.userapiclient, id=storage_1, enabled=True)
+            if storage_1 in self.disabled_list:
+                self.disabled_list.remove(storage_1)
+        except Exception as e:
+            self.fail("Step 7: Couldn't enable storage % s" % storage_1)
+
+
+        self.virtual_machine_1.start(self.userapiclient)
+        verify_vm_state(self, self.virtual_machine_1.id, 'Running')
+
+        try:
+            self.debug('Step 8: Migrating VM % s to Host % s' % (self.virtual_machine_1.id, host_1))
+            self.virtual_machine_1.migrate_vm_with_volume(self.userapiclient, hostid=host_1)
+        except Exception as e:
+            self.fail("Step 8: Couldn't live migrate VM to host % s due to % s" % (host_1, e))
+
+        # Step 9: disable pool again
+        try:
+            StoragePool.update(self.userapiclient, id=storage_1, enabled=False)
+            self.debug("Step 9: Disabling storage pool: % s " % storage_1)
+            self.disabled_list.append(storage_1)
+        except Exception as e:
+            self.fail("Step 9: Couldn't disable storage % s" % storage_1)
+
+
+        st_list = StoragePool.list(self.userapiclient, id=storage_1)
+        self.debug("9.5 Status of storage pool 1 % s  is % s " % (st_list[0].name, st_list[0].state))
+
+
+        # Step 10: Try to attach data disk running from enabled pool with Root running in disabled pool - this should fail
+        with self.assertRaises(Exception):
+             self.virtual_machine_1.attach_volume(self.userapiclient, self.volume_1)
+             self.debug("Step 10: Trying to attach volume % s" % self.volume_1.id)
+
+
+        # Step 11: Enable the pool and try to attach again - this should pass
+        try:
+            StoragePool.update(self.userapiclient, id=storage_1, enabled=True)
+            self.debug("Step 11: Enable storage pool: % s " % storage_1)
+            self.disabled_list.remove(storage_1)
+        except Exception as e:
+            self.fail("Step 11: Couldn't enable storage % s" % storage_1)
+
+        # Step 12: Repeat attach volume - should succeed
+        self.virtual_machine_1.attach_volume(self.userapiclient, self.volume_1)
+        self.debug("Step 12: Trying to attach volume")
+        list_volume = Volume.list(self.userapiclient, id=self.volume_1.id)
+
+        self.assertEqual(list_volume[0].virtualmachineid,
+                         self.virtual_machine_1.id,
+                         'Step 12: Check if volume state (attached) is reflected')
+        self.debug('Step 12: volume id:%s successfully attached to vm id%s' % (self.volume_1.id, self.virtual_machine_1.id))


[09/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtDeleteStoragePoolCommandWrapper, LibvirtGetStorageStatsCommandWrapper and LibvirtUpgradeSnapshotCommandWrapper
  - 7 unit tests added
  - KVM hypervisor plugin with 13.6% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/0d860af6
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0d860af6
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0d860af6

Branch: refs/heads/CLOUDSTACK-8301
Commit: 0d860af659da24b509910e5edbce95d58c6fe569
Parents: 8268d35
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Apr 30 21:33:19 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:11 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  33 ----
 .../LibvirtDeleteStoragePoolCommandWrapper.java |  43 +++++
 .../LibvirtGetStorageStatsCommandWrapper.java   |  43 +++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   6 +
 .../LibvirtUpgradeSnapshotCommandWrapper.java   |  33 ++++
 .../resource/LibvirtComputingResourceTest.java  | 177 ++++++++++++++++++-
 6 files changed, 301 insertions(+), 34 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 8e9cbc1..f72fecf 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -95,11 +95,8 @@ import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
-import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.FenceAnswer;
 import com.cloud.agent.api.FenceCommand;
-import com.cloud.agent.api.GetStorageStatsAnswer;
-import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
@@ -134,7 +131,6 @@ import com.cloud.agent.api.StartupRoutingCommand;
 import com.cloud.agent.api.StartupStorageCommand;
 import com.cloud.agent.api.UnPlugNicAnswer;
 import com.cloud.agent.api.UnPlugNicCommand;
-import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmDiskStatsEntry;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.check.CheckSshAnswer;
@@ -1298,8 +1294,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         try {
             if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
                 return execute((CreatePrivateTemplateFromVolumeCommand)cmd);
-            } else if (cmd instanceof GetStorageStatsCommand) {
-                return execute((GetStorageStatsCommand)cmd);
             } else if (cmd instanceof ManageSnapshotCommand) {
                 return execute((ManageSnapshotCommand)cmd);
             } else if (cmd instanceof BackupSnapshotCommand) {
@@ -1308,16 +1302,12 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((CreateVolumeFromSnapshotCommand)cmd);
             } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                 return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
-            } else if (cmd instanceof UpgradeSnapshotCommand) {
-                return execute((UpgradeSnapshotCommand)cmd);
             } else if (cmd instanceof CreateStoragePoolCommand) {
                 return execute((CreateStoragePoolCommand)cmd);
             } else if (cmd instanceof ModifyStoragePoolCommand) {
                 return execute((ModifyStoragePoolCommand)cmd);
             } else if (cmd instanceof SecurityGroupRulesCmd) {
                 return execute((SecurityGroupRulesCmd)cmd);
-            } else if (cmd instanceof DeleteStoragePoolCommand) {
-                return execute((DeleteStoragePoolCommand)cmd);
             } else if (cmd instanceof FenceCommand) {
                 return execute((FenceCommand)cmd);
             } else if (cmd instanceof StartCommand) {
@@ -1657,15 +1647,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected Answer execute(final DeleteStoragePoolCommand cmd) {
-        try {
-            _storagePoolMgr.deleteStoragePool(cmd.getPool().getType(), cmd.getPool().getUuid());
-            return new Answer(cmd);
-        } catch (final CloudRuntimeException e) {
-            return new Answer(cmd, false, e.toString());
-        }
-    }
-
     protected FenceAnswer execute(final FenceCommand cmd) {
         final ExecutorService executors = Executors.newSingleThreadExecutor();
         final List<NfsStoragePool> pools = _monitor.getStoragePools();
@@ -2520,11 +2501,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected Answer execute(final UpgradeSnapshotCommand cmd) {
-
-        return new Answer(cmd, true, "success");
-    }
-
     protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) {
         final String templateFolder = cmd.getAccountId() + File.separator + cmd.getNewTemplateId();
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
@@ -2582,15 +2558,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected GetStorageStatsAnswer execute(final GetStorageStatsCommand cmd) {
-        try {
-            final KVMStoragePool sp = _storagePoolMgr.getStoragePool(cmd.getPooltype(), cmd.getStorageId(), true);
-            return new GetStorageStatsAnswer(cmd, sp.getCapacity(), sp.getUsed());
-        } catch (final CloudRuntimeException e) {
-            return new GetStorageStatsAnswer(cmd, e.toString());
-        }
-    }
-
     protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromVolumeCommand cmd) {
         final String secondaryStorageURL = cmd.getSecondaryStorageUrl();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteStoragePoolCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteStoragePoolCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteStoragePoolCommandWrapper.java
new file mode 100644
index 0000000..9b0b245
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteStoragePoolCommandWrapper.java
@@ -0,0 +1,43 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.DeleteStoragePoolCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtDeleteStoragePoolCommandWrapper extends CommandWrapper<DeleteStoragePoolCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final DeleteStoragePoolCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            StorageFilerTO pool = command.getPool();
+            KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            storagePoolMgr.deleteStoragePool(pool.getType(), pool.getUuid());
+            return new Answer(command);
+        } catch (final CloudRuntimeException e) {
+            return new Answer(command, false, e.toString());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetStorageStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetStorageStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetStorageStatsCommandWrapper.java
new file mode 100644
index 0000000..98deae2
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetStorageStatsCommandWrapper.java
@@ -0,0 +1,43 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.GetStorageStatsAnswer;
+import com.cloud.agent.api.GetStorageStatsCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtGetStorageStatsCommandWrapper extends CommandWrapper<GetStorageStatsCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final GetStorageStatsCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            final KVMStoragePool sp = storagePoolMgr.getStoragePool(command.getPooltype(), command.getStorageId(), true);
+            return new GetStorageStatsAnswer(command, sp.getCapacity(), sp.getUsed());
+        } catch (final CloudRuntimeException e) {
+            return new GetStorageStatsAnswer(command, e.toString());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 7c9b443..04aa2ea 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -26,7 +26,9 @@ import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.Command;
+import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
+import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
@@ -39,6 +41,7 @@ import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
+import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
@@ -88,6 +91,9 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
         linbvirtCommands.put(DestroyCommand.class, new LibvirtDestroyCommandWrapper());
         linbvirtCommands.put(PrimaryStorageDownloadCommand.class, new LibvirtPrimaryStorageDownloadCommandWrapper());
+        linbvirtCommands.put(GetStorageStatsCommand.class, new LibvirtGetStorageStatsCommandWrapper());
+        linbvirtCommands.put(UpgradeSnapshotCommand.class, new LibvirtUpgradeSnapshotCommandWrapper());
+        linbvirtCommands.put(DeleteStoragePoolCommand.class, new LibvirtDeleteStoragePoolCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpgradeSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpgradeSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpgradeSnapshotCommandWrapper.java
new file mode 100644
index 0000000..0f0fb9a
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUpgradeSnapshotCommandWrapper.java
@@ -0,0 +1,33 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.UpgradeSnapshotCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtUpgradeSnapshotCommandWrapper extends CommandWrapper<UpgradeSnapshotCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final UpgradeSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        return new Answer(command, true, "success");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0d860af6/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 946d871..2432c98 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -68,7 +68,9 @@ import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
+import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
+import com.cloud.agent.api.GetStorageStatsCommand;
 import com.cloud.agent.api.GetVmDiskStatsCommand;
 import com.cloud.agent.api.GetVmStatsCommand;
 import com.cloud.agent.api.GetVncPortCommand;
@@ -81,12 +83,14 @@ import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.StopCommand;
+import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.VmStatsEntry;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
+import com.cloud.agent.api.to.DataStoreTO;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
@@ -557,6 +561,40 @@ public class LibvirtComputingResourceTest {
         }
     }
 
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testGetVmDiskStatsCommandException() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
+        final List<String> vms = new ArrayList<String>();
+        vms.add(vmName);
+
+        final GetVmDiskStatsCommand command = new GetVmDiskStatsCommand(vms, uuid, "hostname");
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnection()).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnection();
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
     @Test
     public void testRebootCommand() {
         final Connect conn = Mockito.mock(Connect.class);
@@ -619,6 +657,39 @@ public class LibvirtComputingResourceTest {
         }
     }
 
+    @Test
+    public void testRebootRouterCommandConnect() {
+        final VirtualRoutingResource routingResource = Mockito.mock(VirtualRoutingResource.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String vmName = "Test";
+        final RebootRouterCommand command = new RebootRouterCommand(vmName, "192.168.0.10");
+
+        when(libvirtComputingResource.getVirtRouterResource()).thenReturn(routingResource);
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(routingResource.connect(command.getPrivateIpAddress())).thenReturn(true);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(vmName)).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getVirtRouterResource();
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
     @Test(expected = NumberFormatException.class)
     public void testGetHostStatsCommand() {
         // A bit difficult to test due to the logger being passed and the parser itself relying on the connection.
@@ -1533,4 +1604,108 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
         verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), command.getPoolUuid());
     }
-}
+
+    @Test
+    public void testGetStorageStatsCommand() {
+        final DataStoreTO store = Mockito.mock(DataStoreTO.class);
+        final GetStorageStatsCommand command = new GetStorageStatsCommand(store );
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(command.getPooltype(), command.getStorageId(), true)).thenReturn(secondaryPool);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePool(command.getPooltype(), command.getStorageId(), true);
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testGetStorageStatsCommandException() {
+        final DataStoreTO store = Mockito.mock(DataStoreTO.class);
+        final GetStorageStatsCommand command = new GetStorageStatsCommand(store );
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testUpgradeSnapshotCommand() {
+        final StoragePool pool = null;
+        final String secondaryStoragePoolURL = null;
+        final Long dcId = null;
+        final Long accountId = null;
+        final Long volumeId = null;
+        final Long templateId = null;
+        final Long tmpltAccountId = null;
+        final String volumePath = null;
+        final String snapshotUuid = null;
+        final String snapshotName = null;
+        final String version = null;
+
+        final UpgradeSnapshotCommand command = new UpgradeSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, templateId, tmpltAccountId, volumePath, snapshotUuid, snapshotName, version);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testDeleteStoragePoolCommand() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+
+        final DeleteStoragePoolCommand command = new DeleteStoragePoolCommand(storagePool);
+
+        final StorageFilerTO pool = command.getPool();
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.deleteStoragePool(pool.getType(), pool.getUuid())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).deleteStoragePool(pool.getType(), pool.getUuid());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testDeleteStoragePoolCommandException() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+
+        final DeleteStoragePoolCommand command = new DeleteStoragePoolCommand(storagePool);
+
+        final StorageFilerTO pool = command.getPool();
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.deleteStoragePool(pool.getType(), pool.getUuid())).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).deleteStoragePool(pool.getType(), pool.getUuid());
+    }
+}
\ No newline at end of file


[28/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Fixing method call on KVMGuru to reach StorageSubSystemCommand


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b284b841
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b284b841
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b284b841

Branch: refs/heads/CLOUDSTACK-8301
Commit: b284b841929c74a8e5273f8a31a26ed9bba5d139
Parents: 74ad48d
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 16:55:03 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:16 2015 +0200

----------------------------------------------------------------------
 .../apache/cloudstack/storage/command/StorageSubSystemCommand.java | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b284b841/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
----------------------------------------------------------------------
diff --git a/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java b/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
index 6507bb0..f50a5fb 100644
--- a/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
+++ b/core/src/org/apache/cloudstack/storage/command/StorageSubSystemCommand.java
@@ -22,5 +22,5 @@ package org.apache.cloudstack.storage.command;
 import com.cloud.agent.api.Command;
 
 public abstract class StorageSubSystemCommand extends Command {
-    abstract void setExecuteInSequence(boolean inSeq);
+    public abstract void setExecuteInSequence(boolean inSeq);
 }
\ No newline at end of file


[12/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCheckOnHostCommandWrapper and LibvirtOvsCreateTunnelCommandWrapper
  - 4 unit tests added
  - KVM hypervisor plugin with 16.2% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3c8b2172
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3c8b2172
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3c8b2172

Branch: refs/heads/CLOUDSTACK-8301
Commit: 3c8b217262e08053fd59329f7466b65b150a18c2
Parents: 6748a73
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri May 1 19:17:30 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:12 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  89 +--------------
 .../LibvirtCheckOnHostCommandWrapper.java       |  64 +++++++++++
 .../LibvirtOvsCreateTunnelCommandWrapper.java   |  68 +++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   4 +
 .../resource/LibvirtComputingResourceTest.java  | 112 +++++++++++++++++++
 5 files changed, 252 insertions(+), 85 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c8b2172/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 9c1a6b4..6d13ce6 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -85,7 +85,6 @@ import com.ceph.rbd.RbdImage;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.BackupSnapshotAnswer;
 import com.cloud.agent.api.BackupSnapshotCommand;
-import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
@@ -98,8 +97,6 @@ import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
 import com.cloud.agent.api.NetworkUsageAnswer;
 import com.cloud.agent.api.NetworkUsageCommand;
-import com.cloud.agent.api.OvsCreateTunnelAnswer;
-import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
@@ -430,6 +427,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _ovsTunnelPath;
     }
 
+    public KVMHAMonitor getMonitor() {
+        return _monitor;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1309,10 +1310,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
             } else if (cmd instanceof PvlanSetupCommand) {
                 return execute((PvlanSetupCommand)cmd);
-            } else if (cmd instanceof CheckOnHostCommand) {
-                return execute((CheckOnHostCommand)cmd);
-            } else if (cmd instanceof OvsCreateTunnelCommand) {
-                return execute((OvsCreateTunnelCommand)cmd);
             } else {
                 s_logger.warn("Unsupported command ");
                 return Answer.createUnsupportedCommandAnswer(cmd);
@@ -1398,39 +1395,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private OvsCreateTunnelAnswer execute(final OvsCreateTunnelCommand cmd) {
-        final String bridge = cmd.getNetworkName();
-        try {
-            if (!findOrCreateTunnelNetwork(bridge)) {
-                s_logger.debug("Error during bridge setup");
-                return new OvsCreateTunnelAnswer(cmd, false,
-                        "Cannot create network", bridge);
-            }
-
-            configureTunnelNetwork(cmd.getNetworkId(), cmd.getFrom(),
-                    cmd.getNetworkName());
-            final Script command = new Script(_ovsTunnelPath, _timeout, s_logger);
-            command.add("create_tunnel");
-            command.add("--bridge", bridge);
-            command.add("--remote_ip", cmd.getRemoteIp());
-            command.add("--key", cmd.getKey().toString());
-            command.add("--src_host", cmd.getFrom().toString());
-            command.add("--dst_host", cmd.getTo().toString());
-
-            final String result = command.execute();
-            if (result != null) {
-                return new OvsCreateTunnelAnswer(cmd, true, result, null,
-                        bridge);
-            } else {
-                return new OvsCreateTunnelAnswer(cmd, false, result, bridge);
-            }
-        } catch (final Exception e) {
-            s_logger.debug("Error during tunnel setup");
-            s_logger.warn("Caught execption when creating ovs tunnel", e);
-            return new OvsCreateTunnelAnswer(cmd, false, e.getMessage(), bridge);
-        }
-    }
-
     private CopyVolumeAnswer execute(final CopyVolumeCommand cmd) {
         /**
              This method is only used for copying files from Primary Storage TO Secondary Storage
@@ -1508,26 +1472,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
 
     }
 
-    protected Answer execute(final CheckOnHostCommand cmd) {
-        final ExecutorService executors = Executors.newSingleThreadExecutor();
-        final List<NfsStoragePool> pools = _monitor.getStoragePools();
-        final KVMHAChecker ha = new KVMHAChecker(pools, cmd.getHost().getPrivateNetwork().getIp());
-        final Future<Boolean> future = executors.submit(ha);
-        try {
-            final Boolean result = future.get();
-            if (result) {
-                return new Answer(cmd, false, "Heart is still beating...");
-            } else {
-                return new Answer(cmd);
-            }
-        } catch (final InterruptedException e) {
-            return new Answer(cmd, false, "can't get status of host:");
-        } catch (final ExecutionException e) {
-            return new Answer(cmd, false, "can't get status of host:");
-        }
-
-    }
-
     protected Storage.StorageResourceType getStorageResourceType() {
         return Storage.StorageResourceType.STORAGE_POOL;
     }
@@ -3795,28 +3739,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return parser.getEmulator();
     }
 
-    private String getGuestType(final Connect conn, final String vmName) {
-        final LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
-        Domain dm = null;
-        try {
-            dm = conn.domainLookupByName(vmName);
-            final String xmlDesc = dm.getXMLDesc(0);
-            parser.parseDomainXML(xmlDesc);
-            return parser.getDescription();
-        } catch (final LibvirtException e) {
-            s_logger.trace("Ignoring libvirt error.", e);
-            return null;
-        } finally {
-            try {
-                if (dm != null) {
-                    dm.free();
-                }
-            } catch (final LibvirtException l) {
-                s_logger.trace("Ignoring libvirt error.", l);
-            }
-        }
-    }
-
     boolean isGuestPVEnabled(final String guestOSName) {
         if (guestOSName == null) {
             return false;
@@ -4304,13 +4226,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     @Override
     public void setName(final String name) {
         // TODO Auto-generated method stub
-
     }
 
     @Override
     public void setConfigParams(final Map<String, Object> params) {
         // TODO Auto-generated method stub
-
     }
 
     @Override
@@ -4328,7 +4248,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     @Override
     public void setRunLevel(final int level) {
         // TODO Auto-generated method stub
-
     }
 
     public HypervisorType getHypervisorType(){

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c8b2172/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckOnHostCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckOnHostCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckOnHostCommandWrapper.java
new file mode 100644
index 0000000..5e56023
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckOnHostCommandWrapper.java
@@ -0,0 +1,64 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CheckOnHostCommand;
+import com.cloud.agent.api.to.HostTO;
+import com.cloud.agent.api.to.NetworkTO;
+import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
+import com.cloud.hypervisor.kvm.resource.KVMHAChecker;
+import com.cloud.hypervisor.kvm.resource.KVMHAMonitor;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtCheckOnHostCommandWrapper extends CommandWrapper<CheckOnHostCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CheckOnHostCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final ExecutorService executors = Executors.newSingleThreadExecutor();
+        final KVMHAMonitor monitor = libvirtComputingResource.getMonitor();
+
+        final List<NfsStoragePool> pools = monitor.getStoragePools();
+        HostTO host = command.getHost();
+        NetworkTO privateNetwork = host.getPrivateNetwork();
+        final KVMHAChecker ha = new KVMHAChecker(pools, privateNetwork.getIp());
+
+        final Future<Boolean> future = executors.submit(ha);
+        try {
+            final Boolean result = future.get();
+            if (result) {
+                return new Answer(command, false, "Heart is still beating...");
+            } else {
+                return new Answer(command);
+            }
+        } catch (final InterruptedException e) {
+            return new Answer(command, false, "can't get status of host:");
+        } catch (final ExecutionException e) {
+            return new Answer(command, false, "can't get status of host:");
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c8b2172/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsCreateTunnelCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsCreateTunnelCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsCreateTunnelCommandWrapper.java
new file mode 100644
index 0000000..3a62057
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsCreateTunnelCommandWrapper.java
@@ -0,0 +1,68 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsCreateTunnelAnswer;
+import com.cloud.agent.api.OvsCreateTunnelCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtOvsCreateTunnelCommandWrapper extends CommandWrapper<OvsCreateTunnelCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsCreateTunnelCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsCreateTunnelCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String bridge = command.getNetworkName();
+        try {
+            if (!libvirtComputingResource.findOrCreateTunnelNetwork(bridge)) {
+                s_logger.debug("Error during bridge setup");
+                return new OvsCreateTunnelAnswer(command, false,
+                        "Cannot create network", bridge);
+            }
+
+            libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                    command.getNetworkName());
+
+            final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger);
+            scriptCommand.add("create_tunnel");
+            scriptCommand.add("--bridge", bridge);
+            scriptCommand.add("--remote_ip", command.getRemoteIp());
+            scriptCommand.add("--key", command.getKey().toString());
+            scriptCommand.add("--src_host", command.getFrom().toString());
+            scriptCommand.add("--dst_host", command.getTo().toString());
+
+            final String result = scriptCommand.execute();
+            if (result != null) {
+                return new OvsCreateTunnelAnswer(command, true, result, null,
+                        bridge);
+            } else {
+                return new OvsCreateTunnelAnswer(command, false, result, bridge);
+            }
+        } catch (final Exception e) {
+            s_logger.warn("Caught execption when creating ovs tunnel", e);
+            return new OvsCreateTunnelAnswer(command, false, e.getMessage(), bridge);
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c8b2172/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index ca7a7d2..af2f544 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -25,6 +25,7 @@ import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkCommand;
+import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
@@ -41,6 +42,7 @@ import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
+import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.OvsFetchInterfaceCommand;
@@ -120,6 +122,8 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CheckSshCommand.class, new LibvirtCheckSshCommandWrapper());
         linbvirtCommands.put(CheckNetworkCommand.class, new LibvirtCheckNetworkCommandWrapper());
         linbvirtCommands.put(OvsDestroyTunnelCommand.class, new LibvirtOvsDestroyTunnelCommandWrapper());
+        linbvirtCommands.put(CheckOnHostCommand.class, new LibvirtCheckOnHostCommandWrapper());
+        linbvirtCommands.put(OvsCreateTunnelCommand.class, new LibvirtOvsCreateTunnelCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3c8b2172/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 1551f98..f01ad7a 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -68,6 +68,7 @@ import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckNetworkCommand;
+import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.CreateStoragePoolCommand;
@@ -83,6 +84,7 @@ import com.cloud.agent.api.ModifySshKeysCommand;
 import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
 import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
+import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
 import com.cloud.agent.api.OvsFetchInterfaceCommand;
@@ -2542,4 +2544,114 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(command.getBridgeName());
     }
+
+    @Test
+    public void testCheckOnHostCommand() {
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.Host.class);;
+
+        final CheckOnHostCommand command = new CheckOnHostCommand(host);
+
+        final KVMHAMonitor monitor = Mockito.mock(KVMHAMonitor.class);
+
+        when(libvirtComputingResource.getMonitor()).thenReturn(monitor);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getMonitor();
+    }
+
+    @Test
+    public void testOvsCreateTunnelCommand() {
+        final String remoteIp = "172.16.16.16";
+        final Integer key = 1;
+        final Long from = 1l;
+        final Long to = 2l;
+        final long networkId = 1l;
+        final String fromIp = "172.15.15.15";
+        final String networkName = "eth";
+        final String networkUuid = "8edb1156-a851-4914-afc6-468ee52ac861";
+
+        final OvsCreateTunnelCommand command = new OvsCreateTunnelCommand(remoteIp, key, from, to, networkId, fromIp, networkName, networkUuid);
+
+        final String bridge = command.getNetworkName();
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(true);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge);
+        verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName());
+    }
+
+    @Test
+    public void testOvsCreateTunnelCommandFailure1() {
+        final String remoteIp = "172.16.16.16";
+        final Integer key = 1;
+        final Long from = 1l;
+        final Long to = 2l;
+        final long networkId = 1l;
+        final String fromIp = "172.15.15.15";
+        final String networkName = "eth";
+        final String networkUuid = "8edb1156-a851-4914-afc6-468ee52ac861";
+
+        final OvsCreateTunnelCommand command = new OvsCreateTunnelCommand(remoteIp, key, from, to, networkId, fromIp, networkName, networkUuid);
+
+        final String bridge = command.getNetworkName();
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(false);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge);
+        verify(libvirtComputingResource, times(0)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testOvsCreateTunnelCommandFailure2() {
+        final String remoteIp = "172.16.16.16";
+        final Integer key = 1;
+        final Long from = 1l;
+        final Long to = 2l;
+        final long networkId = 1l;
+        final String fromIp = "172.15.15.15";
+        final String networkName = "eth";
+        final String networkUuid = "8edb1156-a851-4914-afc6-468ee52ac861";
+
+        final OvsCreateTunnelCommand command = new OvsCreateTunnelCommand(remoteIp, key, from, to, networkId, fromIp, networkName, networkUuid);
+
+        final String bridge = command.getNetworkName();
+
+        when(libvirtComputingResource.findOrCreateTunnelNetwork(bridge)).thenReturn(true);
+        when(libvirtComputingResource.configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName())).thenThrow(Exception.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).findOrCreateTunnelNetwork(bridge);
+        verify(libvirtComputingResource, times(1)).configureTunnelNetwork(command.getNetworkId(), command.getFrom(),
+                command.getNetworkName());
+    }
 }
\ No newline at end of file


[32/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Fixing license header in a file added during the LibVirt refactor
  - New class is MigrateKVMAsync


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/c7d2e444
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/c7d2e444
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/c7d2e444

Branch: refs/heads/CLOUDSTACK-8301
Commit: c7d2e444d2981464dd115d1030371cde2fdaeb68
Parents: 45c0fa2
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 13 11:56:43 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 13 11:56:43 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/MigrateKVMAsync.java           | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/c7d2e444/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/MigrateKVMAsync.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/MigrateKVMAsync.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/MigrateKVMAsync.java
index fdec032..2df6c65 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/MigrateKVMAsync.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/MigrateKVMAsync.java
@@ -1,3 +1,21 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
 package com.cloud.hypervisor.kvm.resource;
 
 import java.util.concurrent.Callable;
@@ -35,4 +53,4 @@ public class MigrateKVMAsync implements Callable<Domain> {
             return dm.migrate(dconn, 1 << 0|1 << 11, dxml, vmName, "tcp:" + destIp, libvirtComputingResource.getMigrateSpeed());
         }
     }
-}
\ No newline at end of file
+}


[30/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8467: set version to unknown instead of null


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/60b6dc13
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/60b6dc13
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/60b6dc13

Branch: refs/heads/CLOUDSTACK-8301
Commit: 60b6dc1368620cb9c08bdee26b410b5409e05949
Parents: b8e82a9
Author: Abhinandan Prateek <ab...@shapeblue.com>
Authored: Wed May 13 12:28:50 2015 +0530
Committer: Abhinandan Prateek <ab...@shapeblue.com>
Committed: Wed May 13 12:28:50 2015 +0530

----------------------------------------------------------------------
 usage/src/com/cloud/usage/UsageManagerImpl.java | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/60b6dc13/usage/src/com/cloud/usage/UsageManagerImpl.java
----------------------------------------------------------------------
diff --git a/usage/src/com/cloud/usage/UsageManagerImpl.java b/usage/src/com/cloud/usage/UsageManagerImpl.java
index 5453be9..c1e26b3 100644
--- a/usage/src/com/cloud/usage/UsageManagerImpl.java
+++ b/usage/src/com/cloud/usage/UsageManagerImpl.java
@@ -182,10 +182,7 @@ public class UsageManagerImpl extends ManagerBase implements UsageManager, Runna
 
         final Class<?> c = UsageServer.class;
         _version = c.getPackage().getImplementationVersion();
-        if (_version == null) {
-            // TODO
-            // throw new CloudRuntimeException("Unable to find the implementation version of this usage server");
-        }
+        if (_version == null) _version="unknown";
 
         if (s_logger.isInfoEnabled()) {
             s_logger.info("Implementation Version is " + _version);


[25/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCopyVolumeCommandWrapper

Refactoring the LibvirtUtilitiesHelper
  - Changing method name

Did not add any test to this commit due to the refactor mentioned abot.
Will proceed and add the tests

i# Please enter the commit message for your changes. Lines starting


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/0b1b2b6d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0b1b2b6d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0b1b2b6d

Branch: refs/heads/CLOUDSTACK-8301
Commit: 0b1b2b6d925ec919e5b467ce5da1fc91f60673cb
Parents: 885b9e4
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 07:38:51 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:15 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  63 +------
 .../wrapper/LibvirtAttachIsoCommandWrapper.java |   2 +-
 .../LibvirtAttachVolumeCommandWrapper.java      |   2 +-
 .../LibvirtBackupSnapshotCommandWrapper.java    |   2 +-
 ...ibvirtCheckVirtualMachineCommandWrapper.java |   2 +-
 .../LibvirtCopyVolumeCommandWrapper.java        |  99 ++++++++++
 ...ivateTemplateFromSnapshotCommandWrapper.java |   4 +-
 .../LibvirtGetVmDiskStatsCommandWrapper.java    |   2 +-
 .../LibvirtGetVmStatsCommandWrapper.java        |   2 +-
 .../LibvirtGetVncPortCommandWrapper.java        |   2 +-
 .../LibvirtManageSnapshotCommandWrapper.java    |   2 +-
 .../wrapper/LibvirtMigrateCommandWrapper.java   |   2 +-
 ...bvirtNetworkRulesSystemVmCommandWrapper.java |   2 +-
 ...NetworkRulesVmSecondaryIpCommandWrapper.java |   2 +-
 .../wrapper/LibvirtPlugNicCommandWrapper.java   |   2 +-
 ...ibvirtPrepareForMigrationCommandWrapper.java |   2 +-
 .../wrapper/LibvirtRebootCommandWrapper.java    |   2 +-
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 ...LibvirtSecurityGroupRulesCommandWrapper.java |   2 +-
 .../wrapper/LibvirtStopCommandWrapper.java      |   2 +-
 .../wrapper/LibvirtUnPlugNicCommandWrapper.java |   2 +-
 .../wrapper/LibvirtUtilitiesHelper.java         |   2 +-
 .../resource/LibvirtComputingResourceTest.java  | 184 +++++++++----------
 23 files changed, 215 insertions(+), 173 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index a9410fb..8b74b1c 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -81,8 +81,6 @@ import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.IpAssocVpcCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
-import com.cloud.agent.api.storage.CopyVolumeAnswer;
-import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.ResizeVolumeAnswer;
 import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
@@ -119,8 +117,8 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.SerialDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.TermPolicy;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VideoDef;
 import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VirtioSerialDef;
-import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper;
+import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtUtilitiesHelper;
 import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
@@ -335,7 +333,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new ExecutionResult(true, null);
     }
 
-    public LibvirtUtilitiesHelper getLibvirtConnectionWrapper() {
+    public LibvirtUtilitiesHelper getLibvirtUtilitiesHelper() {
         return libvirtUtilitiesHelper;
     }
 
@@ -1250,8 +1248,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((StartCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
-            } else if (cmd instanceof CopyVolumeCommand) {
-                return execute((CopyVolumeCommand)cmd);
             } else if (cmd instanceof ResizeVolumeCommand) {
                 return execute((ResizeVolumeCommand)cmd);
             } else if (cmd instanceof StorageSubSystemCommand) {
@@ -1343,61 +1339,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private CopyVolumeAnswer execute(final CopyVolumeCommand cmd) {
-        /**
-             This method is only used for copying files from Primary Storage TO Secondary Storage
-
-             It COULD also do it the other way around, but the code in the ManagementServerImpl shows
-             that it always sets copyToSecondary to true
-
-         */
-        final boolean copyToSecondary = cmd.toSecondaryStorage();
-        String volumePath = cmd.getVolumePath();
-        final StorageFilerTO pool = cmd.getPool();
-        final String secondaryStorageUrl = cmd.getSecondaryStorageURL();
-        KVMStoragePool secondaryStoragePool = null;
-        KVMStoragePool primaryPool = null;
-        try {
-            try {
-                primaryPool = _storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
-            } catch (final CloudRuntimeException e) {
-                if (e.getMessage().contains("not found")) {
-                    primaryPool =
-                            _storagePoolMgr.createStoragePool(cmd.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(), cmd.getPool().getPath(),
-                                    cmd.getPool().getUserInfo(), cmd.getPool().getType());
-                } else {
-                    return new CopyVolumeAnswer(cmd, false, e.getMessage(), null, null);
-                }
-            }
-
-            final String volumeName = UUID.randomUUID().toString();
-
-            if (copyToSecondary) {
-                final String destVolumeName = volumeName + ".qcow2";
-                final KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(cmd.getVolumePath());
-                final String volumeDestPath = "/volumes/" + cmd.getVolumeId() + File.separator;
-                secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl);
-                secondaryStoragePool.createFolder(volumeDestPath);
-                _storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
-                secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + volumeDestPath);
-                _storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, secondaryStoragePool, 0);
-                return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
-            } else {
-                volumePath = "/volumes/" + cmd.getVolumeId() + File.separator;
-                secondaryStoragePool = _storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + volumePath);
-                final KVMPhysicalDisk volume = secondaryStoragePool.getPhysicalDisk(cmd.getVolumePath() + ".qcow2");
-                _storagePoolMgr.copyPhysicalDisk(volume, volumeName, primaryPool, 0);
-                return new CopyVolumeAnswer(cmd, true, null, null, volumeName);
-            }
-        } catch (final CloudRuntimeException e) {
-            return new CopyVolumeAnswer(cmd, false, e.toString(), null, null);
-        } finally {
-            if (secondaryStoragePool != null) {
-                _storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
-            }
-        }
-    }
-
     protected Storage.StorageResourceType getStorageResourceType() {
         return Storage.StorageResourceType.STORAGE_POOL;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
index 9c12845..a85ea54 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachIsoCommandWrapper.java
@@ -35,7 +35,7 @@ public final class LibvirtAttachIsoCommandWrapper extends CommandWrapper<AttachI
     @Override
     public Answer execute(final AttachIsoCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             libvirtComputingResource.attachOrDetachISO(conn, command.getVmName(), command.getIsoPath(), command.isAttach());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
index 038670d..aa0cd84 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtAttachVolumeCommandWrapper.java
@@ -36,7 +36,7 @@ public final class LibvirtAttachVolumeCommandWrapper extends CommandWrapper<Atta
     @Override
     public Answer execute(final AttachVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
index 89fdea0..438f97c 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtBackupSnapshotCommandWrapper.java
@@ -68,7 +68,7 @@ public final class LibvirtBackupSnapshotCommandWrapper extends CommandWrapper<Ba
         final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
 
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
 
             secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
index d59ea5d..45e2e0b 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCheckVirtualMachineCommandWrapper.java
@@ -34,7 +34,7 @@ public final class LibvirtCheckVirtualMachineCommandWrapper extends CommandWrapp
     @Override
     public Answer execute(final CheckVirtualMachineCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             final PowerState state = libvirtComputingResource.getVmState(conn, command.getVmName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
new file mode 100644
index 0000000..d14b045
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCopyVolumeCommandWrapper.java
@@ -0,0 +1,99 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.File;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.CopyVolumeAnswer;
+import com.cloud.agent.api.storage.CopyVolumeCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtCopyVolumeCommandWrapper extends CommandWrapper<CopyVolumeCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CopyVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        /**
+        This method is only used for copying files from Primary Storage TO Secondary Storage
+
+        It COULD also do it the other way around, but the code in the ManagementServerImpl shows
+        that it always sets copyToSecondary to true
+
+         */
+        final boolean copyToSecondary = command.toSecondaryStorage();
+        String volumePath = command.getVolumePath();
+        final StorageFilerTO pool = command.getPool();
+        final String secondaryStorageUrl = command.getSecondaryStorageURL();
+        KVMStoragePool secondaryStoragePool = null;
+        KVMStoragePool primaryPool = null;
+
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+        try {
+            try {
+                primaryPool = storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
+            } catch (final CloudRuntimeException e) {
+                if (e.getMessage().contains("not found")) {
+                    primaryPool =
+                            storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(),
+                                    command.getPool().getUserInfo(), command.getPool().getType());
+                } else {
+                    return new CopyVolumeAnswer(command, false, e.getMessage(), null, null);
+                }
+            }
+
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+            final String volumeName = libvirtUtilitiesHelper.generatereUUIDName();
+
+            if (copyToSecondary) {
+                final String destVolumeName = volumeName + ".qcow2";
+                final KVMPhysicalDisk volume = primaryPool.getPhysicalDisk(command.getVolumePath());
+                final String volumeDestPath = "/volumes/" + command.getVolumeId() + File.separator;
+
+                secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl);
+                secondaryStoragePool.createFolder(volumeDestPath);
+                storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
+                secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + volumeDestPath);
+                storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, secondaryStoragePool, 0);
+
+                return new CopyVolumeAnswer(command, true, null, null, volumeName);
+            } else {
+                volumePath = "/volumes/" + command.getVolumeId() + File.separator;
+                secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStorageUrl + volumePath);
+
+                final KVMPhysicalDisk volume = secondaryStoragePool.getPhysicalDisk(command.getVolumePath() + ".qcow2");
+                storagePoolMgr.copyPhysicalDisk(volume, volumeName, primaryPool, 0);
+
+                return new CopyVolumeAnswer(command, true, null, null, volumeName);
+            }
+        } catch (final CloudRuntimeException e) {
+            return new CopyVolumeAnswer(command, false, e.toString(), null, null);
+        } finally {
+            if (secondaryStoragePool != null) {
+                storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
index 0778586..35c14f8 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
@@ -48,11 +48,11 @@ public final class LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper extend
 
     @Override
     public Answer execute(final CreatePrivateTemplateFromSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
         final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
         final String templateInstallFolder = "template/tmpl/" + templateFolder;
-        final String tmplName = libvirtUtilitiesHelper.buildTemplateUUIDName();
+        final String tmplName = libvirtUtilitiesHelper.generatereUUIDName();
         final String tmplFileName = tmplName + ".qcow2";
 
         KVMStoragePool secondaryPool = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
index 7c76833..4a8ee49 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmDiskStatsCommandWrapper.java
@@ -40,7 +40,7 @@ public final class LibvirtGetVmDiskStatsCommandWrapper extends CommandWrapper<Ge
     @Override
     public Answer execute(final GetVmDiskStatsCommand command, final LibvirtComputingResource libvirtComputingResource) {
         final List<String> vmNames = command.getVmNames();
-        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
         try {
             final HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsNameMap = new HashMap<String, List<VmDiskStatsEntry>>();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
index f1ddca1..2e6f0a7 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVmStatsCommandWrapper.java
@@ -44,7 +44,7 @@ public final class LibvirtGetVmStatsCommandWrapper extends CommandWrapper<GetVmS
             final HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
             for (final String vmName : vmNames) {
 
-                final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+                final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
                 final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
                 final VmStatsEntry statEntry = libvirtComputingResource.getVmStat(conn, vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
index d7c1820..abd9bf9 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetVncPortCommandWrapper.java
@@ -33,7 +33,7 @@ public final class LibvirtGetVncPortCommandWrapper extends CommandWrapper<GetVnc
     @Override
     public Answer execute(final GetVncPortCommand command, final LibvirtComputingResource libvirtComputingResource) {
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getName());
             final Integer vncPort = libvirtComputingResource.getVncPort(conn, command.getName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
index 154e67b..966a431 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
@@ -53,7 +53,7 @@ public final class LibvirtManageSnapshotCommandWrapper extends CommandWrapper<Ma
         final String snapshotPath = command.getSnapshotPath();
         final String vmName = command.getVmName();
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             DomainState state = null;
             Domain vm = null;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
index e30e976..4b30cd9 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtMigrateCommandWrapper.java
@@ -63,7 +63,7 @@ public final class LibvirtMigrateCommandWrapper extends CommandWrapper<MigrateCo
         Connect conn = null;
         String xmlDesc = null;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             ifaces = libvirtComputingResource.getInterfaces(conn, vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
index a328c37..0a87432 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesSystemVmCommandWrapper.java
@@ -36,7 +36,7 @@ public final class LibvirtNetworkRulesSystemVmCommandWrapper extends CommandWrap
     public Answer execute(final NetworkRulesSystemVmCommand command, final LibvirtComputingResource libvirtComputingResource) {
         boolean success = false;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             success = libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
index 19eb3d3..f955b89 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
@@ -36,7 +36,7 @@ public final class LibvirtNetworkRulesVmSecondaryIpCommandWrapper extends Comman
     public Answer execute(final NetworkRulesVmSecondaryIpCommand command, final LibvirtComputingResource libvirtComputingResource) {
         boolean result = false;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             result = libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
index 692f79e..6b6d54f 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
@@ -46,7 +46,7 @@ public final class LibvirtPlugNicCommandWrapper extends CommandWrapper<PlugNicCo
         final String vmName = command.getVmName();
         Domain vm = null;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             vm = libvirtComputingResource.getDomain(conn, vmName);
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
index b9bf770..66aabac 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrepareForMigrationCommandWrapper.java
@@ -54,7 +54,7 @@ public final class LibvirtPrepareForMigrationCommandWrapper extends CommandWrapp
 
         final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vm.getName());
             for (final NicTO nic : nics) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
index 414fcd6..518c367 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRebootCommandWrapper.java
@@ -35,7 +35,7 @@ public final class LibvirtRebootCommandWrapper extends CommandWrapper<RebootComm
 
     @Override
     public Answer execute(final RebootCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
         try {
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 7e73264..1ee14a1 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -69,6 +69,7 @@ import com.cloud.agent.api.UpgradeSnapshotCommand;
 import com.cloud.agent.api.check.CheckSshCommand;
 import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
+import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
 import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
@@ -144,6 +145,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(ManageSnapshotCommand.class, new LibvirtManageSnapshotCommandWrapper());
         linbvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
         linbvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
+        linbvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
index c661a16..ef43182 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtSecurityGroupRulesCommandWrapper.java
@@ -41,7 +41,7 @@ public final class LibvirtSecurityGroupRulesCommandWrapper extends CommandWrappe
         String vif = null;
         String brname = null;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
             final List<InterfaceDef> nics = libvirtComputingResource.getInterfaces(conn, command.getVmName());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
index 0d5f892..59a44fc 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStopCommandWrapper.java
@@ -44,7 +44,7 @@ public final class LibvirtStopCommandWrapper extends CommandWrapper<StopCommand,
     public Answer execute(final StopCommand command, final LibvirtComputingResource libvirtComputingResource) {
         final String vmName = command.getVmName();
 
-        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
         if (command.checkBeforeCleanup()) {
             try {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
index b3016fa..5570793 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnPlugNicCommandWrapper.java
@@ -45,7 +45,7 @@ public final class LibvirtUnPlugNicCommandWrapper extends CommandWrapper<UnPlugN
         final String vmName = command.getVmName();
         Domain vm = null;
         try {
-            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtConnectionWrapper();
+            final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
 
             final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
             vm = libvirtComputingResource.getDomain(conn, vmName);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0b1b2b6d/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
index 5930bf0..c0f1cb5 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -62,7 +62,7 @@ public class LibvirtUtilitiesHelper {
         return qcow2Processor;
     }
 
-    public String buildTemplateUUIDName() {
+    public String generatereUUIDName() {
         return UUID.randomUUID().toString();
     }
 }
\ No newline at end of file


[10/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtPrimaryStorageDownloadCommandWrapper
  - 4 unit tests added
  - KVM hypervisor plugin with 13.3% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/8268d353
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/8268d353
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/8268d353

Branch: refs/heads/CLOUDSTACK-8301
Commit: 8268d353a2a5ffb032017687f7df82c4a6871812
Parents: 4472cad
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Apr 30 14:53:17 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:11 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  55 +------
 ...irtPrimaryStorageDownloadCommandWrapper.java |  88 +++++++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../resource/LibvirtComputingResourceTest.java  | 157 ++++++++++++++++++-
 4 files changed, 247 insertions(+), 55 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8268d353/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 4abc048..8e9cbc1 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -146,8 +146,6 @@ import com.cloud.agent.api.routing.SetSourceNatCommand;
 import com.cloud.agent.api.storage.CopyVolumeAnswer;
 import com.cloud.agent.api.storage.CopyVolumeCommand;
 import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
-import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
-import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
 import com.cloud.agent.api.storage.ResizeVolumeAnswer;
 import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
@@ -1298,9 +1296,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof PrimaryStorageDownloadCommand) {
-                return execute((PrimaryStorageDownloadCommand)cmd);
-            } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
+            if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) {
                 return execute((CreatePrivateTemplateFromVolumeCommand)cmd);
             } else if (cmd instanceof GetStorageStatsCommand) {
                 return execute((GetStorageStatsCommand)cmd);
@@ -2704,55 +2700,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected PrimaryStorageDownloadAnswer execute(final PrimaryStorageDownloadCommand cmd) {
-        final String tmplturl = cmd.getUrl();
-        final int index = tmplturl.lastIndexOf("/");
-        final 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();
-                final List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
-                if (disks == null || disks.isEmpty()) {
-                    return new PrimaryStorageDownloadAnswer("Failed to get volumes from pool: " + secondaryPool.getUuid());
-                }
-                for (final 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 */
-            final KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd.getPool().getType(), cmd.getPoolUuid());
-
-            final KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0);
-
-            return new PrimaryStorageDownloadAnswer(primaryVol.getName(), primaryVol.getSize());
-        } catch (final CloudRuntimeException e) {
-            return new PrimaryStorageDownloadAnswer(e.toString());
-        } finally {
-            if (secondaryPool != null) {
-                _storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid());
-            }
-        }
-    }
-
     protected Answer execute(final CreateStoragePoolCommand cmd) {
         return new Answer(cmd, true, "success");
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8268d353/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrimaryStorageDownloadCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrimaryStorageDownloadCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrimaryStorageDownloadCommandWrapper.java
new file mode 100644
index 0000000..391ab27
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPrimaryStorageDownloadCommandWrapper.java
@@ -0,0 +1,88 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.List;
+import java.util.UUID;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer;
+import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public final class LibvirtPrimaryStorageDownloadCommandWrapper extends CommandWrapper<PrimaryStorageDownloadCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final PrimaryStorageDownloadCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String tmplturl = command.getUrl();
+        final int index = tmplturl.lastIndexOf("/");
+        final 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;
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+        try {
+            secondaryPool = storagePoolMgr.getStoragePoolByURI(mountpoint);
+
+            /* Get template vol */
+            if (tmpltname == null) {
+                secondaryPool.refresh();
+                final List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
+                if (disks == null || disks.isEmpty()) {
+                    return new PrimaryStorageDownloadAnswer("Failed to get volumes from pool: " + secondaryPool.getUuid());
+                }
+                for (final 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 */
+            final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid());
+
+            final KVMPhysicalDisk primaryVol = storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0);
+
+            return new PrimaryStorageDownloadAnswer(primaryVol.getName(), primaryVol.getSize());
+        } catch (final CloudRuntimeException e) {
+            return new PrimaryStorageDownloadAnswer(e.toString());
+        } finally {
+            if (secondaryPool != null) {
+                storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid());
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8268d353/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index eb8d569..7c9b443 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -43,6 +43,7 @@ import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
+import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.resource.RequestWrapper;
@@ -86,6 +87,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(MaintainCommand.class, new LibvirtMaintainCommandWrapper());
         linbvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
         linbvirtCommands.put(DestroyCommand.class, new LibvirtDestroyCommandWrapper());
+        linbvirtCommands.put(PrimaryStorageDownloadCommand.class, new LibvirtPrimaryStorageDownloadCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/8268d353/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 0865fb5..946d871 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -86,6 +86,7 @@ import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
 import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
 import com.cloud.agent.api.storage.CreateCommand;
 import com.cloud.agent.api.storage.DestroyCommand;
+import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
 import com.cloud.agent.api.to.DiskTO;
 import com.cloud.agent.api.to.NicTO;
 import com.cloud.agent.api.to.StorageFilerTO;
@@ -101,6 +102,7 @@ import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.network.Networks.TrafficType;
+import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.Volume;
@@ -1378,4 +1380,157 @@ public class LibvirtComputingResourceTest {
         verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
         verify(poolManager, times(1)).getStoragePool(vol.getPoolType(), vol.getPoolUuid());
     }
-}
\ No newline at end of file
+
+    @Test(expected = NullPointerException.class)
+    public void testPrimaryStorageDownloadCommandNOTemplateDisk() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+
+        final List<KVMPhysicalDisk> disks = new ArrayList<KVMPhysicalDisk>();
+
+        final String name = "Test";
+        final String url = "http://template/";
+        final ImageFormat format = ImageFormat.QCOW2;
+        final long accountId = 1l;
+        final int wait = 0;
+        final PrimaryStorageDownloadCommand command = new PrimaryStorageDownloadCommand(name, url, format, accountId, pool, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk tmplVol = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMPhysicalDisk primaryVol = Mockito.mock(KVMPhysicalDisk.class);
+
+        final KVMPhysicalDisk disk = new KVMPhysicalDisk("/path", "disk.qcow2", primaryPool);
+        disks.add(disk);
+
+        final int index = url.lastIndexOf("/");
+        final String mountpoint = url.substring(0, index);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
+        when(secondaryPool.listPhysicalDisks()).thenReturn(disks);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
+        when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testPrimaryStorageDownloadCommandNOTemplateNODisk() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+
+        final List<KVMPhysicalDisk> disks = new ArrayList<KVMPhysicalDisk>();
+
+        final String name = "Test";
+        final String url = "http://template/";
+        final ImageFormat format = ImageFormat.QCOW2;
+        final long accountId = 1l;
+        final int wait = 0;
+        final PrimaryStorageDownloadCommand command = new PrimaryStorageDownloadCommand(name, url, format, accountId, pool, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk tmplVol = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMPhysicalDisk primaryVol = Mockito.mock(KVMPhysicalDisk.class);
+
+        final int index = url.lastIndexOf("/");
+        final String mountpoint = url.substring(0, index);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
+        when(secondaryPool.listPhysicalDisks()).thenReturn(disks);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
+        when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test
+    public void testPrimaryStorageDownloadCommandNOTemplateNOQcow2() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+
+        final List<KVMPhysicalDisk> disks = new ArrayList<KVMPhysicalDisk>();
+        final List<KVMPhysicalDisk> spiedDisks = Mockito.spy(disks);
+
+        final String name = "Test";
+        final String url = "http://template/";
+        final ImageFormat format = ImageFormat.QCOW2;
+        final long accountId = 1l;
+        final int wait = 0;
+        final PrimaryStorageDownloadCommand command = new PrimaryStorageDownloadCommand(name, url, format, accountId, pool, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk tmplVol = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMPhysicalDisk primaryVol = Mockito.mock(KVMPhysicalDisk.class);
+
+        final int index = url.lastIndexOf("/");
+        final String mountpoint = url.substring(0, index);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
+        when(secondaryPool.listPhysicalDisks()).thenReturn(spiedDisks);
+        when(spiedDisks.isEmpty()).thenReturn(false);
+
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
+        when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+    }
+
+    @Test(expected = NullPointerException.class)
+    public void testPrimaryStorageDownloadCommandTemplateNoDisk() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+
+        final String name = "Test";
+        final String url = "http://template/template.qcow2";
+        final ImageFormat format = ImageFormat.VHD;
+        final long accountId = 1l;
+        final int wait = 0;
+        final PrimaryStorageDownloadCommand command = new PrimaryStorageDownloadCommand(name, url, format, accountId, pool, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk tmplVol = Mockito.mock(KVMPhysicalDisk.class);
+        final KVMPhysicalDisk primaryVol = Mockito.mock(KVMPhysicalDisk.class);
+
+        final int index = url.lastIndexOf("/");
+        final String mountpoint = url.substring(0, index);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePoolByURI(mountpoint)).thenReturn(secondaryPool);
+        when(secondaryPool.getPhysicalDisk("template.qcow2")).thenReturn(tmplVol);
+        when(storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPoolUuid())).thenReturn(primaryPool);
+        when(storagePoolMgr.copyPhysicalDisk(tmplVol, UUID.randomUUID().toString(), primaryPool, 0)).thenReturn(primaryVol);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePool(command.getPool().getType(), command.getPoolUuid());
+    }
+}


[18/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper
  - 5 unit tests added
  - KVM hypervisor plugin with 19.5% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b3913ca1
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b3913ca1
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b3913ca1

Branch: refs/heads/CLOUDSTACK-8301
Commit: b3913ca1fbd3b400961608a4434cd7619cf1606d
Parents: bcf78d3
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Tue May 5 12:53:10 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:14 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |  67 +---
 .../wrapper/LibvirtConnectionWrapper.java       |  33 +-
 ...ivateTemplateFromSnapshotCommandWrapper.java | 113 ++++++
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../resource/LibvirtComputingResourceTest.java  | 354 +++++++++++++++++++
 5 files changed, 502 insertions(+), 67 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b3913ca1/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 4e8b4cf..977288b 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -64,7 +64,6 @@ import org.libvirt.StorageVol;
 
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.Command;
-import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
@@ -84,7 +83,6 @@ import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.routing.SetSourceNatCommand;
 import com.cloud.agent.api.storage.CopyVolumeAnswer;
 import com.cloud.agent.api.storage.CopyVolumeCommand;
-import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
 import com.cloud.agent.api.storage.ResizeVolumeAnswer;
 import com.cloud.agent.api.storage.ResizeVolumeCommand;
 import com.cloud.agent.api.to.DataStoreTO;
@@ -140,10 +138,6 @@ import com.cloud.storage.StorageLayer;
 import com.cloud.storage.Volume;
 import com.cloud.storage.resource.StorageSubsystemCommandHandler;
 import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase;
-import com.cloud.storage.template.Processor;
-import com.cloud.storage.template.Processor.FormatInfo;
-import com.cloud.storage.template.QCOW2Processor;
-import com.cloud.storage.template.TemplateLocation;
 import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
@@ -1252,9 +1246,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
 
         try {
-            if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
-                return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
-            } else if (cmd instanceof StartCommand) {
+            if (cmd instanceof StartCommand) {
                 return execute((StartCommand)cmd);
             } else if (cmd instanceof NetworkElementCommand) {
                 return _virtRouterResource.executeRequest((NetworkElementCommand)cmd);
@@ -1884,63 +1876,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new ExecutionResult(true, null);
     }
 
-    protected CreatePrivateTemplateAnswer execute(final CreatePrivateTemplateFromSnapshotCommand cmd) {
-        final String templateFolder = cmd.getAccountId() + File.separator + cmd.getNewTemplateId();
-        final String templateInstallFolder = "template/tmpl/" + templateFolder;
-        final String tmplName = UUID.randomUUID().toString();
-        final String tmplFileName = tmplName + ".qcow2";
-        KVMStoragePool secondaryPool = null;
-        KVMStoragePool snapshotPool = null;
-        try {
-            String snapshotPath = cmd.getSnapshotUuid();
-            final int index = snapshotPath.lastIndexOf("/");
-            snapshotPath = snapshotPath.substring(0, index);
-            snapshotPool = _storagePoolMgr.getStoragePoolByURI(cmd.getSecondaryStorageUrl() + snapshotPath);
-            final KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(cmd.getSnapshotName());
-
-            secondaryPool = _storagePoolMgr.getStoragePoolByURI(cmd.getSecondaryStorageUrl());
-
-            final String templatePath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
-
-            _storage.mkdirs(templatePath);
-
-            final String tmplPath = templateInstallFolder + File.separator + tmplFileName;
-            final Script command = new Script(_createTmplPath, _cmdsTimeout, s_logger);
-            command.add("-t", templatePath);
-            command.add("-n", tmplFileName);
-            command.add("-f", snapshot.getPath());
-            command.execute();
-
-            final Map<String, Object> params = new HashMap<String, Object>();
-            params.put(StorageLayer.InstanceConfigKey, _storage);
-            final Processor qcow2Processor = new QCOW2Processor();
-            qcow2Processor.configure("QCOW2 Processor", params);
-            final FormatInfo info = qcow2Processor.process(templatePath, null, tmplName);
-
-            final TemplateLocation loc = new TemplateLocation(_storage, templatePath);
-            loc.create(1, true, tmplName);
-            loc.addFormat(info);
-            loc.save();
-
-            return new CreatePrivateTemplateAnswer(cmd, true, "", tmplPath, info.virtualSize, info.size, tmplName, info.format);
-        } catch (final ConfigurationException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
-        } catch (final InternalErrorException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
-        } catch (final IOException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
-        } catch (final CloudRuntimeException e) {
-            return new CreatePrivateTemplateAnswer(cmd, false, e.getMessage());
-        } finally {
-            if (secondaryPool != null) {
-                _storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid());
-            }
-            if (snapshotPool != null) {
-                _storagePoolMgr.deleteStoragePool(snapshotPool.getType(), snapshotPool.getUuid());
-            }
-        }
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b3913ca1/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
index e6743ac..3a51a37 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConnectionWrapper.java
@@ -16,13 +16,25 @@
 // under the License.
 package com.cloud.hypervisor.kvm.resource.wrapper;
 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.naming.ConfigurationException;
+
 import org.libvirt.Connect;
 import org.libvirt.LibvirtException;
 
 import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
+import com.cloud.storage.StorageLayer;
+import com.cloud.storage.template.Processor;
+import com.cloud.storage.template.QCOW2Processor;
+import com.cloud.storage.template.TemplateLocation;
 
 /**
- * This class is used to wrap the calls to LibvirtConnection and ease the burden of the unit tests.
+ * This class is used to wrap the calls to several static methods. By doing so, we make easier to mock this class
+ * and the methods wrapped here.
+ *
  * Please do not instantiate this class directly, but inject it using the {@code @Inject} annotation.
  */
 public class LibvirtConnectionWrapper {
@@ -34,4 +46,23 @@ public class LibvirtConnectionWrapper {
     public Connect getConnection() throws LibvirtException {
         return LibvirtConnection.getConnection();
     }
+
+    public TemplateLocation buildTemplateLocation(final StorageLayer storage, final String templatePath) {
+        final TemplateLocation location = new TemplateLocation(storage, templatePath);
+        return location;
+    }
+
+    public Processor buildQCOW2Processor(final StorageLayer storage) throws ConfigurationException {
+        final Map<String, Object> params = new HashMap<String, Object>();
+        params.put(StorageLayer.InstanceConfigKey, storage);
+
+        final Processor qcow2Processor = new QCOW2Processor();
+        qcow2Processor.configure("QCOW2 Processor", params);
+
+        return qcow2Processor;
+    }
+
+    public String buildTemplateUUIDName() {
+        return UUID.randomUUID().toString();
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b3913ca1/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
new file mode 100644
index 0000000..20bebad
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.java
@@ -0,0 +1,113 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.io.File;
+import java.io.IOException;
+
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
+import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer;
+import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.StorageLayer;
+import com.cloud.storage.template.Processor;
+import com.cloud.storage.template.Processor.FormatInfo;
+import com.cloud.storage.template.TemplateLocation;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper extends CommandWrapper<CreatePrivateTemplateFromSnapshotCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper.class);
+
+    @Override
+    public Answer execute(final CreatePrivateTemplateFromSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+        final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
+        final String templateInstallFolder = "template/tmpl/" + templateFolder;
+        final String tmplName = libvirtConnectionWrapper.buildTemplateUUIDName();
+        final String tmplFileName = tmplName + ".qcow2";
+
+        KVMStoragePool secondaryPool = null;
+        KVMStoragePool snapshotPool = null;
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+
+        try {
+            String snapshotPath = command.getSnapshotUuid();
+            final int index = snapshotPath.lastIndexOf("/");
+            snapshotPath = snapshotPath.substring(0, index);
+
+            snapshotPool = storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+            secondaryPool = storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl());
+
+            final KVMPhysicalDisk snapshot = snapshotPool.getPhysicalDisk(command.getSnapshotName());
+
+            final String templatePath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
+
+            final StorageLayer storage = libvirtComputingResource.getStorage();
+            storage.mkdirs(templatePath);
+
+            final String tmplPath = templateInstallFolder + File.separator + tmplFileName;
+            final String createTmplPath = libvirtComputingResource.createTmplPath();
+            final int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
+
+            final Script scriptCommand = new Script(createTmplPath, cmdsTimeout, s_logger);
+            scriptCommand.add("-t", templatePath);
+            scriptCommand.add("-n", tmplFileName);
+            scriptCommand.add("-f", snapshot.getPath());
+            scriptCommand.execute();
+
+            final Processor qcow2Processor = libvirtConnectionWrapper.buildQCOW2Processor(storage);
+            final FormatInfo info = qcow2Processor.process(templatePath, null, tmplName);
+            final TemplateLocation loc = libvirtConnectionWrapper.buildTemplateLocation(storage, templatePath);
+
+            loc.create(1, true, tmplName);
+            loc.addFormat(info);
+            loc.save();
+
+            return new CreatePrivateTemplateAnswer(command, true, "", tmplPath, info.virtualSize, info.size, tmplName, info.format);
+        } catch (final ConfigurationException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.getMessage());
+        } catch (final InternalErrorException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.getMessage());
+        } catch (final IOException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.getMessage());
+        } catch (final CloudRuntimeException e) {
+            return new CreatePrivateTemplateAnswer(command, false, e.getMessage());
+        } finally {
+            if (secondaryPool != null) {
+                storagePoolMgr.deleteStoragePool(secondaryPool.getType(), secondaryPool.getUuid());
+            }
+            if (snapshotPool != null) {
+                storagePoolMgr.deleteStoragePool(snapshotPool.getType(), snapshotPool.getUuid());
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b3913ca1/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 2656037..7e73264 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -30,6 +30,7 @@ import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
+import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
@@ -142,6 +143,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(CreatePrivateTemplateFromVolumeCommand.class, new LibvirtCreatePrivateTemplateFromVolumeCommandWrapper());
         linbvirtCommands.put(ManageSnapshotCommand.class, new LibvirtManageSnapshotCommandWrapper());
         linbvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
+        linbvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b3913ca1/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index b0c2734..5f9c50a 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -29,6 +29,7 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayInputStream;
+import java.io.File;
 import java.io.IOException;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
@@ -37,6 +38,7 @@ import java.util.List;
 import java.util.Random;
 import java.util.UUID;
 
+import javax.naming.ConfigurationException;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.xpath.XPathConstants;
@@ -72,6 +74,7 @@ import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
 import com.cloud.agent.api.CleanupNetworkRulesCmd;
+import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
 import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
@@ -139,8 +142,12 @@ import com.cloud.network.Networks.TrafficType;
 import com.cloud.network.PhysicalNetworkSetupInfo;
 import com.cloud.storage.Storage.ImageFormat;
 import com.cloud.storage.Storage.StoragePoolType;
+import com.cloud.storage.StorageLayer;
 import com.cloud.storage.StoragePool;
 import com.cloud.storage.Volume;
+import com.cloud.storage.template.Processor;
+import com.cloud.storage.template.Processor.FormatInfo;
+import com.cloud.storage.template.TemplateLocation;
 import com.cloud.template.VirtualMachineTemplate.BootloaderType;
 import com.cloud.utils.Pair;
 import com.cloud.utils.exception.CloudRuntimeException;
@@ -3536,4 +3543,351 @@ public class LibvirtComputingResourceTest {
             fail(e.getMessage());
         }
     }
+
+    @Test
+    public void testCreatePrivateTemplateFromSnapshotCommand() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
+        final String backedUpSnapshotName = "snap";
+        final String origTemplateInstallPath = "/install/path/";
+        final Long newTemplateId = 2l;
+        final String templateName = "templ";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
+
+        final String templatePath = "/template/path";
+        final String localPath = "/mnt/local";
+        final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+        final StorageLayer storage = Mockito.mock(StorageLayer.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final TemplateLocation location = Mockito.mock(TemplateLocation.class);
+        final Processor qcow2Processor = Mockito.mock(Processor.class);
+        final FormatInfo info = Mockito.mock(FormatInfo.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
+        when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(secondaryPool.getLocalPath()).thenReturn(localPath);
+        when(libvirtComputingResource.getStorage()).thenReturn(storage);
+
+        when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
+        when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
+
+        final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
+        final String templateInstallFolder = "template/tmpl/" + templateFolder;
+        final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+
+        try {
+            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
+        } catch (final ConfigurationException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreatePrivateTemplateFromSnapshotCommandConfigurationException() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
+        final String backedUpSnapshotName = "snap";
+        final String origTemplateInstallPath = "/install/path/";
+        final Long newTemplateId = 2l;
+        final String templateName = "templ";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
+
+        final String templatePath = "/template/path";
+        final String localPath = "/mnt/local";
+        final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+        final StorageLayer storage = Mockito.mock(StorageLayer.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final TemplateLocation location = Mockito.mock(TemplateLocation.class);
+        final Processor qcow2Processor = Mockito.mock(Processor.class);
+        final FormatInfo info = Mockito.mock(FormatInfo.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
+        when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(secondaryPool.getLocalPath()).thenReturn(localPath);
+        when(libvirtComputingResource.getStorage()).thenReturn(storage);
+
+        when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
+        when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
+
+        final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
+        final String templateInstallFolder = "template/tmpl/" + templateFolder;
+        final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+
+        try {
+            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenThrow(ConfigurationException.class);
+            when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
+        } catch (final ConfigurationException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreatePrivateTemplateFromSnapshotCommandInternalErrorException() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
+        final String backedUpSnapshotName = "snap";
+        final String origTemplateInstallPath = "/install/path/";
+        final Long newTemplateId = 2l;
+        final String templateName = "templ";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
+
+        final String templatePath = "/template/path";
+        final String localPath = "/mnt/local";
+        final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+        final StorageLayer storage = Mockito.mock(StorageLayer.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final TemplateLocation location = Mockito.mock(TemplateLocation.class);
+        final Processor qcow2Processor = Mockito.mock(Processor.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
+        when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(secondaryPool.getLocalPath()).thenReturn(localPath);
+        when(libvirtComputingResource.getStorage()).thenReturn(storage);
+
+        when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
+        when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
+
+        final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
+        final String templateInstallFolder = "template/tmpl/" + templateFolder;
+        final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+
+        try {
+            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(qcow2Processor.process(tmplPath, null, tmplName)).thenThrow(InternalErrorException.class);
+        } catch (final ConfigurationException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreatePrivateTemplateFromSnapshotCommandIOException() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
+        final String backedUpSnapshotName = "snap";
+        final String origTemplateInstallPath = "/install/path/";
+        final Long newTemplateId = 2l;
+        final String templateName = "templ";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
+
+        final String templatePath = "/template/path";
+        final String localPath = "/mnt/local";
+        final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
+        final KVMPhysicalDisk snapshot = Mockito.mock(KVMPhysicalDisk.class);
+        final StorageLayer storage = Mockito.mock(StorageLayer.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final TemplateLocation location = Mockito.mock(TemplateLocation.class);
+        final Processor qcow2Processor = Mockito.mock(Processor.class);
+        final FormatInfo info = Mockito.mock(FormatInfo.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
+        when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenReturn(snapshot);
+        when(secondaryPool.getLocalPath()).thenReturn(localPath);
+        when(libvirtComputingResource.getStorage()).thenReturn(storage);
+
+        when(libvirtComputingResource.createTmplPath()).thenReturn(templatePath);
+        when(libvirtComputingResource.getCmdsTimeout()).thenReturn(1);
+
+        final String templateFolder = command.getAccountId() + File.separator + command.getNewTemplateId();
+        final String templateInstallFolder = "template/tmpl/" + templateFolder;
+        final String tmplPath = secondaryPool.getLocalPath() + File.separator + templateInstallFolder;
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtConnectionWrapper.buildTemplateLocation(storage, tmplPath)).thenReturn(location);
+        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+
+        try {
+            when(libvirtConnectionWrapper.buildQCOW2Processor(storage)).thenReturn(qcow2Processor);
+            when(qcow2Processor.process(tmplPath, null, tmplName)).thenReturn(info);
+
+            when(location.create(1, true, tmplName)).thenThrow(IOException.class);
+
+        } catch (final ConfigurationException e) {
+            fail(e.getMessage());
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        } catch (final IOException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testCreatePrivateTemplateFromSnapshotCommandCloudRuntime() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final String secondaryStoragePoolURL = "nfs:/192.168.2.2/storage/secondary";
+        final Long dcId = 1l;
+        final Long accountId = 1l;
+        final Long volumeId = 1l;
+        final String backedUpSnapshotUuid = "/run/9a0afe7c-26a7-4585-bf87-abf82ae106d9/";
+        final String backedUpSnapshotName = "snap";
+        final String origTemplateInstallPath = "/install/path/";
+        final Long newTemplateId = 2l;
+        final String templateName = "templ";
+        final int wait = 0;
+
+        final CreatePrivateTemplateFromSnapshotCommand command = new CreatePrivateTemplateFromSnapshotCommand(pool, secondaryStoragePoolURL, dcId, accountId, volumeId, backedUpSnapshotUuid, backedUpSnapshotName, origTemplateInstallPath, newTemplateId, templateName, wait);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool secondaryPool = Mockito.mock(KVMStoragePool.class);
+        final KVMStoragePool snapshotPool = Mockito.mock(KVMStoragePool.class);
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        final String tmplName = "ce97bbc1-34fe-4259-9202-74bbce2562ab";
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+
+        String snapshotPath = command.getSnapshotUuid();
+        final int index = snapshotPath.lastIndexOf("/");
+        snapshotPath = snapshotPath.substring(0, index);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        when(libvirtConnectionWrapper.buildTemplateUUIDName()).thenReturn(tmplName);
+
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath)).thenReturn(snapshotPool);
+        when(storagePoolMgr.getStoragePoolByURI(command.getSecondaryStorageUrl())).thenReturn(secondaryPool);
+        when(snapshotPool.getPhysicalDisk(command.getSnapshotName())).thenThrow(CloudRuntimeException.class);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl() + snapshotPath);
+        verify(storagePoolMgr, times(1)).getStoragePoolByURI(command.getSecondaryStorageUrl());
+    }
 }
\ No newline at end of file


[48/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8301: Enable configuring local storage use for system VMs at zone level
Made system.vm.use.local.storage a zone level configuration.


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/3f7e31ed
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/3f7e31ed
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/3f7e31ed

Branch: refs/heads/CLOUDSTACK-8301
Commit: 3f7e31ed05edf7f235b13d168ff1a5db16b5e2f9
Parents: dacdf97
Author: Koushik Das <ko...@apache.org>
Authored: Wed May 13 17:35:29 2015 +0530
Committer: Koushik Das <ko...@apache.org>
Committed: Tue May 19 21:32:14 2015 +0530

----------------------------------------------------------------------
 api/src/com/cloud/dc/DataCenter.java            |  4 --
 .../cloud/service/dao/ServiceOfferingDao.java   |  6 +++
 .../service/dao/ServiceOfferingDaoImpl.java     | 38 ++++++++++++++++
 .../lb/ElasticLoadBalancerManagerImpl.java      | 19 ++++----
 .../network/lb/LoadBalanceRuleHandler.java      | 26 ++++++++---
 .../lb/InternalLoadBalancerVMManagerImpl.java   | 36 +++++++++++----
 .../InternalLBVMManagerTest.java                |  8 +++-
 .../InternalLBVMServiceTest.java                | 10 +++-
 server/src/com/cloud/configuration/Config.java  |  1 -
 .../configuration/ConfigurationManagerImpl.java | 48 ++++++--------------
 .../consoleproxy/ConsoleProxyManagerImpl.java   | 48 ++++++++++++--------
 .../deploy/DeploymentPlanningManagerImpl.java   | 36 ++++-----------
 .../VirtualNetworkApplianceManagerImpl.java     | 15 +++---
 .../com/cloud/storage/StorageManagerImpl.java   | 13 +++++-
 .../deployment/RouterDeploymentDefinition.java  | 24 ++++++++--
 .../RouterDeploymentDefinitionBuilder.java      |  4 ++
 .../VpcRouterDeploymentDefinition.java          |  6 +--
 .../element/VirtualRouterElementTest.java       |  6 ++-
 .../RouterDeploymentDefinitionTest.java         | 13 ++++--
 .../RouterDeploymentDefinitionTestBase.java     |  7 +++
 .../VpcRouterDeploymentDefinitionTest.java      | 14 +++---
 .../SecondaryStorageManagerImpl.java            | 48 +++++++++++++-------
 22 files changed, 273 insertions(+), 157 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/api/src/com/cloud/dc/DataCenter.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/dc/DataCenter.java b/api/src/com/cloud/dc/DataCenter.java
index 6cd054e..5b3d3c0 100644
--- a/api/src/com/cloud/dc/DataCenter.java
+++ b/api/src/com/cloud/dc/DataCenter.java
@@ -20,7 +20,6 @@ import com.cloud.org.Grouping;
 import org.apache.cloudstack.acl.InfrastructureEntity;
 import org.apache.cloudstack.api.Identity;
 import org.apache.cloudstack.api.InternalIdentity;
-import org.apache.cloudstack.framework.config.ConfigKey;
 
 import java.util.Map;
 
@@ -28,9 +27,6 @@ import java.util.Map;
  *
  */
 public interface DataCenter extends InfrastructureEntity, Grouping, Identity, InternalIdentity {
-    public static final String SystemVMUseLocalStorageCK = "system.vm.use.local.storage";
-    public static final ConfigKey<Boolean> UseSystemVMLocalStorage = new ConfigKey<Boolean>(Boolean.class, SystemVMUseLocalStorageCK, "Advanced", "false",
-            "Indicates whether to use local storage pools or shared storage pools for system VMs.", true, ConfigKey.Scope.Zone, null);
 
     public enum NetworkType {
         Basic, Advanced,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
index ab81853..98dc317 100644
--- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
+++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDao.java
@@ -20,7 +20,9 @@ import java.util.List;
 import java.util.Map;
 
 import com.cloud.service.ServiceOfferingVO;
+import com.cloud.storage.Storage.ProvisioningType;
 import com.cloud.utils.db.GenericDao;
+import com.cloud.vm.VirtualMachine;
 
 /*
  * Data Access Object for service_offering table
@@ -28,6 +30,10 @@ import com.cloud.utils.db.GenericDao;
 public interface ServiceOfferingDao extends GenericDao<ServiceOfferingVO, Long> {
     ServiceOfferingVO findByName(String name);
 
+    List<ServiceOfferingVO> createSystemServiceOfferings(String name, String uniqueName, int cpuCount, int ramSize, int cpuSpeed,
+            Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, ProvisioningType provisioningType,
+            boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vmType, boolean defaultUse);
+
     ServiceOfferingVO persistSystemServiceOffering(ServiceOfferingVO vo);
 
     List<ServiceOfferingVO> findPublicServiceOfferings();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
index a3ff45c..a3ffbc1 100644
--- a/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
+++ b/engine/schema/src/com/cloud/service/dao/ServiceOfferingDaoImpl.java
@@ -31,11 +31,13 @@ import org.springframework.stereotype.Component;
 import com.cloud.event.UsageEventVO;
 import com.cloud.service.ServiceOfferingDetailsVO;
 import com.cloud.service.ServiceOfferingVO;
+import com.cloud.storage.Storage.ProvisioningType;
 import com.cloud.utils.db.DB;
 import com.cloud.utils.db.GenericDaoBase;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
 import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.dao.UserVmDetailsDao;
 
 @Component
@@ -110,6 +112,13 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase<ServiceOfferingVO, Lo
                 vo.setSpeed(500);
                 update(vo.getId(), vo);
             }
+            if (!vo.getUniqueName().endsWith("-Local")) {
+                if (vo.getUseLocalStorage()) {
+                    vo.setUniqueName(vo.getUniqueName() + "-Local");
+                    vo.setName(vo.getName() + " - Local Storage");
+                    update(vo.getId(), vo);
+                }
+            }
             return vo;
         }
         try {
@@ -238,4 +247,33 @@ public class ServiceOfferingDaoImpl extends GenericDaoBase<ServiceOfferingVO, Lo
 
         return dummyoffering;
     }
+
+    @Override
+    public List<ServiceOfferingVO> createSystemServiceOfferings(String name, String uniqueName, int cpuCount, int ramSize, int cpuSpeed,
+            Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, ProvisioningType provisioningType,
+            boolean recreatable, String tags, boolean systemUse, VirtualMachine.Type vmType, boolean defaultUse) {
+        List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
+        ServiceOfferingVO offering = new ServiceOfferingVO(name, cpuCount, ramSize, cpuSpeed, rateMbps, multicastRateMbps, offerHA, displayText,
+                provisioningType, false, recreatable, tags, systemUse, vmType, defaultUse);
+        offering.setUniqueName(uniqueName);
+        offering = persistSystemServiceOffering(offering);
+        if (offering != null) {
+            list.add(offering);
+        }
+
+        boolean useLocal = true;
+        if (offering.getUseLocalStorage()) { // if 1st one is already local then 2nd needs to be shared
+            useLocal = false;
+        }
+
+        offering = new ServiceOfferingVO(name + (useLocal ? " - Local Storage" : ""), cpuCount, ramSize, cpuSpeed, rateMbps, multicastRateMbps, offerHA, displayText,
+                provisioningType, useLocal, recreatable, tags, systemUse, vmType, defaultUse);
+        offering.setUniqueName(uniqueName + (useLocal ? "-Local" : ""));
+        offering = persistSystemServiceOffering(offering);
+        if (offering != null) {
+            list.add(offering);
+        }
+
+        return list;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
index d853299..9aba5ae 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
@@ -148,7 +148,6 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast
     TrafficType _frontendTrafficType = TrafficType.Guest;
 
     Account _systemAcct;
-    ServiceOfferingVO _elasticLbVmOffering;
     ScheduledExecutorService _gcThreadPool;
     String _mgmtCidr;
 
@@ -290,16 +289,18 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast
         }
         _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
 
-        boolean useLocalStorage = Boolean.parseBoolean(configs.get(DataCenter.SystemVMUseLocalStorageCK));
-
         _elasticLbVmRamSize = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmMemory.key()), DEFAULT_ELB_VM_RAMSIZE);
         _elasticLbvmCpuMHz = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmCpuMhz.key()), DEFAULT_ELB_VM_CPU_MHZ);
         _elasticLbvmNumCpu = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmNumVcpu.key()), 1);
-        _elasticLbVmOffering = new ServiceOfferingVO("System Offering For Elastic LB VM", _elasticLbvmNumCpu,
-                _elasticLbVmRamSize, _elasticLbvmCpuMHz, 0, 0, true, null, Storage.ProvisioningType.THIN, useLocalStorage,
-                true, null, true, VirtualMachine.Type.ElasticLoadBalancerVm, true);
-        _elasticLbVmOffering.setUniqueName(ServiceOffering.elbVmDefaultOffUniqueName);
-        _elasticLbVmOffering = _serviceOfferingDao.persistSystemServiceOffering(_elasticLbVmOffering);
+        List<ServiceOfferingVO> offerings = _serviceOfferingDao.createSystemServiceOfferings("System Offering For Elastic LB VM",
+                ServiceOffering.elbVmDefaultOffUniqueName, _elasticLbvmNumCpu, _elasticLbVmRamSize, _elasticLbvmCpuMHz, 0, 0, true, null,
+                Storage.ProvisioningType.THIN, true, null, true, VirtualMachine.Type.ElasticLoadBalancerVm, true);
+        // this can sometimes happen, if DB is manually or programmatically manipulated
+        if (offerings == null || offerings.size() < 2) {
+            String msg = "Data integrity problem : System Offering For Elastic LB VM has been removed?";
+            s_logger.error(msg);
+            throw new ConfigurationException(msg);
+        }
 
         String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key());
         _enabled = (enabled == null) ? false : Boolean.parseBoolean(enabled);
@@ -322,7 +323,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast
             _itMgr.registerGuru(VirtualMachine.Type.ElasticLoadBalancerVm, this);
         }
 
-        loadBalanceRuleHandler = new LoadBalanceRuleHandler(_elasticLbVmOffering, _instance, _systemAcct);
+        loadBalanceRuleHandler = new LoadBalanceRuleHandler(_instance, _systemAcct);
 
         return true;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
index 497913f..f2c4685 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/LoadBalanceRuleHandler.java
@@ -32,6 +32,7 @@ import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 import org.apache.log4j.Logger;
 
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.Pod;
 import com.cloud.dc.PodVlanMapVO;
@@ -70,8 +71,10 @@ import com.cloud.network.router.VirtualRouter.RedundantState;
 import com.cloud.network.router.VirtualRouter.Role;
 import com.cloud.network.rules.LoadBalancer;
 import com.cloud.offering.NetworkOffering;
+import com.cloud.offering.ServiceOffering;
 import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.VMTemplateVO;
 import com.cloud.storage.dao.VMTemplateDao;
 import com.cloud.user.Account;
@@ -141,16 +144,16 @@ public class LoadBalanceRuleHandler {
     @Inject
     private VirtualRouterProviderDao _vrProviderDao;
     @Inject
+    private ServiceOfferingDao _serviceOfferingDao;
+    @Inject
     private UserDao _userDao;
 
     static final private String ELB_VM_NAME_PREFIX = "l";
 
-    private final ServiceOfferingVO _elasticLbVmOffering;
     private final String _instance;
     private final Account _systemAcct;
 
-    public LoadBalanceRuleHandler(final ServiceOfferingVO elasticLbVmOffering, final String instance, final Account systemAcct) {
-        _elasticLbVmOffering = elasticLbVmOffering;
+    public LoadBalanceRuleHandler(String instance, Account systemAcct) {
         _instance = instance;
         _systemAcct = systemAcct;
     }
@@ -279,12 +282,23 @@ public class LoadBalanceRuleHandler {
                     userId =  _userDao.listByAccount(owner.getAccountId()).get(0).getId();
                 }
 
-                elbVm = new DomainRouterVO(id, _elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX),
+                String offeringName = ServiceOffering.elbVmDefaultOffUniqueName;
+                Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
+                if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+                    offeringName += "-Local";
+                }
+                ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findByName(offeringName);
+                if (elasticLbVmOffering == null) {
+                    String message = "System service offering " + offeringName + " not found";
+                    s_logger.error(message);
+                    throw new CloudRuntimeException(message);
+                }
+                elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX),
                         template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN,
-                        _elasticLbVmOffering.getOfferHA(), false, null);
+                        elasticLbVmOffering.getOfferHA(), false, null);
                 elbVm.setRole(Role.LB);
                 elbVm = _routerDao.persist(elbVm);
-                _itMgr.allocate(elbVm.getInstanceName(), template, _elasticLbVmOffering, networks, plan, null);
+                _itMgr.allocate(elbVm.getInstanceName(), template, elasticLbVmOffering, networks, plan, null);
                 elbVm = _routerDao.findById(elbVm.getId());
                 //TODO: create usage stats
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
index affbd5c..818ad88 100644
--- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
+++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java
@@ -46,6 +46,7 @@ import com.cloud.agent.api.routing.NetworkElementCommand;
 import com.cloud.agent.api.to.LoadBalancerTO;
 import com.cloud.agent.manager.Commands;
 import com.cloud.configuration.Config;
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenterVO;
 import com.cloud.dc.dao.DataCenterDao;
@@ -380,15 +381,15 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
 
         //if offering wasn't set, try to get the default one
         if (_internalLbVmOfferingId == 0L) {
-            final boolean useLocalStorage = Boolean.parseBoolean(configs.get(DataCenter.SystemVMUseLocalStorageCK));
-            ServiceOfferingVO newOff =
-                    new ServiceOfferingVO("System Offering For Internal LB VM", 1, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_RAMSIZE,
-                            InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_CPU_MHZ, null, null, true, null,
-                            Storage.ProvisioningType.THIN, useLocalStorage, true, null, true,
-                            VirtualMachine.Type.InternalLoadBalancerVm, true);
-            newOff.setUniqueName(ServiceOffering.internalLbVmDefaultOffUniqueName);
-            newOff = _serviceOfferingDao.persistSystemServiceOffering(newOff);
-            _internalLbVmOfferingId = newOff.getId();
+            List<ServiceOfferingVO> offerings = _serviceOfferingDao.createSystemServiceOfferings("System Offering For Internal LB VM",
+                    ServiceOffering.internalLbVmDefaultOffUniqueName, 1, InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_RAMSIZE,
+                    InternalLoadBalancerVMManager.DEFAULT_INTERNALLB_VM_CPU_MHZ, null, null, true, null,
+                    Storage.ProvisioningType.THIN, true, null, true, VirtualMachine.Type.InternalLoadBalancerVm, true);
+            if (offerings == null || offerings.size() < 2) {
+                String msg = "Data integrity problem : System Offering For Internal LB VM has been removed?";
+                s_logger.error(msg);
+                throw new ConfigurationException(msg);
+            }
         }
 
         _itMgr.registerGuru(VirtualMachine.Type.InternalLoadBalancerVm, this);
@@ -620,9 +621,24 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In
             }
 
             final LinkedHashMap<Network, List<? extends NicProfile>> networks = createInternalLbVmNetworks(guestNetwork, plan, requestedGuestIp);
+            long internalLbVmOfferingId = _internalLbVmOfferingId;
+            if (internalLbVmOfferingId == 0L) {
+                String offeringName = ServiceOffering.internalLbVmDefaultOffUniqueName;
+                Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
+                if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+                    offeringName += "-Local";
+                }
+                ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(offeringName);
+                if (serviceOffering == null) {
+                    String message = "System service offering " + offeringName + " not found";
+                    s_logger.error(message);
+                    throw new CloudRuntimeException(message);
+                }
+                internalLbVmOfferingId = serviceOffering.getId();
+            }
             //Pass startVm=false as we are holding the network lock that needs to be released at the end of vm allocation
             final DomainRouterVO internalLbVm =
-                    deployInternalLbVm(owner, dest, plan, params, internalLbProviderId, _internalLbVmOfferingId, guestNetwork.getVpcId(), networks, false);
+                    deployInternalLbVm(owner, dest, plan, params, internalLbProviderId, internalLbVmOfferingId, guestNetwork.getVpcId(), networks, false);
             if (internalLbVm != null) {
                 _internalLbVmDao.addRouterToGuestNetwork(internalLbVm, guestNetwork);
                 internalLbVms.add(internalLbVm);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
index 0b47b1f..bc48d46 100644
--- a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMManagerTest.java
@@ -59,6 +59,7 @@ import com.cloud.offerings.dao.NetworkOfferingDao;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.Storage;
+import com.cloud.storage.Storage.ProvisioningType;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountVO;
 import com.cloud.utils.component.ComponentContext;
@@ -120,7 +121,12 @@ public class InternalLBVMManagerTest extends TestCase {
         ServiceOfferingVO off = new ServiceOfferingVO("alena", 1, 1,
                 1, 1, 1, false, "alena", Storage.ProvisioningType.THIN, false, false, null, false, VirtualMachine.Type.InternalLoadBalancerVm, false);
         off = setId(off, 1);
-        Mockito.when(_svcOffDao.persistSystemServiceOffering(Matchers.any(ServiceOfferingVO.class))).thenReturn(off);
+        List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
+        list.add(off);
+        list.add(off);
+        Mockito.when(_svcOffDao.createSystemServiceOfferings(Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(),
+                Matchers.anyInt(), Matchers.anyInt(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.any(ProvisioningType.class), Matchers.anyBoolean(),
+                Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(VirtualMachine.Type.class), Matchers.anyBoolean())).thenReturn(list);
 
         ComponentContext.initComponentsLifeCycle();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
index e376e51..84c5f1b 100644
--- a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
+++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbvmmgr/InternalLBVMServiceTest.java
@@ -17,6 +17,8 @@
 package org.apache.cloudstack.internallbvmmgr;
 
 import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.inject.Inject;
 
@@ -44,6 +46,7 @@ import com.cloud.network.router.VirtualRouter.Role;
 import com.cloud.service.ServiceOfferingVO;
 import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.storage.Storage;
+import com.cloud.storage.Storage.ProvisioningType;
 import com.cloud.user.AccountManager;
 import com.cloud.user.AccountVO;
 import com.cloud.user.UserVO;
@@ -90,7 +93,12 @@ public class InternalLBVMServiceTest extends TestCase {
         ServiceOfferingVO off = new ServiceOfferingVO("alena", 1, 1,
                 1, 1, 1, false, "alena", Storage.ProvisioningType.THIN, false, false, null, false, VirtualMachine.Type.InternalLoadBalancerVm, false);
         off = setId(off, 1);
-        Mockito.when(_svcOffDao.persistSystemServiceOffering(Matchers.any(ServiceOfferingVO.class))).thenReturn(off);
+        List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
+        list.add(off);
+        list.add(off);
+        Mockito.when(_svcOffDao.createSystemServiceOfferings(Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(),
+                Matchers.anyInt(), Matchers.anyInt(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.any(ProvisioningType.class), Matchers.anyBoolean(),
+                Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(VirtualMachine.Type.class), Matchers.anyBoolean())).thenReturn(list);
 
         ComponentContext.initComponentsLifeCycle();
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index 8dcddc8..2352313 100644
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -685,7 +685,6 @@ public enum Config {
             "/var/cloudstack/mnt",
             "The mount point on the Management Server for Secondary Storage.",
             null),
-//    UpgradeURL("Advanced", ManagementServer.class, String.class, "upgrade.url", "http://example.com:8080/client/agent/update.zip", "The upgrade URL is the URL of the management server that agents will connect to in order to automatically upgrade.", null),
     SystemVMAutoReserveCapacity(
             "Advanced",
             ManagementServer.class,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index a739695..d08cac6 100644
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -38,7 +38,6 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.log4j.Logger;
-
 import org.apache.cloudstack.acl.SecurityChecker;
 import org.apache.cloudstack.affinity.AffinityGroup;
 import org.apache.cloudstack.affinity.AffinityGroupService;
@@ -72,6 +71,7 @@ import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationSe
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 import org.apache.cloudstack.framework.config.ConfigDepot;
 import org.apache.cloudstack.framework.config.ConfigKey;
+import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
 import org.apache.cloudstack.framework.config.impl.ConfigurationVO;
 import org.apache.cloudstack.region.PortableIp;
@@ -215,7 +215,7 @@ import com.cloud.vm.dao.NicIpAliasVO;
 import com.cloud.vm.dao.NicSecondaryIpDao;
 
 @Local(value = {ConfigurationManager.class, ConfigurationService.class})
-public class ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService {
+public class ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService, Configurable {
     public static final Logger s_logger = Logger.getLogger(ConfigurationManagerImpl.class);
 
     @Inject
@@ -335,6 +335,9 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
     private Set<String> weightBasedParametersForValidation;
     private Set<String> overprovisioningFactorsForValidation;
 
+    public static final ConfigKey<Boolean> SystemVMUseLocalStorage = new ConfigKey<Boolean>(Boolean.class, "system.vm.use.local.storage", "Advanced", "false",
+            "Indicates whether to use local storage pools or shared storage pools for system VMs.", false, ConfigKey.Scope.Zone, null);
+
     @Override
     public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
         String maxVolumeSizeInGbString = _configDao.getValue(Config.MaxVolumeSize.key());
@@ -575,35 +578,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             } catch (Throwable e) {
                 throw new CloudRuntimeException("Failed to update storage.network.device2 in host_details due to exception ", e);
             }
-        } else if (DataCenter.SystemVMUseLocalStorageCK.equalsIgnoreCase(name)) {
-            if (s_logger.isDebugEnabled()) {
-                s_logger.debug("Config 'system.vm.use.local.storage' changed to value:" + value + ", need to update System VM offerings");
-            }
-            boolean useLocalStorage = Boolean.parseBoolean(_configDao.getValue(DataCenter.SystemVMUseLocalStorageCK));
-            ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.consoleProxyDefaultOffUniqueName);
-            if (serviceOffering != null) {
-                serviceOffering.setUseLocalStorage(useLocalStorage);
-                if (!_serviceOfferingDao.update(serviceOffering.getId(), serviceOffering)) {
-                    throw new CloudRuntimeException("Failed to update ConsoleProxy offering's use_local_storage option to value:" + useLocalStorage);
-                }
-            }
-
-            serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.routerDefaultOffUniqueName);
-            if (serviceOffering != null) {
-                serviceOffering.setUseLocalStorage(useLocalStorage);
-                if (!_serviceOfferingDao.update(serviceOffering.getId(), serviceOffering)) {
-                    throw new CloudRuntimeException("Failed to update SoftwareRouter offering's use_local_storage option to value:" + useLocalStorage);
-                }
-            }
-
-            serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.ssvmDefaultOffUniqueName);
-            if (serviceOffering != null) {
-                serviceOffering.setUseLocalStorage(useLocalStorage);
-                if (!_serviceOfferingDao.update(serviceOffering.getId(), serviceOffering)) {
-                    throw new CloudRuntimeException("Failed to update SecondaryStorage offering's use_local_storage option to value:" + useLocalStorage);
-                }
-            }
-        }else if (Config.SecStorageSecureCopyCert.key().equalsIgnoreCase(name)) {
+        } else if (Config.SecStorageSecureCopyCert.key().equalsIgnoreCase(name)) {
             //FIXME - Ideally there should be a listener model to listen to global config changes and be able to take action gracefully.
             //Expire the download urls
             String sqlTemplate = "update template_store_ref set download_url_created=?";
@@ -622,8 +597,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
             } catch (Throwable e) {
                 throw new CloudRuntimeException("Failed to clean up download URLs in template_store_ref or volume_store_ref due to exception ", e);
             }
-
-
         }
 
         txn.commit();
@@ -5200,4 +5173,13 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
         _secChecker = secChecker;
     }
 
+    @Override
+    public String getConfigComponentName() {
+        return ConfigurationManagerImpl.class.getSimpleName();
+    }
+
+    @Override
+    public ConfigKey<?>[] getConfigKeys() {
+        return new ConfigKey<?>[] {SystemVMUseLocalStorage};
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
index bfcef5f..f8d7474 100644
--- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
+++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
@@ -60,6 +60,7 @@ import com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer;
 import com.cloud.agent.manager.Commands;
 import com.cloud.cluster.ClusterManager;
 import com.cloud.configuration.Config;
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.configuration.ZoneConfig;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenter.NetworkType;
@@ -225,7 +226,6 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
     private int _capacityPerProxy = ConsoleProxyManager.DEFAULT_PROXY_CAPACITY;
     private int _standbyCapacity = ConsoleProxyManager.DEFAULT_STANDBY_CAPACITY;
 
-    private boolean _useLvm;
     private boolean _useStorageVm;
     private boolean _disableRpFilter = false;
     private String _instance;
@@ -716,13 +716,27 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
             networks.put(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<NicProfile>());
         }
 
+        ServiceOfferingVO serviceOffering = _serviceOffering;
+        if (serviceOffering == null) {
+            String offeringName = ServiceOffering.consoleProxyDefaultOffUniqueName;
+            Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
+            if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+                offeringName += "-Local";
+            }
+            serviceOffering = _offeringDao.findByName(offeringName);
+            if (serviceOffering == null) {
+                String message = "System service offering " + offeringName + " not found";
+                s_logger.error(message);
+                throw new CloudRuntimeException(message);
+            }
+        }
         ConsoleProxyVO proxy =
-            new ConsoleProxyVO(id, _serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
-                systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), 0, _serviceOffering.getOfferHA());
+            new ConsoleProxyVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
+                systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), 0, serviceOffering.getOfferHA());
         proxy.setDynamicallyScalable(template.isDynamicallyScalable());
         proxy = _consoleProxyDao.persist(proxy);
         try {
-            _itMgr.allocate(name, template, _serviceOffering, networks, plan, null);
+            _itMgr.allocate(name, template, serviceOffering, networks, plan, null);
         } catch (InsufficientCapacityException e) {
             s_logger.warn("InsufficientCapacity", e);
             throw new CloudRuntimeException("Insufficient capacity exception", e);
@@ -951,7 +965,12 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
             TemplateDataStoreVO templateHostRef = _vmTemplateStoreDao.findByTemplateZoneDownloadStatus(template.getId(), dataCenterId, Status.DOWNLOADED);
 
             if (templateHostRef != null) {
-                List<Pair<Long, Integer>> l = _consoleProxyDao.getDatacenterStoragePoolHostInfo(dataCenterId, _useLvm);
+                boolean useLocalStorage = false;
+                Boolean useLocal = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
+                if (useLocal != null) {
+                    useLocalStorage = useLocal.booleanValue();
+                }
+                List<Pair<Long, Integer>> l = _consoleProxyDao.getDatacenterStoragePoolHostInfo(dataCenterId, useLocalStorage);
                 if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
                     return true;
                 } else {
@@ -1208,11 +1227,6 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
             _disableRpFilter = true;
         }
 
-        value = configs.get(DataCenter.SystemVMUseLocalStorageCK);
-        if (value != null && value.equalsIgnoreCase("true")) {
-            _useLvm = true;
-        }
-
         value = configs.get("secondary.storage.vm");
         if (value != null && value.equalsIgnoreCase("true")) {
             _useStorageVm = true;
@@ -1238,8 +1252,6 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
 
         _itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);
 
-        boolean useLocalStorage = Boolean.parseBoolean(configs.get(DataCenter.SystemVMUseLocalStorageCK));
-
         //check if there is a default service offering configured
         String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key());
         if (cpvmSrvcOffIdStr != null) {
@@ -1259,15 +1271,11 @@ public class ConsoleProxyManagerImpl extends ManagerBase implements ConsoleProxy
         if (_serviceOffering == null || !_serviceOffering.getSystemUse()) {
             int ramSize = NumbersUtil.parseInt(_configDao.getValue("console.ram.size"), DEFAULT_PROXY_VM_RAMSIZE);
             int cpuFreq = NumbersUtil.parseInt(_configDao.getValue("console.cpu.mhz"), DEFAULT_PROXY_VM_CPUMHZ);
-            _serviceOffering =
-                new ServiceOfferingVO("System Offering For Console Proxy", 1, ramSize, cpuFreq, 0, 0, false, null,
-                    Storage.ProvisioningType.THIN, useLocalStorage, true, null, true,
-                    VirtualMachine.Type.ConsoleProxy, true);
-            _serviceOffering.setUniqueName(ServiceOffering.consoleProxyDefaultOffUniqueName);
-            _serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering);
-
+            List<ServiceOfferingVO> offerings = _offeringDao.createSystemServiceOfferings("System Offering For Console Proxy",
+                    ServiceOffering.consoleProxyDefaultOffUniqueName, 1, ramSize, cpuFreq, 0, 0, false, null,
+                    Storage.ProvisioningType.THIN, true, null, true, VirtualMachine.Type.ConsoleProxy, true);
             // this can sometimes happen, if DB is manually or programmatically manipulated
-            if (_serviceOffering == null) {
+            if (offerings == null || offerings.size() < 2) {
                 String msg = "Data integrity problem : System Offering For Console Proxy has been removed?";
                 s_logger.error(msg);
                 throw new ConfigurationException(msg);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
index 3a7173b..57abb92 100644
--- a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
+++ b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
@@ -32,8 +32,8 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import com.cloud.utils.fsm.StateMachine2;
-import org.apache.log4j.Logger;
 
+import org.apache.log4j.Logger;
 import org.apache.cloudstack.affinity.AffinityGroupProcessor;
 import org.apache.cloudstack.affinity.AffinityGroupService;
 import org.apache.cloudstack.affinity.AffinityGroupVMMapVO;
@@ -46,8 +46,6 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
 import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator;
 import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
-import org.apache.cloudstack.framework.config.ConfigKey;
-import org.apache.cloudstack.framework.config.Configurable;
 import org.apache.cloudstack.framework.messagebus.MessageBus;
 import org.apache.cloudstack.framework.messagebus.MessageSubscriber;
 import org.apache.cloudstack.managed.context.ManagedContextTimerTask;
@@ -67,6 +65,7 @@ import com.cloud.agent.manager.allocator.HostAllocator;
 import com.cloud.capacity.CapacityManager;
 import com.cloud.capacity.dao.CapacityDao;
 import com.cloud.configuration.Config;
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.dc.ClusterDetailsDao;
 import com.cloud.dc.ClusterDetailsVO;
 import com.cloud.dc.ClusterVO;
@@ -134,7 +133,7 @@ import com.cloud.vm.dao.VMInstanceDao;
 
 @Local(value = {DeploymentPlanningManager.class})
 public class DeploymentPlanningManagerImpl extends ManagerBase implements DeploymentPlanningManager, Manager, Listener,
-StateListener<State, VirtualMachine.Event, VirtualMachine>, Configurable {
+StateListener<State, VirtualMachine.Event, VirtualMachine> {
 
     private static final Logger s_logger = Logger.getLogger(DeploymentPlanningManagerImpl.class);
     @Inject
@@ -762,16 +761,6 @@ StateListener<State, VirtualMachine.Event, VirtualMachine>, Configurable {
         return false;
     }
 
-    @Override
-    public String getConfigComponentName() {
-        return DeploymentPlanningManagerImpl.class.getSimpleName();
-    }
-
-    @Override
-    public ConfigKey<?>[] getConfigKeys() {
-        return new ConfigKey<?>[] {DataCenter.UseSystemVMLocalStorage};
-    }
-
     class HostReservationReleaseChecker extends ManagedContextTimerTask {
         @Override
         protected void runInContext() {
@@ -1301,20 +1290,11 @@ StateListener<State, VirtualMachine.Event, VirtualMachine>, Configurable {
             boolean useLocalStorage = false;
             if (vmProfile.getType() != VirtualMachine.Type.User) {
                 DataCenterVO zone = _dcDao.findById(plan.getDataCenterId());
-                // It should not happen to have a "null" zone here. There can be NO instance if there is NO zone,
-                // so this part of the code would never be reached if no zone has been created.
-                // Added the check and the comment just to make it clear.
-                boolean zoneUsesLocalStorage = zone != null ? zone.isLocalStorageEnabled() : false;
-                boolean ssvmUseLocalStorage = DataCenter.UseSystemVMLocalStorage.value();
-                if (zone != null) {
-                    ssvmUseLocalStorage = DataCenter.UseSystemVMLocalStorage.valueIn(plan.getDataCenterId());
-                }
-                s_logger.debug("Checking if we need local storage for systemvms is needed for zone id=" + plan.getDataCenterId() + " with system.vm.use.local.storage=" + ssvmUseLocalStorage);
-                // Local storage is used for the NON User VMs if, and only if, the Zone is marked to use local storage AND
-                // the global settings (ssvmUseLocalStorage) is set to true. Otherwise, the global settings won't be applied.
-                if (ssvmUseLocalStorage && zoneUsesLocalStorage) {
-                    useLocalStorage = true;
-                    s_logger.debug("SystemVMs will use local storage for zone id=" + plan.getDataCenterId());
+                assert (zone != null) : "Invalid zone in deployment plan";
+                Boolean useLocalStorageForSystemVM = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(zone.getId());
+                if (useLocalStorageForSystemVM != null) {
+                    useLocalStorage = useLocalStorageForSystemVM.booleanValue();
+                    s_logger.debug("System VMs will use " + (useLocalStorage ? "local" : "shared") + " storage for zone id=" + plan.getDataCenterId());
                 }
             } else {
                 useLocalStorage = diskOffering.getUseLocalStorage();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
index c7e0c29..2a518e4 100644
--- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
+++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
@@ -631,12 +631,15 @@ Configurable, StateListener<State, VirtualMachine.Event, VirtualMachine> {
 
         _agentMgr.registerForHostEvents(new SshKeysDistriMonitor(_agentMgr, _hostDao, _configDao), true, false, false);
 
-        final boolean useLocalStorage = Boolean.parseBoolean(configs.get(DataCenter.SystemVMUseLocalStorageCK));
-        ServiceOfferingVO offering = new ServiceOfferingVO("System Offering For Software Router", 1, _routerRamSize, _routerCpuMHz, null, null, true, null, ProvisioningType.THIN,
-                useLocalStorage, true, null, true, VirtualMachine.Type.DomainRouter, true);
-        offering.setUniqueName(ServiceOffering.routerDefaultOffUniqueName);
-        offering = _serviceOfferingDao.persistSystemServiceOffering(offering);
-        _routerDeploymentManagerBuilder.setOfferingId(offering.getId());
+        List<ServiceOfferingVO> offerings = _serviceOfferingDao.createSystemServiceOfferings("System Offering For Software Router",
+                ServiceOffering.routerDefaultOffUniqueName, 1, _routerRamSize, _routerCpuMHz, null,
+                null, true, null, ProvisioningType.THIN, true, null, true, VirtualMachine.Type.DomainRouter, true);
+        // this can sometimes happen, if DB is manually or programmatically manipulated
+        if (offerings == null || offerings.size() < 2) {
+            final String msg = "Data integrity problem : System Offering For Software router VM has been removed?";
+            s_logger.error(msg);
+            throw new ConfigurationException(msg);
+        }
 
         NetworkHelperImpl.setSystemAccount(_accountMgr.getSystemAccount());
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/com/cloud/storage/StorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java
index e725ce3..2c70b17 100644
--- a/server/src/com/cloud/storage/StorageManagerImpl.java
+++ b/server/src/com/cloud/storage/StorageManagerImpl.java
@@ -42,6 +42,7 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import com.cloud.hypervisor.Hypervisor;
+
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd;
@@ -111,6 +112,7 @@ import com.cloud.cluster.ClusterManagerListener;
 import com.cloud.cluster.ManagementServerHost;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.configuration.Resource.ResourceType;
 import com.cloud.dc.ClusterVO;
 import com.cloud.dc.DataCenterVO;
@@ -546,9 +548,16 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C
     @DB
     @Override
     public DataStore createLocalStorage(Host host, StoragePoolInfo pInfo) throws ConnectionException {
-
         DataCenterVO dc = _dcDao.findById(host.getDataCenterId());
-        if (dc == null || !dc.isLocalStorageEnabled()) {
+        if (dc == null) {
+            return null;
+        }
+        boolean useLocalStorageForSystemVM = false;
+        Boolean isLocal = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dc.getId());
+        if (isLocal != null) {
+            useLocalStorageForSystemVM = isLocal.booleanValue();
+        }
+        if (!(dc.isLocalStorageEnabled() || useLocalStorageForSystemVM)) {
             return null;
         }
         DataStore store;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
----------------------------------------------------------------------
diff --git a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
index 5ef2070..569200c 100644
--- a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
+++ b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinition.java
@@ -23,6 +23,7 @@ import java.util.Map;
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 import org.apache.log4j.Logger;
 
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.dc.HostPodVO;
 import com.cloud.dc.Pod;
@@ -52,7 +53,10 @@ import com.cloud.network.dao.VirtualRouterProviderDao;
 import com.cloud.network.router.NetworkHelper;
 import com.cloud.network.router.VirtualRouter.Role;
 import com.cloud.network.vpc.Vpc;
+import com.cloud.offering.ServiceOffering;
 import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.utils.db.DB;
@@ -80,6 +84,7 @@ public class RouterDeploymentDefinition {
     protected NetworkModel networkModel;
     protected VirtualRouterProviderDao vrProviderDao;
     protected NetworkOfferingDao networkOfferingDao;
+    protected ServiceOfferingDao serviceOfferingDao;
     protected IpAddressManager ipAddrMgr;
     protected VMInstanceDao vmDao;
     protected HostPodDao podDao;
@@ -354,10 +359,23 @@ public class RouterDeploymentDefinition {
         }
     }
 
+    protected void findDefaultServiceOfferingId() {
+        String offeringName = ServiceOffering.routerDefaultOffUniqueName;
+        Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId());
+        if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+            offeringName += "-Local";
+        }
+        ServiceOfferingVO serviceOffering = serviceOfferingDao.findByName(offeringName);
+        if (serviceOffering == null) {
+            throw new CloudRuntimeException("System service offering " + offeringName + " not found");
+        }
+        serviceOfferingId = serviceOffering.getId();
+    }
+
     protected void findServiceOfferingId() {
-        final Long networkOfferingId = networkOfferingDao.findById(guestNetwork.getNetworkOfferingId()).getServiceOfferingId();
-        if (networkOfferingId != null) {
-            serviceOfferingId = networkOfferingId;
+        serviceOfferingId = networkOfferingDao.findById(guestNetwork.getNetworkOfferingId()).getServiceOfferingId();
+        if (serviceOfferingId == null) {
+            findDefaultServiceOfferingId();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinitionBuilder.java
----------------------------------------------------------------------
diff --git a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinitionBuilder.java b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinitionBuilder.java
index 33ed9d0..3ba4fad 100644
--- a/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinitionBuilder.java
+++ b/server/src/org/cloud/network/router/deployment/RouterDeploymentDefinitionBuilder.java
@@ -45,6 +45,7 @@ import com.cloud.network.vpc.VpcManager;
 import com.cloud.network.vpc.dao.VpcDao;
 import com.cloud.network.vpc.dao.VpcOfferingDao;
 import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.vm.DomainRouterVO;
@@ -68,6 +69,8 @@ public class RouterDeploymentDefinitionBuilder {
     @Inject
     private NetworkOfferingDao networkOfferingDao;
     @Inject
+    private ServiceOfferingDao serviceOfferingDao;
+    @Inject
     private IpAddressManager ipAddrMgr;
     @Inject
     private VMInstanceDao vmDao;
@@ -120,6 +123,7 @@ public class RouterDeploymentDefinitionBuilder {
         routerDeploymentDefinition.networkModel = networkModel;
         routerDeploymentDefinition.vrProviderDao = vrProviderDao;
         routerDeploymentDefinition.networkOfferingDao = networkOfferingDao;
+        routerDeploymentDefinition.serviceOfferingDao = serviceOfferingDao;
         routerDeploymentDefinition.ipAddrMgr = ipAddrMgr;
         routerDeploymentDefinition.vmDao = vmDao;
         routerDeploymentDefinition.podDao = podDao;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/src/org/cloud/network/router/deployment/VpcRouterDeploymentDefinition.java
----------------------------------------------------------------------
diff --git a/server/src/org/cloud/network/router/deployment/VpcRouterDeploymentDefinition.java b/server/src/org/cloud/network/router/deployment/VpcRouterDeploymentDefinition.java
index 5124195..26f2379 100644
--- a/server/src/org/cloud/network/router/deployment/VpcRouterDeploymentDefinition.java
+++ b/server/src/org/cloud/network/router/deployment/VpcRouterDeploymentDefinition.java
@@ -156,9 +156,9 @@ public class VpcRouterDeploymentDefinition extends RouterDeploymentDefinition {
 
     @Override
     protected void findServiceOfferingId() {
-        final Long vpcOfferingId = vpcOffDao.findById(vpc.getVpcOfferingId()).getServiceOfferingId();
-        if (vpcOfferingId != null) {
-            serviceOfferingId = vpcOfferingId;
+        serviceOfferingId = vpcOffDao.findById(vpc.getVpcOfferingId()).getServiceOfferingId();
+        if (serviceOfferingId == null) {
+            findDefaultServiceOfferingId();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/test/com/cloud/network/element/VirtualRouterElementTest.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/network/element/VirtualRouterElementTest.java b/server/test/com/cloud/network/element/VirtualRouterElementTest.java
index f139852..6592778 100644
--- a/server/test/com/cloud/network/element/VirtualRouterElementTest.java
+++ b/server/test/com/cloud/network/element/VirtualRouterElementTest.java
@@ -33,6 +33,7 @@ import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
+import org.mockito.Matchers;
 import org.mockito.Mock;
 import org.mockito.runners.MockitoJUnitRunner;
 
@@ -169,7 +170,7 @@ public class VirtualRouterElementTest {
     private RouterDeploymentDefinitionBuilder routerDeploymentDefinitionBuilder;
 
     @InjectMocks
-    private VpcVirtualNetworkApplianceManagerImpl _routerMgr ;
+    private VpcVirtualNetworkApplianceManagerImpl _routerMgr;
 
     @InjectMocks
     private VirtualRouterElement virtualRouterElement;
@@ -210,7 +211,7 @@ public class VirtualRouterElementTest {
     public void testPrepare() {
         virtualRouterElement._routerMgr = _routerMgr;
         virtualRouterElement.routerDeploymentDefinitionBuilder = routerDeploymentDefinitionBuilder;
-        mockDAOs(testNetwork,testOffering);
+        mockDAOs(testNetwork, testOffering);
         mockMgrs();
 
         boolean done = false;
@@ -276,6 +277,7 @@ public class VirtualRouterElementTest {
                 VirtualMachine.Type.DomainRouter,
                 /* defaultUse */ false);
         when(_serviceOfferingDao.findById(0L)).thenReturn(svcoff);
+        when(_serviceOfferingDao.findByName(Matchers.anyString())).thenReturn(svcoff);
         final DomainRouterVO router = new DomainRouterVO(/* id */ 1L,
                 /* serviceOfferingId */ 1L,
                 /* elementId */ 0L,

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
index abd80d7..b266f88 100644
--- a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
+++ b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTest.java
@@ -38,6 +38,7 @@ import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationSe
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.mockito.Matchers;
 import org.mockito.Mock;
 import org.mockito.runners.MockitoJUnitRunner;
 
@@ -635,7 +636,7 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
     }
 
     @Test
-    public void testFindOfferingIdReceivingNewOne() {
+    public void testFindOfferingIdFromNetwork() {
         // Prepare
         deployment.serviceOfferingId = 1L;
         when(mockNw.getNetworkOfferingId()).thenReturn(OFFERING_ID);
@@ -646,24 +647,26 @@ public class RouterDeploymentDefinitionTest extends RouterDeploymentDefinitionTe
         deployment.findServiceOfferingId();
 
         // Assert
-        assertEquals("Given that no Offering was found, the previous Offering Id should be kept",
+        assertEquals("Service offering id not matching the one associated with network offering",
                 OFFERING_ID, deployment.serviceOfferingId.longValue());
     }
 
     @Test
-    public void testFindOfferingIdReceivingKeepingPrevious() {
+    public void testFindOfferingIdDefault() {
         // Prepare
         deployment.serviceOfferingId = 1L;
         when(mockNw.getNetworkOfferingId()).thenReturn(OFFERING_ID);
         when(mockNetworkOfferingDao.findById(OFFERING_ID)).thenReturn(mockNwOfferingVO);
         when(mockNwOfferingVO.getServiceOfferingId()).thenReturn(null);
+        when(mockServiceOfferingDao.findByName(Matchers.anyString())).thenReturn(mockSvcOfferingVO);
+        when(mockSvcOfferingVO.getId()).thenReturn(DEFAULT_OFFERING_ID);
 
         // Execute
         deployment.findServiceOfferingId();
 
         // Assert
-        assertEquals("Found Offering Id didn't replace previous one",
-                1L, deployment.serviceOfferingId.longValue());
+        assertEquals("Since there is no service offering associated with network offering, offering id should have matched default one",
+                DEFAULT_OFFERING_ID, deployment.serviceOfferingId.longValue());
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTestBase.java
----------------------------------------------------------------------
diff --git a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTestBase.java b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTestBase.java
index 0978ac9..4225083 100644
--- a/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTestBase.java
+++ b/server/test/org/cloud/network/router/deployment/RouterDeploymentDefinitionTestBase.java
@@ -43,6 +43,8 @@ import com.cloud.network.router.NetworkHelper;
 import com.cloud.network.router.VpcNetworkHelperImpl;
 import com.cloud.offerings.NetworkOfferingVO;
 import com.cloud.offerings.dao.NetworkOfferingDao;
+import com.cloud.service.ServiceOfferingVO;
+import com.cloud.service.dao.ServiceOfferingDao;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
 import com.cloud.vm.VirtualMachineProfile.Param;
@@ -57,6 +59,7 @@ public class RouterDeploymentDefinitionTestBase {
     protected static final String ONLY_THE_PROVIDED_AS_DEFAULT_DESTINATION_WAS_EXPECTED = "Only the provided as default destination was expected";
 
     protected static final long OFFERING_ID = 16L;
+    protected static final long DEFAULT_OFFERING_ID = 17L;
     protected static final Long DATA_CENTER_ID = 100l;
     protected static final Long NW_ID_1 = 101l;
     protected static final Long NW_ID_2= 102l;
@@ -92,6 +95,8 @@ public class RouterDeploymentDefinitionTestBase {
     @Mock
     protected NetworkOfferingDao mockNetworkOfferingDao;
     @Mock
+    protected ServiceOfferingDao mockServiceOfferingDao;
+    @Mock
     protected AccountManager mockAccountMgr;
 
     // Instance specific parameters to use during build
@@ -112,6 +117,8 @@ public class RouterDeploymentDefinitionTestBase {
     @Mock
     NetworkOfferingVO mockNwOfferingVO;
     @Mock
+    ServiceOfferingVO mockSvcOfferingVO;
+    @Mock
     protected Account mockOwner;
 
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java b/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
index 4ef3593..5a34ebf 100644
--- a/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
+++ b/server/test/org/cloud/network/router/deployment/VpcRouterDeploymentDefinitionTest.java
@@ -31,6 +31,7 @@ import java.util.List;
 
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Matchers;
 import org.mockito.Mock;
 
 import com.cloud.deploy.DeployDestination;
@@ -178,23 +179,24 @@ public class VpcRouterDeploymentDefinitionTest extends RouterDeploymentDefinitio
     }
 
     @Test
-    public void testFindOfferingIdLeavingPrevious() {
+    public void testFindOfferingIdDefault() {
         // Prepare
-        final Long initialOfferingId = deployment.serviceOfferingId;
         final VpcOfferingVO vpcOffering = mock(VpcOfferingVO.class);
         when(mockVpcOffDao.findById(VPC_OFFERING_ID)).thenReturn(vpcOffering);
         when(vpcOffering.getServiceOfferingId()).thenReturn(null);
+        when(mockServiceOfferingDao.findByName(Matchers.anyString())).thenReturn(mockSvcOfferingVO);
+        when(mockSvcOfferingVO.getId()).thenReturn(DEFAULT_OFFERING_ID);
 
         // Execute
         deployment.findServiceOfferingId();
 
         // Assert
-        assertEquals("Offering Id shouldn't have been updated",
-                initialOfferingId, deployment.serviceOfferingId);
+        assertEquals("Since there is no service offering associated with VPC offering, offering id should have matched default one",
+                DEFAULT_OFFERING_ID, deployment.serviceOfferingId.longValue());
     }
 
     @Test
-    public void testFindOfferingIdSettingNewOne() {
+    public void testFindOfferingIdFromVPC() {
         // Prepare
         final VpcOfferingVO vpcOffering = mock(VpcOfferingVO.class);
         when(mockVpcOffDao.findById(VPC_OFFERING_ID)).thenReturn(vpcOffering);
@@ -204,7 +206,7 @@ public class VpcRouterDeploymentDefinitionTest extends RouterDeploymentDefinitio
         deployment.findServiceOfferingId();
 
         // Assert
-        assertEquals("Offering Id should have been updated",
+        assertEquals("Service offering id not matching the one associated with VPC offering",
                 VPC_OFFERING_ID, deployment.serviceOfferingId.longValue());
     }
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3f7e31ed/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --git a/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java b/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
index 4dc6dbb..445852d 100644
--- a/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
+++ b/services/secondary-storage/controller/src/org/apache/cloudstack/secondarystorage/SecondaryStorageManagerImpl.java
@@ -32,7 +32,6 @@ import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.config.ApiServiceConfiguration;
-
 import org.apache.cloudstack.context.CallContext;
 import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
 import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
@@ -64,6 +63,7 @@ import com.cloud.agent.manager.Commands;
 import com.cloud.capacity.dao.CapacityDao;
 import com.cloud.cluster.ClusterManager;
 import com.cloud.configuration.Config;
+import com.cloud.configuration.ConfigurationManagerImpl;
 import com.cloud.configuration.ZoneConfig;
 import com.cloud.consoleproxy.ConsoleProxyManager;
 import com.cloud.dc.DataCenter;
@@ -242,7 +242,6 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
     private int _secStorageVmMtuSize;
 
     private String _instance;
-    private boolean _useLocalStorage;
     private boolean _useSSlCopy;
     private String _httpProxy;
     private String _allowedInternalSites;
@@ -577,13 +576,27 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
             throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
         }
 
+        ServiceOfferingVO serviceOffering = _serviceOffering;
+        if (serviceOffering == null) {
+            String offeringName = ServiceOffering.ssvmDefaultOffUniqueName;
+            Boolean useLocalStorage = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
+            if (useLocalStorage != null && useLocalStorage.booleanValue()) {
+                offeringName += "-Local";
+            }
+            serviceOffering = _offeringDao.findByName(offeringName);
+            if (serviceOffering == null) {
+                String message = "System service offering " + offeringName + " not found";
+                s_logger.error(message);
+                throw new CloudRuntimeException(message);
+            }
+        }
         SecondaryStorageVmVO secStorageVm =
-            new SecondaryStorageVmVO(id, _serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
-                systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), role, _serviceOffering.getOfferHA());
+            new SecondaryStorageVmVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId,
+                systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), role, serviceOffering.getOfferHA());
         secStorageVm.setDynamicallyScalable(template.isDynamicallyScalable());
         secStorageVm = _secStorageVmDao.persist(secStorageVm);
         try {
-            _itMgr.allocate(name, template, _serviceOffering, networks, plan, null);
+            _itMgr.allocate(name, template, serviceOffering, networks, plan, null);
             secStorageVm = _secStorageVmDao.findById(secStorageVm.getId());
         } catch (InsufficientCapacityException e) {
             s_logger.warn("InsufficientCapacity", e);
@@ -763,14 +776,19 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
                 return false;
             }
 
-            List<Pair<Long, Integer>> l = _storagePoolHostDao.getDatacenterStoragePoolHostInfo(dataCenterId, !_useLocalStorage);
+            boolean useLocalStorage = false;
+            Boolean useLocal = ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId);
+            if (useLocal != null) {
+                useLocalStorage = useLocal.booleanValue();
+            }
+            List<Pair<Long, Integer>> l = _storagePoolHostDao.getDatacenterStoragePoolHostInfo(dataCenterId, !useLocalStorage);
             if (l != null && l.size() > 0 && l.get(0).second().intValue() > 0) {
                 return true;
             } else {
                 if (s_logger.isDebugEnabled()) {
                     s_logger.debug("Primary storage is not ready, wait until it is ready to launch secondary storage vm. dcId: " + dataCenterId +
-                        " system.vm.use.local.storage: " + _useLocalStorage +
-                        "If you want to use local storage to start ssvm, need to set system.vm.use.local.storage to true");
+                        ", " + ConfigurationManagerImpl.SystemVMUseLocalStorage.key() + ": " + useLocalStorage + ". " +
+                        "If you want to use local storage to start SSVM, need to set " + ConfigurationManagerImpl.SystemVMUseLocalStorage.key() + " to true");
                 }
             }
 
@@ -872,18 +890,14 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar
             }
         }
 
-        if(_serviceOffering == null || !_serviceOffering.getSystemUse()){
+        if (_serviceOffering == null || !_serviceOffering.getSystemUse()) {
             int ramSize = NumbersUtil.parseInt(_configDao.getValue("ssvm.ram.size"), DEFAULT_SS_VM_RAMSIZE);
             int cpuFreq = NumbersUtil.parseInt(_configDao.getValue("ssvm.cpu.mhz"), DEFAULT_SS_VM_CPUMHZ);
-            _useLocalStorage = Boolean.parseBoolean(configs.get(DataCenter.SystemVMUseLocalStorageCK));
-            _serviceOffering =
-                new ServiceOfferingVO("System Offering For Secondary Storage VM", 1, ramSize, cpuFreq, null, null, false, null,
-                        Storage.ProvisioningType.THIN,  _useLocalStorage, true, null, true, VirtualMachine.Type.SecondaryStorageVm, true);
-            _serviceOffering.setUniqueName(ServiceOffering.ssvmDefaultOffUniqueName);
-            _serviceOffering = _offeringDao.persistSystemServiceOffering(_serviceOffering);
-
+            List<ServiceOfferingVO> offerings = _offeringDao.createSystemServiceOfferings("System Offering For Secondary Storage VM",
+                    ServiceOffering.ssvmDefaultOffUniqueName, 1, ramSize, cpuFreq, null, null, false, null,
+                    Storage.ProvisioningType.THIN, true, null, true, VirtualMachine.Type.SecondaryStorageVm, true);
             // this can sometimes happen, if DB is manually or programmatically manipulated
-            if (_serviceOffering == null) {
+            if (offerings == null || offerings.size() < 2) {
                 String msg = "Data integrity problem : System Offering For Secondary Storage VM has been removed?";
                 s_logger.error(msg);
                 throw new ConfigurationException(msg);


[40/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Fixing the testGetHostStatsCommand test under LibvirtComputingResourceTest. - Removed the expected value from the Test annotation - Mocking the bash path in order to avoid environment/OS issues

Fixing typo on LibvirtRequestWrapper
  - Replace linbvirtCommands by libvirtCommands on LibvirtRequestWrapper

Signed-off-by: Rohit Yadav <ro...@shapeblue.com>

This closes #255


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/0cdb4b61
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/0cdb4b61
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/0cdb4b61

Branch: refs/heads/CLOUDSTACK-8301
Commit: 0cdb4b610865fa5493cc79e9c9ef310bdf09ccaf
Parents: 9d8a62d
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Mon May 18 14:30:36 2015 +0200
Committer: Rohit Yadav <ro...@shapeblue.com>
Committed: Mon May 18 20:07:02 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  |   2 +
 .../LibvirtGetHostStatsCommandWrapper.java      |  10 +-
 .../resource/wrapper/LibvirtRequestWrapper.java | 120 +++++++++----------
 .../wrapper/LibvirtUtilitiesHelper.java         |   4 +
 .../resource/LibvirtComputingResourceTest.java  |  11 +-
 5 files changed, 83 insertions(+), 64 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cdb4b61/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index a04074b..995a8cf 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -194,6 +194,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
     public static final String SSHPRVKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.cloud";
     public static final String SSHPUBKEYPATH = SSHKEYSPATH + File.separator + "id_rsa.pub.cloud";
 
+    public static final String BASH_SCRIPT_PATH = "/bin/bash";
+
     private String _mountPoint = "/mnt";
     private StorageLayer _storage;
     private KVMStoragePoolManager _storagePoolMgr;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cdb4b61/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetHostStatsCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetHostStatsCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetHostStatsCommandWrapper.java
index ba9ba18..45713cb 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetHostStatsCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtGetHostStatsCommandWrapper.java
@@ -37,7 +37,11 @@ public final class LibvirtGetHostStatsCommandWrapper extends CommandWrapper<GetH
 
     @Override
     public Answer execute(final GetHostStatsCommand command, final LibvirtComputingResource libvirtComputingResource) {
-        final Script cpuScript = new Script("/bin/bash", s_logger);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
+        final String bashScriptPath = libvirtUtilitiesHelper.retrieveBashScriptPath();
+
+
+        final Script cpuScript = new Script(bashScriptPath, s_logger);
         cpuScript.add("-c");
         cpuScript.add("idle=$(top -b -n 1| awk -F, '/^[%]*[Cc]pu/{$0=$4; gsub(/[^0-9.,]+/,\"\"); print }'); echo $idle");
 
@@ -50,7 +54,7 @@ public final class LibvirtGetHostStatsCommandWrapper extends CommandWrapper<GetH
         final double cpuUtil = 100.0D - Double.parseDouble(parser.getLine());
 
         long freeMem = 0;
-        final Script memScript = new Script("/bin/bash", s_logger);
+        final Script memScript = new Script(bashScriptPath, s_logger);
         memScript.add("-c");
         memScript.add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
         final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
@@ -61,7 +65,7 @@ public final class LibvirtGetHostStatsCommandWrapper extends CommandWrapper<GetH
         }
         freeMem = Long.parseLong(Memparser.getLine());
 
-        final Script totalMem = new Script("/bin/bash", s_logger);
+        final Script totalMem = new Script(bashScriptPath, s_logger);
         totalMem.add("-c");
         totalMem.add("free|grep Mem:|awk '{print $2}'");
         final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cdb4b61/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index b181426..9f157eb 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -99,66 +99,66 @@ public class LibvirtRequestWrapper extends RequestWrapper {
     @SuppressWarnings("rawtypes")
     private void init() {
         // LibvirtComputingResource commands
-        final Hashtable<Class<? extends Command>, CommandWrapper> linbvirtCommands = new Hashtable<Class<? extends Command>, CommandWrapper>();
-
-        linbvirtCommands.put(StopCommand.class, new LibvirtStopCommandWrapper());
-        linbvirtCommands.put(GetVmStatsCommand.class, new LibvirtGetVmStatsCommandWrapper());
-        linbvirtCommands.put(GetVmDiskStatsCommand.class, new LibvirtGetVmDiskStatsCommandWrapper());
-        linbvirtCommands.put(RebootRouterCommand.class, new LibvirtRebootRouterCommandWrapper());
-        linbvirtCommands.put(RebootCommand.class, new LibvirtRebootCommandWrapper());
-        linbvirtCommands.put(GetHostStatsCommand.class, new LibvirtGetHostStatsCommandWrapper());
-        linbvirtCommands.put(CheckHealthCommand.class, new LibvirtCheckHealthCommandWrapper());
-        linbvirtCommands.put(PrepareForMigrationCommand.class, new LibvirtPrepareForMigrationCommandWrapper());
-        linbvirtCommands.put(MigrateCommand.class, new LibvirtMigrateCommandWrapper());
-        linbvirtCommands.put(PingTestCommand.class, new LibvirtPingTestCommandWrapper());
-        linbvirtCommands.put(CheckVirtualMachineCommand.class, new LibvirtCheckVirtualMachineCommandWrapper());
-        linbvirtCommands.put(ReadyCommand.class, new LibvirtReadyCommandWrapper());
-        linbvirtCommands.put(AttachIsoCommand.class, new LibvirtAttachIsoCommandWrapper());
-        linbvirtCommands.put(AttachVolumeCommand.class, new LibvirtAttachVolumeCommandWrapper());
-        linbvirtCommands.put(WatchConsoleProxyLoadCommand.class, new LibvirtWatchConsoleProxyLoadCommandWrapper());
-        linbvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
-        linbvirtCommands.put(GetVncPortCommand.class, new LibvirtGetVncPortCommandWrapper());
-        linbvirtCommands.put(ModifySshKeysCommand.class, new LibvirtModifySshKeysCommandWrapper());
-        linbvirtCommands.put(MaintainCommand.class, new LibvirtMaintainCommandWrapper());
-        linbvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
-        linbvirtCommands.put(DestroyCommand.class, new LibvirtDestroyCommandWrapper());
-        linbvirtCommands.put(PrimaryStorageDownloadCommand.class, new LibvirtPrimaryStorageDownloadCommandWrapper());
-        linbvirtCommands.put(GetStorageStatsCommand.class, new LibvirtGetStorageStatsCommandWrapper());
-        linbvirtCommands.put(UpgradeSnapshotCommand.class, new LibvirtUpgradeSnapshotCommandWrapper());
-        linbvirtCommands.put(DeleteStoragePoolCommand.class, new LibvirtDeleteStoragePoolCommandWrapper());
-        linbvirtCommands.put(OvsSetupBridgeCommand.class, new LibvirtOvsSetupBridgeCommandWrapper());
-        linbvirtCommands.put(OvsDestroyBridgeCommand.class, new LibvirtOvsDestroyBridgeCommandWrapper());
-        linbvirtCommands.put(OvsFetchInterfaceCommand.class, new LibvirtOvsFetchInterfaceCommandWrapper());
-        linbvirtCommands.put(OvsVpcPhysicalTopologyConfigCommand.class, new LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper());
-        linbvirtCommands.put(OvsVpcRoutingPolicyConfigCommand.class, new LibvirtOvsVpcRoutingPolicyConfigCommandWrapper());
-        linbvirtCommands.put(CreateStoragePoolCommand.class, new LibvirtCreateStoragePoolCommandWrapper());
-        linbvirtCommands.put(ModifyStoragePoolCommand.class, new LibvirtModifyStoragePoolCommandWrapper());
-        linbvirtCommands.put(CleanupNetworkRulesCmd.class, new LibvirtCleanupNetworkRulesCommandWrapper());
-        linbvirtCommands.put(NetworkRulesVmSecondaryIpCommand.class, new LibvirtNetworkRulesVmSecondaryIpCommandWrapper());
-        linbvirtCommands.put(NetworkRulesSystemVmCommand.class, new LibvirtNetworkRulesSystemVmCommandWrapper());
-        linbvirtCommands.put(CheckSshCommand.class, new LibvirtCheckSshCommandWrapper());
-        linbvirtCommands.put(CheckNetworkCommand.class, new LibvirtCheckNetworkCommandWrapper());
-        linbvirtCommands.put(OvsDestroyTunnelCommand.class, new LibvirtOvsDestroyTunnelCommandWrapper());
-        linbvirtCommands.put(CheckOnHostCommand.class, new LibvirtCheckOnHostCommandWrapper());
-        linbvirtCommands.put(OvsCreateTunnelCommand.class, new LibvirtOvsCreateTunnelCommandWrapper());
-        linbvirtCommands.put(CreateVolumeFromSnapshotCommand.class, new LibvirtCreateVolumeFromSnapshotCommandWrapper());
-        linbvirtCommands.put(FenceCommand.class, new LibvirtFenceCommandWrapper());
-        linbvirtCommands.put(SecurityGroupRulesCmd.class, new LibvirtSecurityGroupRulesCommandWrapper());
-        linbvirtCommands.put(PlugNicCommand.class, new LibvirtPlugNicCommandWrapper());
-        linbvirtCommands.put(UnPlugNicCommand.class, new LibvirtUnPlugNicCommandWrapper());
-        linbvirtCommands.put(NetworkUsageCommand.class, new LibvirtNetworkUsageCommandWrapper());
-        linbvirtCommands.put(CreatePrivateTemplateFromVolumeCommand.class, new LibvirtCreatePrivateTemplateFromVolumeCommandWrapper());
-        linbvirtCommands.put(ManageSnapshotCommand.class, new LibvirtManageSnapshotCommandWrapper());
-        linbvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
-        linbvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
-        linbvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
-        linbvirtCommands.put(PvlanSetupCommand.class, new LibvirtPvlanSetupCommandWrapper());
-        linbvirtCommands.put(ResizeVolumeCommand.class, new LibvirtResizeVolumeCommandWrapper());
-        linbvirtCommands.put(NetworkElementCommand.class, new LibvirtNetworkElementCommandWrapper());
-        linbvirtCommands.put(StorageSubSystemCommand.class, new LibvirtStorageSubSystemCommandWrapper());
-        linbvirtCommands.put(StartCommand.class, new LibvirtStartCommandWrapper());
-
-        resources.put(LibvirtComputingResource.class, linbvirtCommands);
+        final Hashtable<Class<? extends Command>, CommandWrapper> libvirtCommands = new Hashtable<Class<? extends Command>, CommandWrapper>();
+
+        libvirtCommands.put(StopCommand.class, new LibvirtStopCommandWrapper());
+        libvirtCommands.put(GetVmStatsCommand.class, new LibvirtGetVmStatsCommandWrapper());
+        libvirtCommands.put(GetVmDiskStatsCommand.class, new LibvirtGetVmDiskStatsCommandWrapper());
+        libvirtCommands.put(RebootRouterCommand.class, new LibvirtRebootRouterCommandWrapper());
+        libvirtCommands.put(RebootCommand.class, new LibvirtRebootCommandWrapper());
+        libvirtCommands.put(GetHostStatsCommand.class, new LibvirtGetHostStatsCommandWrapper());
+        libvirtCommands.put(CheckHealthCommand.class, new LibvirtCheckHealthCommandWrapper());
+        libvirtCommands.put(PrepareForMigrationCommand.class, new LibvirtPrepareForMigrationCommandWrapper());
+        libvirtCommands.put(MigrateCommand.class, new LibvirtMigrateCommandWrapper());
+        libvirtCommands.put(PingTestCommand.class, new LibvirtPingTestCommandWrapper());
+        libvirtCommands.put(CheckVirtualMachineCommand.class, new LibvirtCheckVirtualMachineCommandWrapper());
+        libvirtCommands.put(ReadyCommand.class, new LibvirtReadyCommandWrapper());
+        libvirtCommands.put(AttachIsoCommand.class, new LibvirtAttachIsoCommandWrapper());
+        libvirtCommands.put(AttachVolumeCommand.class, new LibvirtAttachVolumeCommandWrapper());
+        libvirtCommands.put(WatchConsoleProxyLoadCommand.class, new LibvirtWatchConsoleProxyLoadCommandWrapper());
+        libvirtCommands.put(CheckConsoleProxyLoadCommand.class, new LibvirtCheckConsoleProxyLoadCommandWrapper());
+        libvirtCommands.put(GetVncPortCommand.class, new LibvirtGetVncPortCommandWrapper());
+        libvirtCommands.put(ModifySshKeysCommand.class, new LibvirtModifySshKeysCommandWrapper());
+        libvirtCommands.put(MaintainCommand.class, new LibvirtMaintainCommandWrapper());
+        libvirtCommands.put(CreateCommand.class, new LibvirtCreateCommandWrapper());
+        libvirtCommands.put(DestroyCommand.class, new LibvirtDestroyCommandWrapper());
+        libvirtCommands.put(PrimaryStorageDownloadCommand.class, new LibvirtPrimaryStorageDownloadCommandWrapper());
+        libvirtCommands.put(GetStorageStatsCommand.class, new LibvirtGetStorageStatsCommandWrapper());
+        libvirtCommands.put(UpgradeSnapshotCommand.class, new LibvirtUpgradeSnapshotCommandWrapper());
+        libvirtCommands.put(DeleteStoragePoolCommand.class, new LibvirtDeleteStoragePoolCommandWrapper());
+        libvirtCommands.put(OvsSetupBridgeCommand.class, new LibvirtOvsSetupBridgeCommandWrapper());
+        libvirtCommands.put(OvsDestroyBridgeCommand.class, new LibvirtOvsDestroyBridgeCommandWrapper());
+        libvirtCommands.put(OvsFetchInterfaceCommand.class, new LibvirtOvsFetchInterfaceCommandWrapper());
+        libvirtCommands.put(OvsVpcPhysicalTopologyConfigCommand.class, new LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper());
+        libvirtCommands.put(OvsVpcRoutingPolicyConfigCommand.class, new LibvirtOvsVpcRoutingPolicyConfigCommandWrapper());
+        libvirtCommands.put(CreateStoragePoolCommand.class, new LibvirtCreateStoragePoolCommandWrapper());
+        libvirtCommands.put(ModifyStoragePoolCommand.class, new LibvirtModifyStoragePoolCommandWrapper());
+        libvirtCommands.put(CleanupNetworkRulesCmd.class, new LibvirtCleanupNetworkRulesCommandWrapper());
+        libvirtCommands.put(NetworkRulesVmSecondaryIpCommand.class, new LibvirtNetworkRulesVmSecondaryIpCommandWrapper());
+        libvirtCommands.put(NetworkRulesSystemVmCommand.class, new LibvirtNetworkRulesSystemVmCommandWrapper());
+        libvirtCommands.put(CheckSshCommand.class, new LibvirtCheckSshCommandWrapper());
+        libvirtCommands.put(CheckNetworkCommand.class, new LibvirtCheckNetworkCommandWrapper());
+        libvirtCommands.put(OvsDestroyTunnelCommand.class, new LibvirtOvsDestroyTunnelCommandWrapper());
+        libvirtCommands.put(CheckOnHostCommand.class, new LibvirtCheckOnHostCommandWrapper());
+        libvirtCommands.put(OvsCreateTunnelCommand.class, new LibvirtOvsCreateTunnelCommandWrapper());
+        libvirtCommands.put(CreateVolumeFromSnapshotCommand.class, new LibvirtCreateVolumeFromSnapshotCommandWrapper());
+        libvirtCommands.put(FenceCommand.class, new LibvirtFenceCommandWrapper());
+        libvirtCommands.put(SecurityGroupRulesCmd.class, new LibvirtSecurityGroupRulesCommandWrapper());
+        libvirtCommands.put(PlugNicCommand.class, new LibvirtPlugNicCommandWrapper());
+        libvirtCommands.put(UnPlugNicCommand.class, new LibvirtUnPlugNicCommandWrapper());
+        libvirtCommands.put(NetworkUsageCommand.class, new LibvirtNetworkUsageCommandWrapper());
+        libvirtCommands.put(CreatePrivateTemplateFromVolumeCommand.class, new LibvirtCreatePrivateTemplateFromVolumeCommandWrapper());
+        libvirtCommands.put(ManageSnapshotCommand.class, new LibvirtManageSnapshotCommandWrapper());
+        libvirtCommands.put(BackupSnapshotCommand.class, new LibvirtBackupSnapshotCommandWrapper());
+        libvirtCommands.put(CreatePrivateTemplateFromSnapshotCommand.class, new LibvirtCreatePrivateTemplateFromSnapshotCommandWrapper());
+        libvirtCommands.put(CopyVolumeCommand.class, new LibvirtCopyVolumeCommandWrapper());
+        libvirtCommands.put(PvlanSetupCommand.class, new LibvirtPvlanSetupCommandWrapper());
+        libvirtCommands.put(ResizeVolumeCommand.class, new LibvirtResizeVolumeCommandWrapper());
+        libvirtCommands.put(NetworkElementCommand.class, new LibvirtNetworkElementCommandWrapper());
+        libvirtCommands.put(StorageSubSystemCommand.class, new LibvirtStorageSubSystemCommandWrapper());
+        libvirtCommands.put(StartCommand.class, new LibvirtStartCommandWrapper());
+
+        resources.put(LibvirtComputingResource.class, libvirtCommands);
     }
 
     public static LibvirtRequestWrapper getInstance() {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cdb4b61/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
index dfff12d..98bf642 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -82,4 +82,8 @@ public class LibvirtUtilitiesHelper {
     public String retrieveSshPrvKeyPath() {
         return LibvirtComputingResource.SSHPRVKEYPATH;
     }
+
+    public String retrieveBashScriptPath() {
+        return LibvirtComputingResource.BASH_SCRIPT_PATH;
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/0cdb4b61/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 36227a5..7f378a3 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -916,19 +916,28 @@ public class LibvirtComputingResourceTest {
         }
     }
 
-    @Test(expected = NumberFormatException.class)
+    @Test
     public void testGetHostStatsCommand() {
         // A bit difficult to test due to the logger being passed and the parser itself relying on the connection.
         // Have to spend some more time afterwards in order to refactor the wrapper itself.
 
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final String bashScriptPath = "/path";
+
         final String uuid = "e8d6b4d0-bc6d-4613-b8bb-cb9e0600f3c6";
         final GetHostStatsCommand command = new GetHostStatsCommand(uuid, "summer", 1l);
 
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        when(libvirtUtilitiesHelper.retrieveBashScriptPath()).thenReturn(bashScriptPath);
+
         final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        verify(libvirtUtilitiesHelper, times(1)).retrieveBashScriptPath();
     }
 
     @Test


[05/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Fixing assertion on the tests that are execting exceptions


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/08a9523d
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/08a9523d
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/08a9523d

Branch: refs/heads/CLOUDSTACK-8301
Commit: 08a9523dcdd5b4d736c4ef29b9ea93daa2b6e400
Parents: 40886b3
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Thu Apr 23 14:46:09 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:20:43 2015 +0200

----------------------------------------------------------------------
 .../hypervisor/kvm/resource/LibvirtComputingResourceTest.java    | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08a9523d/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index e274485..75ce221 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -1055,7 +1055,7 @@ public class LibvirtComputingResourceTest {
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
-        assertTrue(answer.getResult());
+        assertFalse(answer.getResult());
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {
@@ -1100,7 +1100,7 @@ public class LibvirtComputingResourceTest {
         assertNotNull(wrapper);
 
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
-        assertTrue(answer.getResult());
+        assertFalse(answer.getResult());
 
         verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
         try {


[14/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding 7 new command wrappers
  - 10 unit tests added
  - KVM hypervisor plugin with 14.8% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/5499eecd
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/5499eecd
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/5499eecd

Branch: refs/heads/CLOUDSTACK-8301
Commit: 5499eecd33d93c88ed9c0b4828deb0d11ac0a66e
Parents: 4887ce7
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Fri May 1 14:43:30 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:12 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 128 +----------
 ...ibvirtCleanupNetworkRulesCommandWrapper.java |  34 +++
 .../LibvirtCreateStoragePoolCommandWrapper.java |  33 +++
 .../LibvirtModifyStoragePoolCommandWrapper.java |  51 +++++
 ...NetworkRulesVmSecondaryIpCommandWrapper.java |  49 +++++
 .../LibvirtOvsFetchInterfaceCommandWrapper.java |  53 +++++
 ...VpcPhysicalTopologyConfigCommandWrapper.java |  53 +++++
 ...OvsVpcRoutingPolicyConfigCommandWrapper.java |  53 +++++
 .../resource/wrapper/LibvirtRequestWrapper.java |  14 ++
 .../resource/LibvirtComputingResourceTest.java  | 212 +++++++++++++++++++
 10 files changed, 558 insertions(+), 122 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index cc73e65..75c9663 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -88,11 +88,9 @@ import com.cloud.agent.api.BackupSnapshotCommand;
 import com.cloud.agent.api.CheckNetworkAnswer;
 import com.cloud.agent.api.CheckNetworkCommand;
 import com.cloud.agent.api.CheckOnHostCommand;
-import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
 import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
 import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
-import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer;
 import com.cloud.agent.api.CreateVolumeFromSnapshotCommand;
 import com.cloud.agent.api.FenceAnswer;
@@ -100,19 +98,12 @@ import com.cloud.agent.api.FenceCommand;
 import com.cloud.agent.api.HostVmStateReportEntry;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
-import com.cloud.agent.api.ModifyStoragePoolAnswer;
-import com.cloud.agent.api.ModifyStoragePoolCommand;
 import com.cloud.agent.api.NetworkRulesSystemVmCommand;
-import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
 import com.cloud.agent.api.NetworkUsageAnswer;
 import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.OvsCreateTunnelAnswer;
 import com.cloud.agent.api.OvsCreateTunnelCommand;
 import com.cloud.agent.api.OvsDestroyTunnelCommand;
-import com.cloud.agent.api.OvsFetchInterfaceAnswer;
-import com.cloud.agent.api.OvsFetchInterfaceCommand;
-import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
-import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
@@ -202,7 +193,6 @@ import com.cloud.storage.template.Processor;
 import com.cloud.storage.template.Processor.FormatInfo;
 import com.cloud.storage.template.QCOW2Processor;
 import com.cloud.storage.template.TemplateLocation;
-import com.cloud.storage.template.TemplateProp;
 import com.cloud.utils.ExecutionResult;
 import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
@@ -443,6 +433,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return _timeout;
     }
 
+    public String getOvsTunnelPath() {
+        return _ovsTunnelPath;
+    }
+
     private static final class KeyValueInterpreter extends OutputInterpreter {
         private final Map<String, String> map = new HashMap<String, String>();
 
@@ -1300,10 +1294,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((CreateVolumeFromSnapshotCommand)cmd);
             } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) {
                 return execute((CreatePrivateTemplateFromSnapshotCommand)cmd);
-            } else if (cmd instanceof CreateStoragePoolCommand) {
-                return execute((CreateStoragePoolCommand)cmd);
-            } else if (cmd instanceof ModifyStoragePoolCommand) {
-                return execute((ModifyStoragePoolCommand)cmd);
             } else if (cmd instanceof SecurityGroupRulesCmd) {
                 return execute((SecurityGroupRulesCmd)cmd);
             } else if (cmd instanceof FenceCommand) {
@@ -1322,32 +1312,22 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
                 return execute((NetworkUsageCommand)cmd);
             } else if (cmd instanceof NetworkRulesSystemVmCommand) {
                 return execute((NetworkRulesSystemVmCommand)cmd);
-            } else if (cmd instanceof CleanupNetworkRulesCmd) {
-                return execute((CleanupNetworkRulesCmd)cmd);
             } else if (cmd instanceof CopyVolumeCommand) {
                 return execute((CopyVolumeCommand)cmd);
             } else if (cmd instanceof ResizeVolumeCommand) {
                 return execute((ResizeVolumeCommand)cmd);
             } else if (cmd instanceof CheckNetworkCommand) {
                 return execute((CheckNetworkCommand)cmd);
-            } else if (cmd instanceof NetworkRulesVmSecondaryIpCommand) {
-                return execute((NetworkRulesVmSecondaryIpCommand)cmd);
             } else if (cmd instanceof StorageSubSystemCommand) {
                 return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd);
             } else if (cmd instanceof PvlanSetupCommand) {
                 return execute((PvlanSetupCommand)cmd);
             } else if (cmd instanceof CheckOnHostCommand) {
                 return execute((CheckOnHostCommand)cmd);
-            } else if (cmd instanceof OvsFetchInterfaceCommand) {
-                return execute((OvsFetchInterfaceCommand)cmd);
             } else if (cmd instanceof OvsCreateTunnelCommand) {
                 return execute((OvsCreateTunnelCommand)cmd);
             } else if (cmd instanceof OvsDestroyTunnelCommand) {
                 return execute((OvsDestroyTunnelCommand)cmd);
-            } else if (cmd instanceof OvsVpcPhysicalTopologyConfigCommand) {
-                return execute((OvsVpcPhysicalTopologyConfigCommand) cmd);
-            } else if (cmd instanceof OvsVpcRoutingPolicyConfigCommand) {
-                return execute((OvsVpcRoutingPolicyConfigCommand) cmd);
             } else {
                 s_logger.warn("Unsupported command ");
                 return Answer.createUnsupportedCommandAnswer(cmd);
@@ -1357,65 +1337,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private OvsFetchInterfaceAnswer execute(final OvsFetchInterfaceCommand cmd) {
-        final String label = cmd.getLabel();
-        s_logger.debug("Will look for network with name-label:" + label);
-        try {
-            final String ipadd = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'");
-            final String mask = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f4");
-            final String mac = Script.runSimpleBashScript("ifconfig " + label + " | grep HWaddr | awk -F \" \" '{print $5}'");
-            return new OvsFetchInterfaceAnswer(cmd, true, "Interface " + label
-                    + " retrieved successfully", ipadd, mask, mac);
-
-        } catch (final Exception e) {
-            s_logger.warn("Caught execption when fetching interface", e);
-            return new OvsFetchInterfaceAnswer(cmd, false, "EXCEPTION:"
-                    + e.getMessage());
-        }
-
-    }
-
-    public Answer execute(final OvsVpcPhysicalTopologyConfigCommand cmd) {
-
-        final String bridge = cmd.getBridgeName();
-        try {
-            final Script command = new Script(_ovsTunnelPath, _timeout, s_logger);
-            command.add("configure_ovs_bridge_for_network_topology");
-            command.add("--bridge", bridge);
-            command.add("--config", cmd.getVpcConfigInJson());
-
-            final String result = command.execute();
-            if (result.equalsIgnoreCase("SUCCESS")) {
-                return new Answer(cmd, true, result);
-            } else {
-                return new Answer(cmd, false, result);
-            }
-        } catch  (final Exception e) {
-            s_logger.warn("caught exception while updating host with latest routing polcies", e);
-            return new Answer(cmd, false, e.getMessage());
-        }
-    }
-
-    public Answer execute(final OvsVpcRoutingPolicyConfigCommand cmd) {
-
-        try {
-            final Script command = new Script(_ovsTunnelPath, _timeout, s_logger);
-            command.add("configure_ovs_bridge_for_routing_policies");
-            command.add("--bridge", cmd.getBridgeName());
-            command.add("--config", cmd.getVpcConfigInJson());
-
-            final String result = command.execute();
-            if (result.equalsIgnoreCase("SUCCESS")) {
-                return new Answer(cmd, true, result);
-            } else {
-                return new Answer(cmd, false, result);
-            }
-        } catch  (final Exception e) {
-            s_logger.warn("caught exception while updating host with latest VPC topology", e);
-            return new Answer(cmd, false, e.getMessage());
-        }
-    }
-
     public synchronized boolean destroyTunnelNetwork(final String bridge) {
         findOrCreateTunnelNetwork(bridge);
 
@@ -2642,24 +2563,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected Answer execute(final CreateStoragePoolCommand cmd) {
-        return new Answer(cmd, true, "success");
-    }
-
-    protected Answer execute(final ModifyStoragePoolCommand cmd) {
-        final 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");
-        }
-
-        final Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>();
-        final ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, storagepool.getCapacity(), storagepool.getAvailable(), tInfo);
-
-        return answer;
-    }
-
     private Answer execute(final SecurityGroupRulesCmd cmd) {
         String vif = null;
         String brname = null;
@@ -2686,11 +2589,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    private Answer execute(final CleanupNetworkRulesCmd cmd) {
-        final boolean result = cleanup_rules();
-        return new Answer(cmd, result, "");
-    }
-
     protected PowerState convertToPowerState(final DomainState ps) {
         final PowerState state = s_powerStatesTable.get(ps);
         return state == null ? PowerState.PowerUnknown : state;
@@ -4386,7 +4284,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private boolean network_rules_vmSecondaryIp(final Connect conn, final String vmName, final String secIp, final String action) {
+    public boolean configureNetworkRulesVMSecondaryIP(final Connect conn, final String vmName, final String secIp, final String action) {
 
         if (!_canBridgeFirewall) {
             return false;
@@ -4405,7 +4303,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    private boolean cleanup_rules() {
+    public boolean cleanupRules() {
         if (!_canBridgeFirewall) {
             return false;
         }
@@ -4486,20 +4384,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return new Answer(cmd, success, "");
     }
 
-    private Answer execute(final NetworkRulesVmSecondaryIpCommand cmd) {
-        boolean success = false;
-        Connect conn;
-        try {
-            conn = LibvirtConnection.getConnectionByVmName(cmd.getVmName());
-            success = network_rules_vmSecondaryIp(conn, cmd.getVmName(), cmd.getVmSecIp(), cmd.getAction());
-        } catch (final LibvirtException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-
-        return new Answer(cmd, success, "");
-    }
-
     private String prettyVersion(final long version) {
         final long major = version / 1000000;
         final long minor = version % 1000000 / 1000;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCleanupNetworkRulesCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCleanupNetworkRulesCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCleanupNetworkRulesCommandWrapper.java
new file mode 100644
index 0000000..59c353b
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCleanupNetworkRulesCommandWrapper.java
@@ -0,0 +1,34 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CleanupNetworkRulesCmd;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtCleanupNetworkRulesCommandWrapper extends CommandWrapper<CleanupNetworkRulesCmd, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CleanupNetworkRulesCmd command, final LibvirtComputingResource libvirtComputingResource) {
+        final boolean result = libvirtComputingResource.cleanupRules();
+        return new Answer(command, result, "");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateStoragePoolCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateStoragePoolCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateStoragePoolCommandWrapper.java
new file mode 100644
index 0000000..e233b4f
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtCreateStoragePoolCommandWrapper.java
@@ -0,0 +1,33 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.CreateStoragePoolCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtCreateStoragePoolCommandWrapper extends CommandWrapper<CreateStoragePoolCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final CreateStoragePoolCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        return new Answer(command, true, "success");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifyStoragePoolCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifyStoragePoolCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifyStoragePoolCommandWrapper.java
new file mode 100644
index 0000000..34d12ba
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtModifyStoragePoolCommandWrapper.java
@@ -0,0 +1,51 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.ModifyStoragePoolAnswer;
+import com.cloud.agent.api.ModifyStoragePoolCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.storage.template.TemplateProp;
+
+public final class LibvirtModifyStoragePoolCommandWrapper extends CommandWrapper<ModifyStoragePoolCommand, Answer, LibvirtComputingResource> {
+
+    @Override
+    public Answer execute(final ModifyStoragePoolCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+        final KVMStoragePool storagepool =
+                storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool()
+                        .getUserInfo(), command.getPool().getType());
+        if (storagepool == null) {
+            return new Answer(command, false, " Failed to create storage pool");
+        }
+
+        final Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>();
+        final ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(command, storagepool.getCapacity(), storagepool.getAvailable(), tInfo);
+
+        return answer;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
new file mode 100644
index 0000000..6f15345
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtNetworkRulesVmSecondaryIpCommandWrapper.java
@@ -0,0 +1,49 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+
+public final class LibvirtNetworkRulesVmSecondaryIpCommandWrapper extends CommandWrapper<NetworkRulesVmSecondaryIpCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.class);
+
+    @Override
+    public Answer execute(final NetworkRulesVmSecondaryIpCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        boolean result = false;
+        try {
+            final LibvirtConnectionWrapper libvirtConnectionWrapper = libvirtComputingResource.getLibvirtConnectionWrapper();
+
+            final Connect conn = libvirtConnectionWrapper.getConnectionByVmName(command.getVmName());
+            result = libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction());
+        } catch (final LibvirtException e) {
+            s_logger.debug("Could not configure VM secondary IP! => " + e.getLocalizedMessage());
+        }
+
+        return new Answer(command, result, "");
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsFetchInterfaceCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsFetchInterfaceCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsFetchInterfaceCommandWrapper.java
new file mode 100644
index 0000000..e7d0b7e
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsFetchInterfaceCommandWrapper.java
@@ -0,0 +1,53 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsFetchInterfaceAnswer;
+import com.cloud.agent.api.OvsFetchInterfaceCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtOvsFetchInterfaceCommandWrapper extends CommandWrapper<OvsFetchInterfaceCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsFetchInterfaceCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsFetchInterfaceCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        final String label = command.getLabel();
+
+        s_logger.debug("Will look for network with name-label:" + label);
+        try {
+            final String ipadd = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'");
+            final String mask = Script.runSimpleBashScript("ifconfig " + label + " | grep 'inet addr:' | cut -d: -f4");
+            final String mac = Script.runSimpleBashScript("ifconfig " + label + " | grep HWaddr | awk -F \" \" '{print $5}'");
+            return new OvsFetchInterfaceAnswer(command, true, "Interface " + label
+                    + " retrieved successfully", ipadd, mask, mac);
+
+        } catch (final Exception e) {
+            s_logger.warn("Caught execption when fetching interface", e);
+            return new OvsFetchInterfaceAnswer(command, false, "EXCEPTION:"
+                    + e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper.java
new file mode 100644
index 0000000..d1e8651
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper.java
@@ -0,0 +1,53 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper extends CommandWrapper<OvsVpcPhysicalTopologyConfigCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsVpcPhysicalTopologyConfigCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger);
+            scriptCommand.add("configure_ovs_bridge_for_network_topology");
+            scriptCommand.add("--bridge", command.getBridgeName());
+            scriptCommand.add("--config", command.getVpcConfigInJson());
+
+            final String result = scriptCommand.execute();
+            if (result.equalsIgnoreCase("SUCCESS")) {
+                return new Answer(command, true, result);
+            } else {
+                return new Answer(command, false, result);
+            }
+        } catch  (final Exception e) {
+            s_logger.warn("caught exception while updating host with latest routing polcies", e);
+            return new Answer(command, false, e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.java
new file mode 100644
index 0000000..36762ed
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.java
@@ -0,0 +1,53 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.utils.script.Script;
+
+public final class LibvirtOvsVpcRoutingPolicyConfigCommandWrapper extends CommandWrapper<OvsVpcRoutingPolicyConfigCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtOvsVpcRoutingPolicyConfigCommandWrapper.class);
+
+    @Override
+    public Answer execute(final OvsVpcRoutingPolicyConfigCommand command, final LibvirtComputingResource libvirtComputingResource) {
+        try {
+            final Script scriptCommand = new Script(libvirtComputingResource.getOvsTunnelPath(), libvirtComputingResource.getTimeout(), s_logger);
+            scriptCommand.add("configure_ovs_bridge_for_routing_policies");
+            scriptCommand.add("--bridge", command.getBridgeName());
+            scriptCommand.add("--config", command.getVpcConfigInJson());
+
+            final String result = scriptCommand.execute();
+            if (result.equalsIgnoreCase("SUCCESS")) {
+                return new Answer(command, true, result);
+            } else {
+                return new Answer(command, false, result);
+            }
+        } catch  (final Exception e) {
+            s_logger.warn("caught exception while updating host with latest VPC topology", e);
+            return new Answer(command, false, e.getMessage());
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index 05dbe2d..87b4ec2 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -25,7 +25,9 @@ import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
+import com.cloud.agent.api.CleanupNetworkRulesCmd;
 import com.cloud.agent.api.Command;
+import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetStorageStatsCommand;
@@ -35,8 +37,13 @@ import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
+import com.cloud.agent.api.ModifyStoragePoolCommand;
+import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsFetchInterfaceCommand;
 import com.cloud.agent.api.OvsSetupBridgeCommand;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
+import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -98,6 +105,13 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(DeleteStoragePoolCommand.class, new LibvirtDeleteStoragePoolCommandWrapper());
         linbvirtCommands.put(OvsSetupBridgeCommand.class, new LibvirtOvsSetupBridgeCommandWrapper());
         linbvirtCommands.put(OvsDestroyBridgeCommand.class, new LibvirtOvsDestroyBridgeCommandWrapper());
+        linbvirtCommands.put(OvsFetchInterfaceCommand.class, new LibvirtOvsFetchInterfaceCommandWrapper());
+        linbvirtCommands.put(OvsVpcPhysicalTopologyConfigCommand.class, new LibvirtOvsVpcPhysicalTopologyConfigCommandWrapper());
+        linbvirtCommands.put(OvsVpcRoutingPolicyConfigCommand.class, new LibvirtOvsVpcRoutingPolicyConfigCommandWrapper());
+        linbvirtCommands.put(CreateStoragePoolCommand.class, new LibvirtCreateStoragePoolCommandWrapper());
+        linbvirtCommands.put(ModifyStoragePoolCommand.class, new LibvirtModifyStoragePoolCommandWrapper());
+        linbvirtCommands.put(CleanupNetworkRulesCmd.class, new LibvirtCleanupNetworkRulesCommandWrapper());
+        linbvirtCommands.put(NetworkRulesVmSecondaryIpCommand.class, new LibvirtNetworkRulesVmSecondaryIpCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/5499eecd/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index b8046f5..8fd1ecf 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -68,6 +68,8 @@ import com.cloud.agent.api.AttachIsoCommand;
 import com.cloud.agent.api.AttachVolumeCommand;
 import com.cloud.agent.api.CheckHealthCommand;
 import com.cloud.agent.api.CheckVirtualMachineCommand;
+import com.cloud.agent.api.CleanupNetworkRulesCmd;
+import com.cloud.agent.api.CreateStoragePoolCommand;
 import com.cloud.agent.api.DeleteStoragePoolCommand;
 import com.cloud.agent.api.GetHostStatsCommand;
 import com.cloud.agent.api.GetStorageStatsCommand;
@@ -77,8 +79,17 @@ import com.cloud.agent.api.GetVncPortCommand;
 import com.cloud.agent.api.MaintainCommand;
 import com.cloud.agent.api.MigrateCommand;
 import com.cloud.agent.api.ModifySshKeysCommand;
+import com.cloud.agent.api.ModifyStoragePoolCommand;
+import com.cloud.agent.api.NetworkRulesVmSecondaryIpCommand;
 import com.cloud.agent.api.OvsDestroyBridgeCommand;
+import com.cloud.agent.api.OvsFetchInterfaceCommand;
 import com.cloud.agent.api.OvsSetupBridgeCommand;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand.Host;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand.Tier;
+import com.cloud.agent.api.OvsVpcPhysicalTopologyConfigCommand.Vm;
+import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand;
+import com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand.Acl;
 import com.cloud.agent.api.PingTestCommand;
 import com.cloud.agent.api.PrepareForMigrationCommand;
 import com.cloud.agent.api.ReadyCommand;
@@ -1995,4 +2006,205 @@ public class LibvirtComputingResourceTest {
 
         verify(libvirtComputingResource, times(1)).destroyTunnelNetwork(command.getBridgeName());
     }
+
+    @Test
+    public void testOvsFetchInterfaceCommand() {
+        final String label = "eth0";
+
+        final OvsFetchInterfaceCommand command = new OvsFetchInterfaceCommand(label);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testOvsVpcPhysicalTopologyConfigCommand() {
+        final Host[] hosts = null;
+        final Tier[] tiers = null;
+        final Vm[] vms = null;
+        final String cidr = null;
+
+        final OvsVpcPhysicalTopologyConfigCommand command = new OvsVpcPhysicalTopologyConfigCommand(hosts, tiers, vms, cidr);
+
+        when(libvirtComputingResource.getOvsTunnelPath()).thenReturn("/path");
+        when(libvirtComputingResource.getTimeout()).thenReturn(0);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getOvsTunnelPath();
+        verify(libvirtComputingResource, times(1)).getTimeout();
+    }
+
+    @Test
+    public void testOvsVpcRoutingPolicyConfigCommand() {
+        final String id = null;
+        final String cidr = null;
+        final Acl[] acls = null;
+        final com.cloud.agent.api.OvsVpcRoutingPolicyConfigCommand.Tier[] tiers = null;
+
+        final OvsVpcRoutingPolicyConfigCommand command = new OvsVpcRoutingPolicyConfigCommand(id, cidr, acls, tiers);
+
+        when(libvirtComputingResource.getOvsTunnelPath()).thenReturn("/path");
+        when(libvirtComputingResource.getTimeout()).thenReturn(0);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getOvsTunnelPath();
+        verify(libvirtComputingResource, times(1)).getTimeout();
+    }
+
+    @Test
+    public void testCreateStoragePoolCommand() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);
+        final CreateStoragePoolCommand command = new CreateStoragePoolCommand(true, pool);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+    }
+
+    @Test
+    public void testModifyStoragePoolCommand() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final ModifyStoragePoolCommand command = new ModifyStoragePoolCommand(true, pool);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool kvmStoragePool = Mockito.mock(KVMStoragePool.class);
+
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool()
+                .getUserInfo(), command.getPool().getType())).thenReturn(kvmStoragePool);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool()
+                .getUserInfo(), command.getPool().getType());
+    }
+
+    @Test
+    public void testModifyStoragePoolCommandFailure() {
+        final StoragePool pool = Mockito.mock(StoragePool.class);;
+        final ModifyStoragePoolCommand command = new ModifyStoragePoolCommand(true, pool);
+
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool()
+                .getUserInfo(), command.getPool().getType())).thenReturn(null);
+
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(storagePoolMgr, times(1)).createStoragePool(command.getPool().getUuid(), command.getPool().getHost(), command.getPool().getPort(), command.getPool().getPath(), command.getPool()
+                .getUserInfo(), command.getPool().getType());
+    }
+
+    @Test
+    public void testCleanupNetworkRulesCmd() {
+        final CleanupNetworkRulesCmd command = new CleanupNetworkRulesCmd(1);
+
+        when(libvirtComputingResource.cleanupRules()).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).cleanupRules();
+    }
+
+    @Test
+    public void testNetworkRulesVmSecondaryIpCommand() {
+        final String vmName = "Test";
+        final String vmMac = "00:00:00:00";
+        final String secondaryIp = "172.168.25.25";
+        final boolean action = true;
+
+        final NetworkRulesVmSecondaryIpCommand command = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, action );
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenReturn(conn);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        when(libvirtComputingResource.configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction())).thenReturn(true);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+        verify(libvirtComputingResource, times(1)).configureNetworkRulesVMSecondaryIP(conn, command.getVmName(), command.getVmSecIp(), command.getAction());
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testNetworkRulesVmSecondaryIpCommandFailure() {
+        final String vmName = "Test";
+        final String vmMac = "00:00:00:00";
+        final String secondaryIp = "172.168.25.25";
+        final boolean action = true;
+
+        final NetworkRulesVmSecondaryIpCommand command = new NetworkRulesVmSecondaryIpCommand(vmName, vmMac, secondaryIp, action );
+
+        final LibvirtConnectionWrapper libvirtConnectionWrapper = Mockito.mock(LibvirtConnectionWrapper.class);
+
+        when(libvirtComputingResource.getLibvirtConnectionWrapper()).thenReturn(libvirtConnectionWrapper);
+        try {
+            when(libvirtConnectionWrapper.getConnectionByVmName(command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        try {
+            verify(libvirtConnectionWrapper, times(1)).getConnectionByVmName(command.getVmName());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+        verify(libvirtComputingResource, times(1)).getLibvirtConnectionWrapper();
+    }
 }
\ No newline at end of file


[26/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
Refactoring the LibvirtComputingResource
  - Adding LibvirtStartCommandWrapper
  - 8 unit tests added
  - KVM hypervisor plugin with 23.2% coverage


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/74ad48db
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/74ad48db
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/74ad48db

Branch: refs/heads/CLOUDSTACK-8301
Commit: 74ad48db55d141f697b6e8235e7ac472d844dd57
Parents: 09656ca
Author: wilderrodrigues <wr...@schubergphilis.com>
Authored: Wed May 6 16:11:49 2015 +0200
Committer: wilderrodrigues <wr...@schubergphilis.com>
Committed: Wed May 6 19:24:16 2015 +0200

----------------------------------------------------------------------
 .../kvm/resource/LibvirtComputingResource.java  | 150 +-----
 .../LibvirtManageSnapshotCommandWrapper.java    |   6 +-
 .../resource/wrapper/LibvirtRequestWrapper.java |   2 +
 .../wrapper/LibvirtStartCommandWrapper.java     | 151 ++++++
 .../wrapper/LibvirtUtilitiesHelper.java         |   4 +
 .../resource/LibvirtComputingResourceTest.java  | 502 +++++++++++++++++++
 6 files changed, 672 insertions(+), 143 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index d7b4b18..a04074b 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -67,8 +67,6 @@ import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingRoutingWithNwGroupsCommand;
 import com.cloud.agent.api.SetupGuestNetworkCommand;
-import com.cloud.agent.api.StartAnswer;
-import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupRoutingCommand;
 import com.cloud.agent.api.StartupStorageCommand;
@@ -118,7 +116,6 @@ import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.hypervisor.kvm.storage.KVMStorageProcessor;
 import com.cloud.network.Networks.BroadcastDomainType;
-import com.cloud.network.Networks.IsolationType;
 import com.cloud.network.Networks.RouterPrivateIpStrategy;
 import com.cloud.network.Networks.TrafficType;
 import com.cloud.resource.ServerResource;
@@ -1173,7 +1170,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return "0".equals(command.execute(null));
     }
 
-    private boolean passCmdLine(final String vmName, final String cmdLine) throws InternalErrorException {
+    public boolean passCmdLine(final String vmName, final String cmdLine) throws InternalErrorException {
         final Script command = new Script(_patchViaSocketPath, 5 * 1000, s_logger);
         String result;
         command.add("-n", vmName);
@@ -1199,7 +1196,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected String startVM(final Connect conn, final String vmName, final String domainXML) throws LibvirtException, InternalErrorException {
+    public String startVM(final Connect conn, final String vmName, final String domainXML) throws LibvirtException, InternalErrorException {
         try {
             /*
                 We create a transient domain here. When this method gets
@@ -1253,19 +1250,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         try {
             return wrapper.execute(cmd, this);
         } catch (final Exception e) {
-            //[TODO] ignore for now, we still need to finish the other commands.
-            //return Answer.createUnsupportedCommandAnswer(cmd);
-        }
-
-        try {
-            if (cmd instanceof StartCommand) {
-                return execute((StartCommand)cmd);
-            } else {
-                s_logger.warn("Unsupported command ");
-                return Answer.createUnsupportedCommandAnswer(cmd);
-            }
-        } catch (final IllegalArgumentException e) {
-            return new Answer(cmd, false, e.getMessage());
+            return Answer.createUnsupportedCommandAnswer(cmd);
         }
     }
 
@@ -1791,7 +1776,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return stats;
     }
 
-    protected void handleVmStartFailure(final Connect conn, final String vmName, final LibvirtVMDef vm) {
+    public void handleVmStartFailure(final Connect conn, final String vmName, final LibvirtVMDef vm) {
         if (vm != null && vm.getDevices() != null) {
             cleanupVMNetworks(conn, vm.getDevices().getInterfaces());
         }
@@ -1814,25 +1799,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return uuid;
     }
 
-    private void getOsVersion() {
-        final String version = Script.runSimpleBashScript("cat /etc/redhat-release | awk '{print $7}'");
-        if (version != null) {
-            final String[] versions = version.split("\\.");
-            if (versions.length == 2) {
-                final String major = versions[0];
-                final String minor = versions[1];
-                try {
-                    final Integer m = Integer.parseInt(major);
-                    final Integer min = Integer.parseInt(minor);
-                    hostOsVersion = new Pair<>(m, min);
-                } catch(final NumberFormatException e) {
-
-                }
-            }
-        }
-    }
-
-    protected LibvirtVMDef createVMFromSpec(final VirtualMachineTO vmTO) {
+    public LibvirtVMDef createVMFromSpec(final VirtualMachineTO vmTO) {
         final LibvirtVMDef vm = new LibvirtVMDef();
         vm.setDomainName(vmTO.getName());
         String uuid = vmTO.getUuid();
@@ -1972,7 +1939,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return vm;
     }
 
-    protected void createVifs(final VirtualMachineTO vmSpec, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
+    public void createVifs(final VirtualMachineTO vmSpec, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
         final NicTO[] nics = vmSpec.getNics();
         final Map <String, String> params = vmSpec.getDetails();
         String nicAdapter = "";
@@ -1988,107 +1955,6 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected StartAnswer execute(final StartCommand cmd) {
-        final VirtualMachineTO vmSpec = cmd.getVirtualMachine();
-        vmSpec.setVncAddr(cmd.getHostIp());
-        final String vmName = vmSpec.getName();
-        LibvirtVMDef vm = null;
-
-        DomainState  state = DomainState.VIR_DOMAIN_SHUTOFF;
-        Connect conn = null;
-        try {
-            final NicTO[] nics = vmSpec.getNics();
-
-            for (final NicTO nic : nics) {
-                if (vmSpec.getType() != VirtualMachine.Type.User) {
-                    nic.setPxeDisable(true);
-                }
-            }
-
-            vm = createVMFromSpec(vmSpec);
-
-            conn = LibvirtConnection.getConnectionByType(vm.getHvsType());
-
-            createVbd(conn, vmSpec, vmName, vm);
-
-            if (!_storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)) {
-                return new StartAnswer(cmd, "Failed to connect physical disks to host");
-            }
-
-            createVifs(vmSpec, vm);
-
-            s_logger.debug("starting " + vmName + ": " + vm.toString());
-            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) {
-                        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:";
-                        }
-                        default_network_rules(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++) {
-                    passCmdLine(vmName, vmSpec.getBootArgs());
-                    //check router is up?
-                    final boolean result = _virtRouterResource.connect(controlIp, 1, 5000);
-                    if (result) {
-                        break;
-                    }
-                }
-            }
-
-            state = DomainState.VIR_DOMAIN_RUNNING;
-            return new StartAnswer(cmd);
-        } catch (final LibvirtException e) {
-            s_logger.warn("LibvirtException ", e);
-            if (conn != null) {
-                handleVmStartFailure(conn, vmName, vm);
-            }
-            return new StartAnswer(cmd, e.getMessage());
-        } catch (final InternalErrorException e) {
-            s_logger.warn("InternalErrorException ", e);
-            if (conn != null) {
-                handleVmStartFailure(conn, vmName, vm);
-            }
-            return new StartAnswer(cmd, e.getMessage());
-        } catch (final URISyntaxException e) {
-            s_logger.warn("URISyntaxException ", e);
-            if (conn != null) {
-                handleVmStartFailure(conn, vmName, vm);
-            }
-            return new StartAnswer(cmd, e.getMessage());
-        } finally {
-            if (state != DomainState.VIR_DOMAIN_RUNNING) {
-                _storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
-            }
-        }
-    }
-
     public String getVolumePath(final Connect conn, final DiskTO volume) throws LibvirtException, URISyntaxException {
         final DataTO data = volume.getData();
         final DataStoreTO store = data.getDataStore();
@@ -2107,7 +1973,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         }
     }
 
-    protected void createVbd(final Connect conn, final VirtualMachineTO vmSpec, final String vmName, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException, URISyntaxException {
+    public void createVbd(final Connect conn, final VirtualMachineTO vmSpec, final String vmName, final LibvirtVMDef vm) throws InternalErrorException, LibvirtException, URISyntaxException {
         final List<DiskTO> disks = Arrays.asList(vmSpec.getDisks());
         Collections.sort(disks, new Comparator<DiskTO>() {
             @Override
@@ -3197,7 +3063,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
         return true;
     }
 
-    protected boolean default_network_rules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr) {
+    public boolean defaultNetworkRules(final Connect conn, final String vmName, final NicTO nic, final Long vmId, final String secIpStr) {
         if (!_canBridgeFirewall) {
             return false;
         }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
index 966a431..2256340 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtManageSnapshotCommandWrapper.java
@@ -36,9 +36,11 @@ import com.ceph.rbd.RbdImage;
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.ManageSnapshotAnswer;
 import com.cloud.agent.api.ManageSnapshotCommand;
+import com.cloud.agent.api.to.StorageFilerTO;
 import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
 import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk;
 import com.cloud.hypervisor.kvm.storage.KVMStoragePool;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
 import com.cloud.resource.CommandWrapper;
 import com.cloud.storage.Storage.StoragePoolType;
 import com.cloud.utils.script.Script;
@@ -66,7 +68,9 @@ public final class LibvirtManageSnapshotCommandWrapper extends CommandWrapper<Ma
                 }
             }
 
-            final KVMStoragePool primaryPool = libvirtComputingResource.getStoragePoolMgr().getStoragePool(command.getPool().getType(), command.getPool().getUuid());
+            KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
+            StorageFilerTO pool = command.getPool();
+            final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid());
 
             final KVMPhysicalDisk disk = primaryPool.getPhysicalDisk(command.getVolumePath());
             if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryPool.isExternalSnapshot()) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
index e8b7b8c..b181426 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRequestWrapper.java
@@ -66,6 +66,7 @@ import com.cloud.agent.api.ReadyCommand;
 import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
+import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
@@ -155,6 +156,7 @@ public class LibvirtRequestWrapper extends RequestWrapper {
         linbvirtCommands.put(ResizeVolumeCommand.class, new LibvirtResizeVolumeCommandWrapper());
         linbvirtCommands.put(NetworkElementCommand.class, new LibvirtNetworkElementCommandWrapper());
         linbvirtCommands.put(StorageSubSystemCommand.class, new LibvirtStorageSubSystemCommandWrapper());
+        linbvirtCommands.put(StartCommand.class, new LibvirtStartCommandWrapper());
 
         resources.put(LibvirtComputingResource.class, linbvirtCommands);
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java
new file mode 100644
index 0000000..649e11c
--- /dev/null
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtStartCommandWrapper.java
@@ -0,0 +1,151 @@
+//
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+//
+
+package com.cloud.hypervisor.kvm.resource.wrapper;
+
+import java.net.URISyntaxException;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.libvirt.Connect;
+import org.libvirt.DomainInfo.DomainState;
+import org.libvirt.LibvirtException;
+
+import com.cloud.agent.api.Answer;
+import com.cloud.agent.api.StartAnswer;
+import com.cloud.agent.api.StartCommand;
+import com.cloud.agent.api.to.NicTO;
+import com.cloud.agent.api.to.VirtualMachineTO;
+import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
+import com.cloud.exception.InternalErrorException;
+import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
+import com.cloud.hypervisor.kvm.resource.LibvirtVMDef;
+import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager;
+import com.cloud.network.Networks.IsolationType;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.resource.CommandWrapper;
+import com.cloud.vm.VirtualMachine;
+
+public final class LibvirtStartCommandWrapper extends CommandWrapper<StartCommand, Answer, LibvirtComputingResource> {
+
+    private static final Logger s_logger = Logger.getLogger(LibvirtStartCommandWrapper.class);
+
+    @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 {
+            final NicTO[] nics = vmSpec.getNics();
+
+            for (final NicTO nic : nics) {
+                if (vmSpec.getType() != VirtualMachine.Type.User) {
+                    nic.setPxeDisable(true);
+                }
+            }
+
+            vm = libvirtComputingResource.createVMFromSpec(vmSpec);
+            conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType());
+            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);
+            }
+        }
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
index c0f1cb5..74a41c6 100644
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUtilitiesHelper.java
@@ -65,4 +65,8 @@ public class LibvirtUtilitiesHelper {
     public String generatereUUIDName() {
         return UUID.randomUUID().toString();
     }
+
+    public Connect getConnectionByType(final String hvsType) throws LibvirtException {
+        return LibvirtConnection.getConnectionByType(hvsType);
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/74ad48db/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index 140262f..4a1dcc4 100644
--- a/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/test/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -121,6 +122,7 @@ import com.cloud.agent.api.RebootCommand;
 import com.cloud.agent.api.RebootRouterCommand;
 import com.cloud.agent.api.SecurityGroupRulesCmd;
 import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
+import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StopCommand;
 import com.cloud.agent.api.UnPlugNicCommand;
 import com.cloud.agent.api.UpgradeSnapshotCommand;
@@ -758,6 +760,96 @@ public class LibvirtComputingResourceTest {
         }
     }
 
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testRebootCommandException1() {
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final String vmName = "Test";
+        final RebootCommand command = new RebootCommand(vmName);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testRebootCommandError() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final String vmName = "Test";
+        final RebootCommand command = new RebootCommand(vmName);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtComputingResource.rebootVM(conn, command.getVmName())).thenReturn("error");
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testRebootCommandException2() {
+        final Connect conn = Mockito.mock(Connect.class);
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+
+        final String vmName = "Test";
+        final RebootCommand command = new RebootCommand(vmName);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtComputingResource.rebootVM(conn, command.getVmName())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
     @Test
     public void testRebootRouterCommand() {
         final VirtualRoutingResource routingResource = Mockito.mock(VirtualRoutingResource.class);
@@ -3588,6 +3680,65 @@ public class LibvirtComputingResourceTest {
         }
     }
 
+    @Test
+    public void testManageSnapshotCommandLibvirt() {
+        final StoragePool storagePool = Mockito.mock(StoragePool.class);;
+        final String volumePath = "/123/vol";
+        final String vmName = "Test";
+        final long snapshotId = 1l;
+        final String preSnapshotPath = "/snapshot/path";
+        final String snapshotName = "snap";
+
+        final ManageSnapshotCommand command = new ManageSnapshotCommand(snapshotId, volumePath, storagePool, preSnapshotPath, snapshotName, vmName);
+
+        final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
+        final Connect conn = Mockito.mock(Connect.class);
+        final KVMStoragePoolManager storagePoolMgr = Mockito.mock(KVMStoragePoolManager.class);
+        final KVMStoragePool primaryPool = Mockito.mock(KVMStoragePool.class);
+        final Domain vm = Mockito.mock(Domain.class);
+        final DomainInfo info = Mockito.mock(DomainInfo.class);
+        final DomainState state = DomainInfo.DomainState.VIR_DOMAIN_RUNNING;
+        info.state = state;
+
+        final KVMPhysicalDisk disk = Mockito.mock(KVMPhysicalDisk.class);
+
+        final StorageFilerTO pool = command.getPool();
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenReturn(conn);
+            when(libvirtComputingResource.getDomain(conn, command.getVmName())).thenReturn(vm);
+            when(vm.getInfo()).thenReturn(info);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(storagePoolMgr.getStoragePool(pool.getType(), pool.getUuid())).thenReturn(primaryPool);
+        when(primaryPool.getPhysicalDisk(command.getVolumePath())).thenReturn(disk);
+        when(primaryPool.isExternalSnapshot()).thenReturn(false);
+
+        try {
+            when(vm.getUUIDString()).thenReturn("cdb18980-546d-4153-b916-70ee9edf0908");
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByVmName(vmName);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
     @SuppressWarnings("unchecked")
     @Test
     public void testBackupSnapshotCommandLibvirtException() {
@@ -4545,4 +4696,355 @@ public class LibvirtComputingResourceTest {
         final Answer answer = wrapper.execute(command, libvirtComputingResource);
         assertTrue(answer.getResult());
     }
+
+    @Test
+    public void testStartCommandFailedConnect() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
+            doNothing().when(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(false);
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Test
+    public void testStartCommandLibvirtException() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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 LibvirtVMDef vmDef = Mockito.mock(LibvirtVMDef.class);
+
+        final NicTO nic = Mockito.mock(NicTO.class);
+        final NicTO[] nics = new NicTO[]{nic};
+
+        final String vmName = "Test";
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenThrow(LibvirtException.class);
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testStartCommandInternalError() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
+            doThrow(InternalErrorException.class).when(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, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testStartCommandUriException() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
+            doThrow(URISyntaxException.class).when(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, libvirtComputingResource);
+        assertFalse(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testStartCommand() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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 String vmName = "Test";
+        final String controlIp = "169.122.10.10";
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
+            doNothing().when(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(libvirtComputingResource).createVifs(vmSpec, vmDef);
+
+            when(libvirtComputingResource.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS");
+
+            when(vmSpec.getBootArgs()).thenReturn("ls -lart");
+            when(libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true);
+
+            when(nic.getIp()).thenReturn(controlIp);
+            when(nic.getType()).thenReturn(TrafficType.Control);
+            when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
+            when(virtRouterResource.connect(controlIp, 1, 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, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
+
+    @Test
+    public void testStartCommandIsolationEc2() {
+        final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
+        final com.cloud.host.Host host = Mockito.mock(com.cloud.host.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 String vmName = "Test";
+        final String controlIp = "169.122.10.10";
+
+        when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
+        when(vmSpec.getNics()).thenReturn(nics);
+        when(vmSpec.getType()).thenReturn(VirtualMachine.Type.DomainRouter);
+        when(vmSpec.getName()).thenReturn(vmName);
+        when(libvirtComputingResource.createVMFromSpec(vmSpec)).thenReturn(vmDef);
+
+        when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
+        try {
+            when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
+            doNothing().when(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(libvirtComputingResource).createVifs(vmSpec, vmDef);
+
+            when(libvirtComputingResource.startVM(conn, vmName, vmDef.toString())).thenReturn("SUCCESS");
+
+            when(nic.isSecurityGroupEnabled()).thenReturn(true);
+            when(nic.getIsolationUri()).thenReturn(new URI("ec2://test"));
+
+
+            when(vmSpec.getBootArgs()).thenReturn("ls -lart");
+            when(libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true);
+
+            when(nic.getIp()).thenReturn(controlIp);
+            when(nic.getType()).thenReturn(TrafficType.Control);
+            when(libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
+            when(virtRouterResource.connect(controlIp, 1, 5000)).thenReturn(true);
+        } catch (final InternalErrorException e) {
+            fail(e.getMessage());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        } catch (final URISyntaxException e) {
+            fail(e.getMessage());
+        }
+
+        final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
+        assertNotNull(wrapper);
+
+        final Answer answer = wrapper.execute(command, libvirtComputingResource);
+        assertTrue(answer.getResult());
+
+        verify(libvirtComputingResource, times(1)).getStoragePoolMgr();
+        verify(libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
+        try {
+            verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
+        } catch (final LibvirtException e) {
+            fail(e.getMessage());
+        }
+    }
 }
\ No newline at end of file


[33/50] [abbrv] git commit: updated refs/heads/CLOUDSTACK-8301 to 8ff9000

Posted by ko...@apache.org.
CLOUDSTACK-8468: Correct test case in test_bugs.py

Signed-off-by: Gaurav Aradhye <ga...@clogeny.com>
This closes #251


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/b1f2e598
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/b1f2e598
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/b1f2e598

Branch: refs/heads/CLOUDSTACK-8301
Commit: b1f2e598e83e8ec018ae993f918accb0199b9237
Parents: c7d2e44
Author: Gaurav Aradhye <ga...@clogeny.com>
Authored: Wed May 13 16:36:56 2015 +0530
Committer: Gaurav Aradhye <ga...@clogeny.com>
Committed: Wed May 13 16:40:00 2015 +0530

----------------------------------------------------------------------
 test/integration/component/maint/test_bugs.py | 6 ++++++
 1 file changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b1f2e598/test/integration/component/maint/test_bugs.py
----------------------------------------------------------------------
diff --git a/test/integration/component/maint/test_bugs.py b/test/integration/component/maint/test_bugs.py
index 96d0f77..6652b04 100644
--- a/test/integration/component/maint/test_bugs.py
+++ b/test/integration/component/maint/test_bugs.py
@@ -532,6 +532,12 @@ class Test42xBugsMgmtSvr(cloudstackTestCase):
 
          """
 
+        if not is_config_suitable(apiclient=self.apiClient,
+                                  name='apply.allocation.algorithm.to.pods',
+                                  value='true'):
+            self.skipTest('apply.allocation.algorithm.to.pods '
+                          'should be true. skipping')
+
         # register windows 2012 VM template as windows 8 template
         self.hypervisor = self.testClient.getHypervisorInfo()
         if self.hypervisor.lower() in ['lxc']: