You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by hu...@apache.org on 2013/11/07 15:10:14 UTC

[1/5] git commit: updated refs/heads/master to 85f38b3

Updated Branches:
  refs/heads/master 9631df8d0 -> 85f38b3e0


Fix CID 1127045 Dead local store
Fix CID 1127041,1127040, 1127039, 1127038, 1127037 String concatenation in loop


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

Branch: refs/heads/master
Commit: ad0d7f882f001ed6421e4aa40070a215ffb1fd3b
Parents: 9631df8
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 14:40:14 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 14:40:14 2013 +0100

----------------------------------------------------------------------
 .../resource/HypervDirectConnectResource.java   | 111 ++++++++++---------
 1 file changed, 58 insertions(+), 53 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/ad0d7f88/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java
----------------------------------------------------------------------
diff --git a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java
index a8a09f6..194ad77 100644
--- a/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java
+++ b/plugins/hypervisors/hyperv/src/com/cloud/hypervisor/hyperv/resource/HypervDirectConnectResource.java
@@ -19,7 +19,6 @@ package com.cloud.hypervisor.hyperv.resource;
 import java.io.File;
 import java.io.IOException;
 import java.net.ConnectException;
-import java.net.InetSocketAddress;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
@@ -27,16 +26,11 @@ import java.nio.channels.SocketChannel;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Random;
 import java.util.UUID;
 
 import javax.ejb.Local;
-import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
-import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
-import org.apache.cloudstack.utils.identity.ManagementServerNode;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
 import org.apache.http.client.ClientProtocolException;
@@ -47,6 +41,8 @@ import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.util.EntityUtils;
 import org.apache.log4j.Logger;
 
+import com.google.gson.Gson;
+
 import com.cloud.agent.api.Answer;
 import com.cloud.agent.api.CheckRouterAnswer;
 import com.cloud.agent.api.CheckRouterCommand;
@@ -60,7 +56,6 @@ import com.cloud.agent.api.NetworkUsageCommand;
 import com.cloud.agent.api.PingCommand;
 import com.cloud.agent.api.PingRoutingCommand;
 import com.cloud.agent.api.PingTestCommand;
-import com.cloud.agent.api.StartCommand;
 import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupRoutingCommand;
 import com.cloud.agent.api.StartupRoutingCommand.VmState;
@@ -95,8 +90,6 @@ import com.cloud.agent.api.to.FirewallRuleTO;
 import com.cloud.agent.api.to.IpAddressTO;
 import com.cloud.agent.api.to.PortForwardingRuleTO;
 import com.cloud.agent.api.to.StaticNatRuleTO;
-import com.cloud.agent.api.to.VirtualMachineTO;
-import com.cloud.configuration.Config;
 import com.cloud.dc.DataCenter.NetworkType;
 import com.cloud.host.Host.Type;
 import com.cloud.hypervisor.Hypervisor;
@@ -107,20 +100,11 @@ import com.cloud.network.rules.FirewallRule;
 import com.cloud.resource.ServerResource;
 import com.cloud.resource.ServerResourceBase;
 import com.cloud.serializer.GsonHelper;
-import com.cloud.storage.JavaStorageLayer;
-import com.cloud.storage.StorageLayer;
-import com.cloud.utils.FileUtil;
-import com.cloud.utils.NumbersUtil;
 import com.cloud.utils.Pair;
 import com.cloud.utils.StringUtils;
-import com.cloud.utils.db.GlobalLock;
-import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
-import com.cloud.utils.script.Script;
 import com.cloud.utils.ssh.SshHelper;
-import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.VirtualMachineName;
-import com.google.gson.Gson;
 
 /**
  * Implementation of dummy resource to be returned from discoverer.
@@ -164,8 +148,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         if (!_configureCalled) {
             String errMsg =
                     this.getClass().getName()
-                            + " requires configure() be called before"
-                            + " initialize()";
+                    + " requires configure() be called before"
+                    + " initialize()";
             s_logger.error(errMsg);
         }
 
@@ -220,7 +204,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
                             "Host %s (IP %s) changed zone/data center.  Was "
                                     + defaultStartRoutCmd.getDataCenter()
                                     + " NOW its " + startCmd.getDataCenter(),
-                            _name, _agentIp);
+                                    _name, _agentIp);
             s_logger.error(errMsg);
             // TODO: valid to return null, or should we throw?
             return null;
@@ -267,8 +251,8 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             String errMsg =
                     String.format(
                             "Host %s (IP %s) name.  Was " + startCmd.getName()
-                                    + " NOW its "
-                                    + defaultStartRoutCmd.getName(), _name,
+                            + " NOW its "
+                            + defaultStartRoutCmd.getName(), _name,
                             _agentIp);
             s_logger.error(errMsg);
             // TODO: valid to return null, or should we throw?
@@ -315,7 +299,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             s_logger.debug("Ping host " + _name + " (IP " + _agentIp + ")");
         }
 
-        Answer pingAns = this.executeRequest(pingCmd);
+        Answer pingAns = executeRequest(pingCmd);
 
         if (pingAns == null || !pingAns.getResult()) {
             s_logger.info("Cannot ping host " + _name + " (IP " + _agentIp
@@ -390,9 +374,9 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         } else if (clazz == GetDomRVersionCmd.class) {
             answer = execute((GetDomRVersionCmd)cmd);
         } else if (cmd instanceof NetworkUsageCommand) {
-           answer = execute((NetworkUsageCommand) cmd);
+            answer = execute((NetworkUsageCommand) cmd);
         } else if (clazz == IpAssocCommand.class) {
-           answer = execute((IpAssocCommand) cmd);
+            answer = execute((IpAssocCommand) cmd);
         } else if (clazz == DnsMasqConfigCommand.class) {
             return execute((DnsMasqConfigCommand) cmd);
         } else if (clazz == CreateIpAliasCommand.class) {
@@ -430,7 +414,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             // Else send the cmd to hyperv agent.
             String ansStr = postHttpRequest(s_gson.toJson(cmd), agentUri);
             if (ansStr == null) {
-               return Answer.createUnsupportedCommandAnswer(cmd);
+                return Answer.createUnsupportedCommandAnswer(cmd);
             }
             // Only Answer instances are returned by remote agents.
             // E.g. see Response.getAnswers()
@@ -498,12 +482,13 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         Pair<Boolean, String> result;
         try {
             String controlIp = getRouterSshControlIp(cmd);
-            String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh ";
+            StringBuilder cmdline = new StringBuilder("/opt/cloud/bin/checkbatchs2svpn.sh ");
             for (String ip : cmd.getVpnIps()) {
-                cmdline += " " + ip;
+                cmdline.append(" ");
+                cmdline.append(ip);
             }
 
-            result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, cmdline);
+            result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, cmdline.toString());
 
             if (!result.first()) {
                 s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: "
@@ -833,13 +818,23 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         if (s_logger.isInfoEnabled()) {
             s_logger.info("Executing deleteIpAlias command: " + s_gson.toJson(cmd));
         }
-        String args = "";
+        StringBuilder args = new StringBuilder();
         for (IpAliasTO ipAliasTO : revokedIpAliasTOs) {
-            args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
-        }
-        args = args + "- ";
+            args.append(ipAliasTO.getAlias_count());
+            args.append(":");
+            args.append(ipAliasTO.getRouterip());
+            args.append(":");
+            args.append(ipAliasTO.getNetmask());
+            args.append("-");
+        }
+        args.append("- ");
         for (IpAliasTO ipAliasTO : activeIpAliasTOs) {
-            args = args + ipAliasTO.getAlias_count() + ":" + ipAliasTO.getRouterip() + ":" + ipAliasTO.getNetmask() + "-";
+            args.append(ipAliasTO.getAlias_count());
+            args.append(":");
+            args.append(ipAliasTO.getRouterip());
+            args.append(":");
+            args.append(ipAliasTO.getNetmask());
+            args.append("-");
         }
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/deleteIpAlias " + args);
@@ -887,14 +882,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
 
         String[][] rules = cfgtr.generateFwRules(cmd);
         String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg";
-        String tmpCfgFileContents = "";
+        StringBuilder tmpCfgFileContents = new StringBuilder();
         for (int i = 0; i < config.length; i++) {
-            tmpCfgFileContents += config[i];
-            tmpCfgFileContents += "\n";
+            tmpCfgFileContents.append(config[i]);
+            tmpCfgFileContents.append("\n");
         }
 
         try {
-            SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null);
+            SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.toString().getBytes(), routerIp.replace('.', '_') + ".cfg", null);
 
             try {
                 String[] addRules = rules[LoadBalancerConfigurator.ADD];
@@ -1076,7 +1071,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         } catch (Throwable e) {
             s_logger.error("SetFirewallRulesCommand(args: " + args
                     + ") failed on setting one rule due to "
-                     ,e);
+                    ,e);
             //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails
             for (int i=0; i < results.length; i++) {
                 results[i] = "Failed";
@@ -1229,9 +1224,14 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         }
         cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
         List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList();
-        String args="";
+        StringBuilder args = new StringBuilder();
         for (IpAliasTO ipaliasto : ipAliasTOs) {
-            args = args + ipaliasto.getAlias_count()+":"+ipaliasto.getRouterip()+":"+ipaliasto.getNetmask()+"-";
+            args.append(ipaliasto.getAlias_count());
+            args.append(":");
+            args.append(ipaliasto.getRouterip());
+            args.append(":");
+            args.append(ipaliasto.getNetmask());
+            args.append("-");
         }
         if (s_logger.isDebugEnabled()) {
             s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/createIpAlias " + args);
@@ -1271,9 +1271,16 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
         assert(controlIp != null);
 
         List<DhcpTO> dhcpTos = cmd.getIps();
-        String args ="";
+        StringBuilder args = new StringBuilder();
         for(DhcpTO dhcpTo : dhcpTos) {
-            args = args + dhcpTo.getRouterIp()+":"+dhcpTo.getGateway()+":"+dhcpTo.getNetmask()+":"+dhcpTo.getStartIpOfSubnet()+"-";
+            args.append(dhcpTo.getRouterIp());
+            args.append(":");
+            args.append(dhcpTo.getGateway());
+            args.append(":");
+            args.append(dhcpTo.getNetmask());
+            args.append(":");
+            args.append(dhcpTo.getStartIpOfSubnet());
+            args.append("-");
         }
 
         try {
@@ -1320,7 +1327,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             for (; i < cmd.getIpAddresses().length; i++) {
                 results[i++] = IpAssocAnswer.errorResult;
             }
-            } catch (Throwable e) {
+        } catch (Throwable e) {
             s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e);
 
             for (; i < cmd.getIpAddresses().length; i++) {
@@ -1335,14 +1342,12 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception {
 
         boolean addVif = false;
-        boolean removeVif = false;
         if (add) {
             if (s_logger.isDebugEnabled()) {
                 s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress);
             }
             addVif = true;
         } else if (!add && firstIP) {
-            removeVif = true;
         }
 
         String args = null;
@@ -1448,7 +1453,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
             s_logger.info("Executing resource NetworkUsageCommand "+ s_gson.toJson(cmd));
         }
         if(cmd.getOption()!=null && cmd.getOption().equals("create") ){
-            String result = networkUsage(cmd.getPrivateIP(), "create", null);
+            networkUsage(cmd.getPrivateIP(), "create", null);
             NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "true", 0L, 0L);
             return answer;
         }
@@ -1594,7 +1599,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
 
             // Unsupported commands will not route.
             if (response.getStatusLine().getStatusCode()
-                == HttpStatus.SC_NOT_FOUND) {
+                    == HttpStatus.SC_NOT_FOUND) {
                 String errMsg =
                         "Failed to send : HTTP error code : "
                                 + response.getStatusLine().getStatusCode();
@@ -1608,11 +1613,11 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
                 s_logger.error(ans);
                 result = s_gson.toJson(new Answer[] {ans});
             } else if (response.getStatusLine().getStatusCode()
-                != HttpStatus.SC_OK) {
+                    != HttpStatus.SC_OK) {
                 String errMsg =
                         "Failed send to " + agentUri.toString()
-                                + " : HTTP error code : "
-                                + response.getStatusLine().getStatusCode();
+                        + " : HTTP error code : "
+                        + response.getStatusLine().getStatusCode();
                 s_logger.error(errMsg);
                 return null;
             } else {
@@ -1707,7 +1712,7 @@ public class HypervDirectConnectResource extends ServerResourceBase implements S
                 sch.configureBlocking(true);
                 sch.socket().setSoTimeout(5000);
                 // we need to connect to the public ip address to check the status of the VM
-/*
+                /*
                 InetSocketAddress addr = new InetSocketAddress(ipAddress, port);
                 sch.connect(addr);*/
                 return null;


[5/5] git commit: updated refs/heads/master to 85f38b3

Posted by hu...@apache.org.
Fix CID 1127051 DLS: Dead local store
Fix CID 1127050 WMI: Inefficient Map iterator



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

Branch: refs/heads/master
Commit: 85f38b3e07bf6bb0419392f2b4d4438c796327f9
Parents: 831eeeb
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 15:01:21 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 15:01:21 2013 +0100

----------------------------------------------------------------------
 .../configuration/ConfigurationManagerImpl.java | 123 +++++++++----------
 1 file changed, 61 insertions(+), 62 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/85f38b3e/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 e4bbe8e..c3a196f 100755
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@ -28,6 +28,7 @@ import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.UUID;
 
@@ -35,6 +36,8 @@ import javax.ejb.Local;
 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;
@@ -79,10 +82,8 @@ import org.apache.cloudstack.region.Region;
 import org.apache.cloudstack.region.RegionVO;
 import org.apache.cloudstack.region.dao.RegionDao;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
-import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailVO;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
-import org.apache.log4j.Logger;
 
 import com.cloud.alert.AlertManager;
 import com.cloud.api.ApiDBUtils;
@@ -95,7 +96,6 @@ import com.cloud.dc.ClusterDetailsVO;
 import com.cloud.dc.ClusterVO;
 import com.cloud.dc.DataCenter;
 import com.cloud.dc.DataCenter.NetworkType;
-import com.cloud.dc.DataCenterDetailVO;
 import com.cloud.dc.DataCenterIpAddressVO;
 import com.cloud.dc.DataCenterLinkLocalIpAddressVO;
 import com.cloud.dc.DataCenterVO;
@@ -207,7 +207,7 @@ import com.cloud.vm.dao.NicSecondaryIpDao;
 
 @Local(value = { ConfigurationManager.class, ConfigurationService.class })
 public class
-        ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService {
+ConfigurationManagerImpl extends ManagerBase implements ConfigurationManager, ConfigurationService {
     public static final Logger s_logger = Logger.getLogger(ConfigurationManagerImpl.class);
 
     @Inject
@@ -407,16 +407,16 @@ public class
                 _alertMgr.sendAlert(AlertManager.ALERT_TYPE_MANAGMENT_NODE, 0, new Long(0),
                         "Management network CIDR is not configured originally. Set it default to " + localCidrs[0], "");
                 _configDao
-                        .update(Config.ManagementNetwork.key(), Config.ManagementNetwork.getCategory(), localCidrs[0]);
+                .update(Config.ManagementNetwork.key(), Config.ManagementNetwork.getCategory(), localCidrs[0]);
             } else {
                 s_logger.warn("Management network CIDR is not properly configured and we are not able to find a default setting");
                 _alertMgr
-                        .sendAlert(
-                                AlertManager.ALERT_TYPE_MANAGMENT_NODE,
-                                0,
-                                new Long(0),
-                                "Management network CIDR is not properly configured and we are not able to find a default setting",
-                                "");
+                .sendAlert(
+                        AlertManager.ALERT_TYPE_MANAGMENT_NODE,
+                        0,
+                        new Long(0),
+                        "Management network CIDR is not properly configured and we are not able to find a default setting",
+                        "");
             }
         }
 
@@ -475,7 +475,7 @@ public class
                     throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
                 }
                 _storagePoolDetailsDao.addDetail(resourceId, name, value);
-                
+
                 break;
 
             case Account:
@@ -1200,7 +1200,7 @@ public class
                         _capacityDao.updateCapacityState(null, pod.getId(), null, null, allocationStateStrFinal);
                         pod.setAllocationState(allocationState);
                     }
-        
+
                     _podDao.update(id, pod);
                 }
             });
@@ -1679,8 +1679,8 @@ public class
         boolean checkForDuplicates = !zoneName.equals(oldZoneName);
         checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, checkForDuplicates, null,
                 allocationStateStr, ip6Dns1, ip6Dns2);// not allowing updating
-                                                      // domain associated with
-                                                      // a zone, once created
+        // domain associated with
+        // a zone, once created
 
         zone.setName(zoneName);
         zone.setDns1(dns1);
@@ -1712,10 +1712,10 @@ public class
                 }
                 updatedDetails.putAll(newDetails);
                 zone.setDetails(updatedDetails);
-        
+
                 if (allocationStateStr != null && !allocationStateStr.isEmpty()) {
                     Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr);
-        
+
                     if (allocationState == Grouping.AllocationState.Enabled) {
                         // check if zone has necessary trafficTypes before enabling
                         try {
@@ -1729,7 +1729,7 @@ public class
                                 // network with public Thpe
                                 _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                             }
-        
+
                             try {
                                 _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Storage);
                             } catch (InvalidParameterValueException noStorage) {
@@ -1976,7 +1976,7 @@ public class
 
         return createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, guestCidr,
                 domainVO != null ? domainVO.getName() : null, domainId, zoneType, allocationState, networkDomain,
-                isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2);
+                        isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2);
     }
 
     @Override
@@ -1999,7 +1999,6 @@ public class
         Integer cpuNumber = cmd.getCpuNumber();
         Integer cpuSpeed = cmd.getCpuSpeed();
         Integer memory = cmd.getMemory();
-        boolean customized = cmd.getCustomized();
 
         if ((cpuNumber != null) && ((cpuNumber.intValue() <=0) || (cpuNumber.intValue() > 2147483647))) {
             throw new InvalidParameterValueException("Failed to create service offering " + name
@@ -2101,10 +2100,10 @@ public class
         if ((offering = _serviceOfferingDao.persist(offering)) != null) {
             if (details != null) {
                 List<ServiceOfferingDetailsVO> detailsVO = new ArrayList<ServiceOfferingDetailsVO>();
-                for (String key : details.keySet()) {
-                    detailsVO.add(new ServiceOfferingDetailsVO(offering.getId(), key, details.get(key)));
+                for (Entry<String, String> detailEntry : details.entrySet()) {
+                    detailsVO.add(new ServiceOfferingDetailsVO(offering.getId(), detailEntry.getKey(), detailEntry.getValue()));
                 }
-                
+
                 _serviceOfferingDetailsDao.saveDetails(detailsVO);
             }
             CallContext.current().setEventDetails("Service offering id=" + offering.getId());
@@ -2187,8 +2186,8 @@ public class
     }
 
     protected DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized,
-    		boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,
-    		Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, Integer hypervisorSnapshotReserve) {
+            boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops,
+            Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate, Integer hypervisorSnapshotReserve) {
         long diskSize = 0;// special case for custom disk offerings
         if (numGibibytes != null && (numGibibytes <= 0)) {
             throw new InvalidParameterValueException("Please specify a disk size of at least 1 Gb.");
@@ -2211,8 +2210,8 @@ public class
             iopsWriteRate = null;
 
             if (isCustomizedIops) {
-            	minIops = null;
-            	maxIops = null;
+                minIops = null;
+                maxIops = null;
             }
             else {
                 if (minIops == null && maxIops == null) {
@@ -2220,17 +2219,17 @@ public class
                     maxIops = 0L;
                 }
                 else {
-                	if (minIops == null || minIops <= 0) {
-                	    throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
-        	        }
+                    if (minIops == null || minIops <= 0) {
+                        throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
+                    }
 
-                	if (maxIops == null) {
-        	        	maxIops = 0L;
-        	        }
+                    if (maxIops == null) {
+                        maxIops = 0L;
+                    }
 
-                	if (minIops > maxIops) {
-                		throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
-                	}
+                    if (minIops > maxIops) {
+                        throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
+                    }
                 }
             }
         }
@@ -2241,7 +2240,7 @@ public class
 
         tags = StringUtils.cleanupTags(tags);
         DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize, tags, isCustomized,
-        		isCustomizedIops, minIops, maxIops);
+                isCustomizedIops, minIops, maxIops);
         newDiskOffering.setUseLocalStorage(localStorageRequired);
         newDiskOffering.setDisplayOffering(isDisplayOfferingEnabled);
 
@@ -2278,8 +2277,8 @@ public class
         Long numGibibytes = cmd.getDiskSize();
         boolean isDisplayOfferingEnabled = cmd.getDisplayOffering() != null ? cmd.getDisplayOffering() : true;
         boolean isCustomized = cmd.isCustomized() != null ? cmd.isCustomized() : false; // false
-                                                                                        // by
-                                                                                        // default
+        // by
+        // default
         String tags = cmd.getTags();
         // Long domainId = cmd.getDomainId() != null ? cmd.getDomainId() :
         // Long.valueOf(DomainVO.ROOT_DOMAIN); // disk offering
@@ -2441,9 +2440,9 @@ public class
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_CREATE, eventDescription = "creating vlan ip range",
-            async = false)
+    async = false)
     public Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException,
-            ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException {
+    ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException {
         Long zoneId = cmd.getZoneId();
         Long podId = cmd.getPodId();
         String startIP = cmd.getStartIp();
@@ -2453,8 +2452,8 @@ public class
         String vlanId = cmd.getVlan();
         // TODO decide if we should be forgiving or demand a valid and complete URI
         if (!((vlanId == null)
-            || ("".equals(vlanId))
-            || vlanId.startsWith(BroadcastDomainType.Vlan.scheme())))
+                || ("".equals(vlanId))
+                || vlanId.startsWith(BroadcastDomainType.Vlan.scheme())))
             vlanId = BroadcastDomainType.Vlan.toUri(vlanId).toString();
         Boolean forVirtualNetwork = cmd.isForVirtualNetwork();
         Long networkId = cmd.getNetworkID();
@@ -2690,12 +2689,12 @@ public class
             public Vlan doInTransaction(TransactionStatus status) {
                 String newVlanNetmask = newVlanNetmaskFinal;
                 String newVlanGateway = newVlanGatewayFinal;
-                
+
                 if ((sameSubnet == null || sameSubnet.first() == false) && (network.getTrafficType()== TrafficType.Guest) && (network.getGuestType() == GuestType.Shared) && (_vlanDao.listVlansByNetworkId(networkId) != null)) {
                     Map<Capability, String> dhcpCapabilities = _networkSvc.getNetworkOfferingServiceCapabilities(_networkOfferingDao.findById(network.getNetworkOfferingId()), Service.Dhcp);
                     String supportsMultipleSubnets = dhcpCapabilities.get(Capability.DhcpAccrossMultipleSubnets);
                     if (supportsMultipleSubnets == null || !Boolean.valueOf(supportsMultipleSubnets)) {
-                               throw new  InvalidParameterValueException("The Dhcp serivice provider for this network dose not support the dhcp  across multiple subnets");
+                        throw new  InvalidParameterValueException("The Dhcp serivice provider for this network dose not support the dhcp  across multiple subnets");
                     }
                     s_logger.info("adding a new subnet to the network " + network.getId());
                 } else if (sameSubnet != null)  {
@@ -2776,7 +2775,7 @@ public class
                         sameSubnet = true;
                         //check if the gateway provided by the user is same as that of the subnet.
                         if (newVlanGateway != null && !newVlanGateway.equals(vlanGateway)) {
-                             throw new InvalidParameterValueException("The gateway of the subnet should be unique. The subnet alreaddy has a gateway "+ vlanGateway);
+                            throw new InvalidParameterValueException("The gateway of the subnet should be unique. The subnet alreaddy has a gateway "+ vlanGateway);
                         }
                         break;
                     }
@@ -2982,7 +2981,7 @@ public class
                     throw new InvalidParameterValueException("This subnet is overlapped with subnet in other network " + vlan.getNetworkId()
                             + " in zone " + zone.getName()
                             + " . Please specify a different gateway/netmask.");
-                   
+
                 }
                 String[] otherVlanIpRange = vlan.getIpRange().split("\\-");
                 String otherVlanStartIP = otherVlanIpRange[0];
@@ -2999,7 +2998,7 @@ public class
                 }
                 if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) {
                     throw new InvalidParameterValueException("The IP range already has IPs that overlap with the new range." +
-                    		" Please specify a different start IP/end IP.");
+                            " Please specify a different start IP/end IP.");
                 }
             }
         }
@@ -3202,7 +3201,7 @@ public class
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DEDICATE, eventDescription = "dedicating vlan ip range",
-            async = false)
+    async = false)
     public Vlan dedicatePublicIpRange(DedicatePublicIpRangeCmd cmd) throws ResourceAllocationException {
         Long vlanDbId = cmd.getId();
         String accountName = cmd.getAccountName();
@@ -3291,7 +3290,7 @@ public class
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_RELEASE, eventDescription = "releasing a public ip range",
-            async = false)
+    async = false)
     public boolean releasePublicIpRange(ReleasePublicIpRangeCmd cmd) {
         Long vlanDbId = cmd.getId();
 
@@ -3425,7 +3424,7 @@ public class
     }
 
     private void checkConflictsWithPortableIpRange(long zoneId, String vlanId, String vlanGateway, String vlanNetmask,
-                                          String startIP, String endIP) {
+            String startIP, String endIP) {
         // check and throw exception if there is portable IP range that overlaps with public ip range being configured
         if (checkOverlapPortableIpRange(_regionDao.getRegionId(), startIP, endIP)) {
             throw new InvalidParameterValueException("Ip range: " + startIP + "-" + endIP
@@ -3549,7 +3548,7 @@ public class
                     if (podName.equals("newPod")) {
                         throw new InvalidParameterValueException(
                                 "The subnet of the pod you are adding conflicts with the subnet of pod " + otherPodName
-                                        + " in zone " + zoneName + ". Please specify a different CIDR.");
+                                + " in zone " + zoneName + ". Please specify a different CIDR.");
                     } else {
                         throw new InvalidParameterValueException("Warning: The pods " + podName + " and "
                                 + otherPodName + " in zone " + zoneName
@@ -3610,7 +3609,7 @@ public class
 
     @Override
     @ActionEvent(eventType = EventTypes.EVENT_VLAN_IP_RANGE_DELETE, eventDescription = "deleting vlan ip range",
-            async = false)
+    async = false)
     public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) {
         Long vlanDbId = cmd.getId();
 
@@ -3802,7 +3801,7 @@ public class
                         if (provider == Provider.PaloAlto) {
                             firewallProvider = Provider.PaloAlto;
                         }
-                        
+
                         if ((service == Service.PortForwarding || service == Service.StaticNat)
                                 && provider == Provider.VirtualRouter) {
                             firewallProvider = Provider.VirtualRouter;
@@ -3840,7 +3839,7 @@ public class
                     "Capabilities for LB service can be specifed only when LB service is enabled for network offering.");
         }
         validateLoadBalancerServiceCapabilities(lbServiceCapabilityMap);
-        
+
         if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) {
             maxconn = cmd.getMaxconnections();
             if (maxconn == null) {
@@ -3850,7 +3849,7 @@ public class
         if(cmd.getKeepAliveEnabled() != null && cmd.getKeepAliveEnabled()) {
             enableKeepAlive = true;
         }
-        
+
         // validate the Source NAT service capabilities specified in the network
         // offering
         Map<Capability, String> sourceNatServiceCapabilityMap = cmd.getServiceCapabilities(Service.SourceNat);
@@ -4164,7 +4163,7 @@ public class
                 }
             }
         }
-        
+
         if (serviceProviderMap != null && serviceProviderMap.containsKey(Service.Lb) && !internalLb && !publicLb) {
             //if not specified, default public lb to true
             publicLb = true;
@@ -4626,7 +4625,7 @@ public class
         }
         if (_ntwkOffServiceMapDao.areServicesSupportedByNetworkOffering(offering.getId(), Service.Lb)){
             if (maxconn != null) {
-                 offering.setConcurrentConnections(maxconn);
+                offering.setConcurrentConnections(maxconn);
             }
         }
 
@@ -4845,7 +4844,7 @@ public class
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_CREATE,
-            eventDescription = "creating portable ip range", async = false)
+    eventDescription = "creating portable ip range", async = false)
     public PortableIpRange createPortableIpRange(CreatePortableIpRangeCmd cmd) throws ConcurrentOperationException {
         final Integer regionId = cmd.getRegionId();
         final String startIP = cmd.getStartIp();
@@ -4920,7 +4919,7 @@ public class
                     // implicitly enable portable IP service for the region
                     region.setPortableipEnabled(true);
                     _regionDao.update(region.getId(), region);
-                    
+
                     return portableIpRange;
                 }
             });
@@ -4932,7 +4931,7 @@ public class
     @Override
     @DB
     @ActionEvent(eventType = EventTypes.EVENT_PORTABLE_IP_RANGE_DELETE,
-            eventDescription = "deleting portable ip range", async = false)
+    eventDescription = "deleting portable ip range", async = false)
     public boolean deletePortableIpRange(DeletePortableIpRangeCmd cmd) {
         long rangeId = cmd.getId();
 
@@ -5032,7 +5031,7 @@ public class
 
     @Inject
     public void setSecChecker(List<SecurityChecker> secChecker) {
-        this._secChecker = secChecker;
+        _secChecker = secChecker;
     }
 
 


[4/5] git commit: updated refs/heads/master to 85f38b3

Posted by hu...@apache.org.
Fix CID 1127031 Inefficient Map iterator

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

Branch: refs/heads/master
Commit: 831eeeb42234bc7d87381dcea5afb7d7f664d372
Parents: f00bfea
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 14:59:43 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 14:59:43 2013 +0100

----------------------------------------------------------------------
 server/src/com/cloud/network/vpc/VpcManagerImpl.java | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/831eeeb4/server/src/com/cloud/network/vpc/VpcManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java
index 11cbd95..017d38d 100644
--- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java
+++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java
@@ -22,6 +22,7 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -351,16 +352,16 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
         svcProviderMap.put(Service.Gateway, defaultProviders);
 
         if (serviceProviders != null) {
-            for (String serviceStr : serviceProviders.keySet()) {
-                Network.Service service = Network.Service.getService(serviceStr);
+            for (Entry<String, List<String>> serviceEntry : serviceProviders.entrySet()) {
+                Network.Service service = Network.Service.getService(serviceEntry.getKey());
                 if (svcProviderMap.containsKey(service)) {
                     Set<Provider> providers = new HashSet<Provider>();
                     // don't allow to specify more than 1 provider per service
-                    if (serviceProviders.get(serviceStr) != null && serviceProviders.get(serviceStr).size() > 1) {
+                    if (serviceEntry.getValue() != null && serviceEntry.getValue().size() > 1) {
                         throw new InvalidParameterValueException("In the current release only one provider can be " +
                                 "specified for the service");
                     }
-                    for (String prvNameStr : serviceProviders.get(serviceStr)) {
+                    for (String prvNameStr : serviceEntry.getValue()) {
                         // check if provider is supported
                         Network.Provider provider = Network.Provider.getProvider(prvNameStr);
                         if (provider == null) {
@@ -371,7 +372,7 @@ public class VpcManagerImpl extends ManagerBase implements VpcManager, VpcProvis
                     }
                     svcProviderMap.put(service, providers);
                 } else {
-                    throw new InvalidParameterValueException("Service " + serviceStr + " is not enabled for the network " +
+                    throw new InvalidParameterValueException("Service " + serviceEntry.getKey() + " is not enabled for the network " +
                             "offering, can't add a provider to it");
                 }
             }


[3/5] git commit: updated refs/heads/master to 85f38b3

Posted by hu...@apache.org.
Fix CID 1127030, 1127029 Questionable Boxing of primitive value
Fix CID 1127028 Fix Inefficient Map Iterator
Fix bug.

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

Branch: refs/heads/master
Commit: f00bfea61eea50d5d9d7669705a934e33f306f64
Parents: b736cbd
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 14:59:03 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 14:59:03 2013 +0100

----------------------------------------------------------------------
 server/src/com/cloud/vm/UserVmManagerImpl.java | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/f00bfea6/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java
index 2d537bf..ca10b06 100755
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@ -23,6 +23,7 @@ import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.Executors;
@@ -2282,7 +2283,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
                 throw new InvalidParameterValueException("Only support one network per VM if security group enabled");
             }
 
-            NetworkVO network = _networkDao.findById(networkIdList.get(0).longValue());
+            NetworkVO network = _networkDao.findById(networkIdList.get(0));
 
             if (network == null) {
                 throw new InvalidParameterValueException(
@@ -2549,7 +2550,7 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
         }
         _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, (isIso
                 || diskOfferingId == null ? 1 : 2));
-        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, new Long (size));
+        _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
 
         // verify security group ids
         if (securityGroupIdList != null) {
@@ -2811,14 +2812,13 @@ public class UserVmManagerImpl extends ManagerBase implements UserVmManager, Vir
             }
         }
 
-        for (String ntwkDomain : ntwkDomains.keySet()) {
-            for (Long ntwkId : ntwkDomains.get(ntwkDomain)) {
+        for (Entry<String, List<Long>> ntwkDomain : ntwkDomains.entrySet()) {
+            for (Long ntwkId : ntwkDomain.getValue()) {
                 // * get all vms hostNames in the network
                 List<String> hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId);
                 // * verify that there are no duplicates
                 if (hostNames.contains(hostName)) {
-                    throw new InvalidParameterValueException("The vm with hostName " + hostName
-                            + " already exists in the network domain: " + ntwkDomain + "; network="
+                    throw new InvalidParameterValueException("The vm with hostName " + hostName + " already exists in the network domain: " + ntwkDomain.getKey() + "; network="
                             + _networkModel.getNetwork(ntwkId));
                 }
             }


[2/5] git commit: updated refs/heads/master to 85f38b3

Posted by hu...@apache.org.
Fix CID 1127024 Various resource leaks

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

Branch: refs/heads/master
Commit: b736cbd27a3e16011079061cb2ed3136d9a547f7
Parents: ad0d7f8
Author: Hugo Trippaers <ht...@schubergphilis.com>
Authored: Thu Nov 7 14:57:40 2013 +0100
Committer: Hugo Trippaers <ht...@schubergphilis.com>
Committed: Thu Nov 7 14:57:40 2013 +0100

----------------------------------------------------------------------
 .../com/cloud/upgrade/dao/Upgrade420to421.java  | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/b736cbd2/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java b/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java
index d37c0a1..d7eccc1 100644
--- a/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java
+++ b/engine/schema/src/com/cloud/upgrade/dao/Upgrade420to421.java
@@ -108,7 +108,15 @@ public class Upgrade420to421 implements DbUpgrade {
         } catch (SQLException e) {
             throw new CloudRuntimeException("Unable to update cpu/memory overprovisioning factors", e);
         } finally {
-
+            try {
+                if (pstmt1 != null)
+                    pstmt1.close();
+                if (pstmt2 != null)
+                    pstmt2.close();
+                if (pstmt3 != null)
+                    pstmt3.close();
+            } catch (SQLException e) {
+            }
         }
 
     }
@@ -131,9 +139,9 @@ public class Upgrade420to421 implements DbUpgrade {
                 long domain_id = rsAccount.getLong(2);
                 // 1. update cpu,memory for all accounts
                 pstmt2 = conn.prepareStatement( "SELECT SUM(service_offering.cpu), SUM(service_offering.ram_size)" +
-                            " FROM `cloud`.`vm_instance`, `cloud`.`service_offering`" +
-                            " WHERE vm_instance.service_offering_id = service_offering.id AND vm_instance.account_id = ?" + " AND vm_instance.removed is NULL" +
-                            " AND vm_instance.vm_type='User' AND state not in ('Destroyed', 'Error', 'Expunging')");
+                        " FROM `cloud`.`vm_instance`, `cloud`.`service_offering`" +
+                        " WHERE vm_instance.service_offering_id = service_offering.id AND vm_instance.account_id = ?" + " AND vm_instance.removed is NULL" +
+                        " AND vm_instance.vm_type='User' AND state not in ('Destroyed', 'Error', 'Expunging')");
                 pstmt2.setLong(1, account_id);
                 rsCount = pstmt2.executeQuery();
                 if (rsCount.next()) {
@@ -172,7 +180,7 @@ public class Upgrade420to421 implements DbUpgrade {
                     totalSnapshotsSize = rsCount.getLong(1);
                 }
                 pstmt4 = conn.prepareStatement("SELECT sum(template_store_ref.size) FROM `cloud`.`template_store_ref`,`cloud`.`vm_template` WHERE account_id = ?" +
-                		" AND template_store_ref.template_id = vm_template.id AND download_state = 'DOWNLOADED' AND destroyed = false AND removed is NULL");
+                        " AND template_store_ref.template_id = vm_template.id AND download_state = 'DOWNLOADED' AND destroyed = false AND removed is NULL");
                 pstmt4.setLong(1, account_id);
                 rsCount = pstmt4.executeQuery();
                 if (rsCount.next()) {
@@ -248,7 +256,7 @@ public class Upgrade420to421 implements DbUpgrade {
         pstmt.executeUpdate();
         pstmt.close();
     }
-    
+
     private static void upgradeResourceCountforDomain(Connection conn, Long domain_id, String type, Long resource_count) throws SQLException {
         //update or insert into resource_count table.
         PreparedStatement pstmt = null;