cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [48/50] [abbrv] merged from master
Date Thu, 30 May 2013 00:04:42 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index 10e47d3,89739cf..b83b343
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -141,8 -161,9 +139,10 @@@ import org.apache.cloudstack.api.respon
  import org.apache.cloudstack.api.response.VpcResponse;
  import org.apache.cloudstack.api.response.VpnUsersResponse;
  import org.apache.cloudstack.api.response.ZoneResponse;
 +import org.apache.cloudstack.framework.jobs.AsyncJob;
  import org.apache.cloudstack.network.lb.ApplicationLoadBalancerRule;
+ import org.apache.cloudstack.region.PortableIp;
+ import org.apache.cloudstack.region.PortableIpRange;
  import org.apache.cloudstack.region.Region;
  import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
  import org.apache.cloudstack.usage.Usage;
@@@ -198,19 -220,8 +198,20 @@@ import com.cloud.network.Network
  import com.cloud.network.Network.Capability;
  import com.cloud.network.Network.Provider;
  import com.cloud.network.Network.Service;
 +import com.cloud.network.NetworkModel;
 +import com.cloud.network.NetworkProfile;
  import com.cloud.network.Networks.IsolationType;
  import com.cloud.network.Networks.TrafficType;
 +import com.cloud.network.PhysicalNetwork;
 +import com.cloud.network.PhysicalNetworkServiceProvider;
 +import com.cloud.network.PhysicalNetworkTrafficType;
 +import com.cloud.network.RemoteAccessVpn;
 +import com.cloud.network.Site2SiteCustomerGateway;
 +import com.cloud.network.Site2SiteVpnConnection;
 +import com.cloud.network.Site2SiteVpnGateway;
 +import com.cloud.network.VirtualRouterProvider;
 +import com.cloud.network.VpnUser;
++import com.cloud.network.VpnUserVO;
  import com.cloud.network.as.AutoScalePolicy;
  import com.cloud.network.as.AutoScaleVmGroup;
  import com.cloud.network.as.AutoScaleVmProfile;
@@@ -219,17 -230,10 +220,19 @@@ import com.cloud.network.as.Condition
  import com.cloud.network.as.ConditionVO;
  import com.cloud.network.as.Counter;
  import com.cloud.network.dao.IPAddressVO;
++import com.cloud.network.dao.LoadBalancerVO;
  import com.cloud.network.dao.NetworkVO;
  import com.cloud.network.dao.PhysicalNetworkVO;
  import com.cloud.network.router.VirtualRouter;
 +import com.cloud.network.rules.FirewallRule;
 +import com.cloud.network.rules.FirewallRuleVO;
 +import com.cloud.network.rules.HealthCheckPolicy;
 +import com.cloud.network.rules.LoadBalancer;
  import com.cloud.network.rules.LoadBalancerContainer.Scheme;
 +import com.cloud.network.rules.PortForwardingRule;
++import com.cloud.network.rules.PortForwardingRuleVO;
 +import com.cloud.network.rules.StaticNatRule;
 +import com.cloud.network.rules.StickinessPolicy;
  import com.cloud.network.security.SecurityGroup;
  import com.cloud.network.security.SecurityGroupVO;
  import com.cloud.network.security.SecurityRule;
@@@ -775,7 -779,10 +778,10 @@@ public class ApiResponseHelper implemen
              tagResponses.add(tagResponse);
          }
          lbResponse.setTags(tagResponses);
 -        
 +
+         Network ntwk = ApiDBUtils.findNetworkById(loadBalancer.getNetworkId());
+         lbResponse.setNetworkId(ntwk.getUuid());
+ 
          lbResponse.setObjectName("loadbalancer");
          return lbResponse;
      }
@@@ -3442,147 -3455,149 +3448,149 @@@
      }
  
  
 -    @Override
 -    public UsageRecordResponse createUsageResponse(Usage usageRecord) {
 -        UsageRecordResponse usageRecResponse = new UsageRecordResponse();
 -
 -        Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId());
 -        if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
 -            //find the project
 -            Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
 -            usageRecResponse.setProjectId(project.getUuid());
 -            usageRecResponse.setProjectName(project.getName());
 -        } else {
 -            usageRecResponse.setAccountId(account.getUuid());
 -            usageRecResponse.setAccountName(account.getAccountName());
 -        }
 -
 -        Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
 -        if (domain != null) {
 -            usageRecResponse.setDomainId(domain.getUuid());
 -        }
 -
 -        if (usageRecord.getZoneId() != null) {
 -            DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
 -            if (zone != null) {
 -                usageRecResponse.setZoneId(zone.getUuid());
 -            }
 -        }
 -        usageRecResponse.setDescription(usageRecord.getDescription());
 -        usageRecResponse.setUsage(usageRecord.getUsageDisplay());
 -        usageRecResponse.setUsageType(usageRecord.getUsageType());
 -        if (usageRecord.getVmInstanceId() != null) {
 -            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
 -            usageRecResponse.setVirtualMachineId(vm.getUuid());
 -        }
 -        usageRecResponse.setVmName(usageRecord.getVmName());
 -        if (usageRecord.getTemplateId() != null) {
 -            VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
 -            if (template != null) {
 -                usageRecResponse.setTemplateId(template.getUuid());
 -            }
 -        }
 -
 -        if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){
 -            ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
 -            //Service Offering Id
 -            usageRecResponse.setOfferingId(svcOffering.getUuid());
 -            //VM Instance ID
 -            VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(vm.getUuid());
 -            //Hypervisor Type
 -            usageRecResponse.setType(usageRecord.getType());
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.IP_ADDRESS){
 -            //isSourceNAT
 -            usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat"))?true:false);
 -            //isSystem
 -            usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false);
 -            //IP Address ID
 -            IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(ip.getUuid());
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){
 -            //Device Type
 -            usageRecResponse.setType(usageRecord.getType());
 -            if(usageRecord.getType().equals("DomainRouter")){
 -                //Domain Router Id
 -                VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
 -                usageRecResponse.setUsageId(vm.getUuid());
 -            } else {
 -                //External Device Host Id
 -                HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
 -                usageRecResponse.setUsageId(host.getUuid());
 -            }
 -            //Network ID
 -            NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
 -            usageRecResponse.setNetworkId(network.getUuid());
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.VOLUME){
 -            //Volume ID
 -            VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(volume.getUuid());
 -            //Volume Size
 -            usageRecResponse.setSize(usageRecord.getSize());
 -            //Disk Offering Id
 -            if(usageRecord.getOfferingId() != null){
 -                DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
 -                usageRecResponse.setOfferingId(diskOff.getUuid());
 -            }
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO){
 -            //Template/ISO ID
 -            VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(tmpl.getUuid());
 -            //Template/ISO Size
 -            usageRecResponse.setSize(usageRecord.getSize());
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){
 -            //Snapshot ID
 -            SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(snap.getUuid());
 -            //Snapshot Size
 -            usageRecResponse.setSize(usageRecord.getSize());
 -
 -        } else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){
 -            //Load Balancer Policy ID
 +	@Override
 +	public UsageRecordResponse createUsageResponse(Usage usageRecord) {
 +		UsageRecordResponse usageRecResponse = new UsageRecordResponse();
 +
 +		Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId());
 +		if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
 +			//find the project
 +			Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
 +			usageRecResponse.setProjectId(project.getUuid());
 +			usageRecResponse.setProjectName(project.getName());
 +		} else {
 +			usageRecResponse.setAccountId(account.getUuid());
 +			usageRecResponse.setAccountName(account.getAccountName());
 +		}
 +
 +		Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
 +		if (domain != null) {
 +			usageRecResponse.setDomainId(domain.getUuid());
 +		}
 +
 +		if (usageRecord.getZoneId() != null) {
 +			DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
 +			if (zone != null) {
 +				usageRecResponse.setZoneId(zone.getUuid());
 +			}
 +		}
 +		usageRecResponse.setDescription(usageRecord.getDescription());
 +		usageRecResponse.setUsage(usageRecord.getUsageDisplay());
 +		usageRecResponse.setUsageType(usageRecord.getUsageType());
 +		if (usageRecord.getVmInstanceId() != null) {
 +			VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
 +			usageRecResponse.setVirtualMachineId(vm.getUuid());
 +		}
 +		usageRecResponse.setVmName(usageRecord.getVmName());
 +		if (usageRecord.getTemplateId() != null) {
 +			VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
 +			if (template != null) {
 +				usageRecResponse.setTemplateId(template.getUuid());
 +			}
 +		}
 +
 +		if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){
 +			ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
 +			//Service Offering Id
 +			usageRecResponse.setOfferingId(svcOffering.getUuid());
 +			//VM Instance ID
 +			VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(vm.getUuid());
 +			//Hypervisor Type
 +			usageRecResponse.setType(usageRecord.getType());
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.IP_ADDRESS){
 +			//isSourceNAT
 +			usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat"))?true:false);
 +			//isSystem
 +			usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false);
 +			//IP Address ID
 +			IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(ip.getUuid());
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){
 +			//Device Type
 +			usageRecResponse.setType(usageRecord.getType());
 +			if(usageRecord.getType().equals("DomainRouter")){
 +				//Domain Router Id
 +				VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
 +				usageRecResponse.setUsageId(vm.getUuid());
 +			} else {
 +				//External Device Host Id
 +				HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
 +				usageRecResponse.setUsageId(host.getUuid());
 +			}
 +			//Network ID
 +			NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
 +			usageRecResponse.setNetworkId(network.getUuid());
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.VOLUME){
 +			//Volume ID
 +			VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(volume.getUuid());
 +			//Volume Size
 +			usageRecResponse.setSize(usageRecord.getSize());
 +			//Disk Offering Id
 +			if(usageRecord.getOfferingId() != null){
 +				DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
 +				usageRecResponse.setOfferingId(diskOff.getUuid());
 +			}
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO){
 +			//Template/ISO ID
 +			VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(tmpl.getUuid());
 +			//Template/ISO Size
 +			usageRecResponse.setSize(usageRecord.getSize());
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){
 +			//Snapshot ID
 +			SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(snap.getUuid());
 +			//Snapshot Size
 +			usageRecResponse.setSize(usageRecord.getSize());
 +
 +		} else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){
 +			//Load Balancer Policy ID
- 			usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
- 
+             LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
+             usageRecResponse.setUsageId(lb.getUuid());
 -        } else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){
 -            //Port Forwarding Rule ID
 +		} else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){
 +			//Port Forwarding Rule ID
- 			usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
+             PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
+             usageRecResponse.setUsageId(pf.getUuid());
  
 -        } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){
 -            //Network Offering Id
 -            NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
 -            usageRecResponse.setOfferingId(netOff.getUuid());
 -            //is Default
 -            usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false);
 +		} else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){
 +			//Network Offering Id
 +			NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
 +			usageRecResponse.setOfferingId(netOff.getUuid());
 +			//is Default
 +			usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false);
  
 -        } else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){
 -            //VPN User ID
 +		} else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){
 +			//VPN User ID
- 			usageRecResponse.setUsageId(usageRecord.getUsageId().toString());
+             VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
+             usageRecResponse.setUsageId(vpnUser.getUuid());
  
 -        } else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){
 -            //Security Group Id
 -            SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
 -            usageRecResponse.setUsageId(sg.getUuid());
 -        }
 -
 -        if (usageRecord.getRawUsage() != null) {
 -            DecimalFormat decimalFormat = new DecimalFormat("###########.######");
 -            usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
 -        }
 -
 -        if (usageRecord.getStartDate() != null) {
 -            usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
 -        }
 -        if (usageRecord.getEndDate() != null) {
 -            usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
 -        }
 -
 -        return usageRecResponse;
 -    }
 +		} else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){
 +			//Security Group Id
 +			SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
 +			usageRecResponse.setUsageId(sg.getUuid());
 +		}
 +
 +		if (usageRecord.getRawUsage() != null) {
 +			DecimalFormat decimalFormat = new DecimalFormat("###########.######");
 +			usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
 +		}
 +
 +		if (usageRecord.getStartDate() != null) {
 +			usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
 +		}
 +		if (usageRecord.getEndDate() != null) {
 +			usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
 +		}
 +
 +		return usageRecResponse;
 +	}
  
  
      public String getDateStringInternal(Date inputDate) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/api/ApiServer.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/async/AsyncJobManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/async/AsyncJobManagerImpl.java
index 2556219,0101a8a..cf5cc70
--- a/server/src/com/cloud/async/AsyncJobManagerImpl.java
+++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java
@@@ -770,11 -621,18 +770,18 @@@ public class AsyncJobManagerImpl extend
  
                      // limit to 100 jobs per turn, this gives cleanup throughput as 600 jobs per minute
                      // hopefully this will be fast enough to balance potential growth of job table
-                     List<AsyncJobVO> l = _jobDao.getExpiredJobs(cutTime, 100);
-                     if(l != null && l.size() > 0) {
+                     //1) Expire unfinished jobs that weren't processed yet
+                     List<AsyncJobVO> l = _jobDao.getExpiredUnfinishedJobs(cutTime, 100);
 -                    for(AsyncJobVO job : l) {
 +                        for(AsyncJobVO job : l) {
+                     	s_logger.trace("Expunging unfinished job " + job);
 -                        expungeAsyncJob(job);
 -                    }       
 +                            expungeAsyncJob(job);
 +                        }
+                     
+                     //2) Expunge finished jobs
+                     List<AsyncJobVO> completedJobs = _jobDao.getExpiredCompletedJobs(cutTime, 100);
+                     for(AsyncJobVO job : completedJobs) {
+                     	s_logger.trace("Expunging completed job " + job);
+                         expungeAsyncJob(job);
                      }
  
                      // forcefully cancel blocking queue items if they've been staying there for too long

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/configuration/ConfigurationManagerImpl.java
index e132ec6,79375f9..779ef48
--- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
+++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java
@@@ -1744,13 -1740,11 +1742,11 @@@ public class ConfigurationManagerImpl e
                  // check if zone has necessary trafficTypes before enabling
                  try {
                      PhysicalNetwork mgmtPhyNetwork;
-                     if (NetworkType.Advanced == zone.getNetworkType()) {
-                         // zone should have a physical network with public and management traffiType
-                         _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
-                         mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
-                     } else {
 -                    // zone should have a physical network with management traffiType
 -                    mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
 +                        // zone should have a physical network with management traffiType
 +                        mgmtPhyNetwork = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Management);
+                     if (NetworkType.Advanced == zone.getNetworkType() && ! zone.isSecurityGroupEnabled() ) {
+                         // advanced zone without SG should have a physical network with public Thpe
+                         _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(zoneId, TrafficType.Public);
                      }
  
                      try {
@@@ -3025,12 -3018,19 +3020,19 @@@
                                  }
                              }
                          }
 -                    }
 +    }
                  }
  
+             } else {
+                 // when there is no dhcp support in the network.
+                 if (!deletePublicIPRange(vlanDbId)) {
+                     return false;
+                 }
+                 _vlanDao.expunge(vlanDbId);
+                 return  true;
              }
          }
-        throw new InvalidParameterValueException("One of the ips in the range is used to provide Dhcp service to this subnet. cannot delete this range as ");
+         return false;
      }
  
  
@@@ -3303,43 -3303,7 +3305,7 @@@
              throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as your IP range's gateway, as per the IP range's netmask.");
          }
      }
 -    
 +
-     private void checkPrivateIpRangeErrors(Long podId, String startIP, String endIP) {
-         HostPodVO pod = _podDao.findById(podId);
-         if (pod == null) {
-             throw new InvalidParameterValueException("Please specify a valid pod.");
-         }
- 
-         // Check that the start and end IPs are valid
-         if (!NetUtils.isValidIp(startIP)) {
-             throw new InvalidParameterValueException("Please specify a valid start IP");
-         }
- 
-         if (endIP != null && !NetUtils.isValidIp(endIP)) {
-             throw new InvalidParameterValueException("Please specify a valid end IP");
-         }
- 
-         if (endIP != null && !NetUtils.validIpRange(startIP, endIP)) {
-             throw new InvalidParameterValueException("Please specify a valid IP range.");
-         }
- 
-         // Check that the IPs that are being added are compatible with the pod's
-         // CIDR
-         String cidrAddress = getCidrAddress(podId);
-         long cidrSize = getCidrSize(podId);
- 
-         if (endIP != null && !NetUtils.sameSubnetCIDR(startIP, endIP, cidrSize)) {
-             throw new InvalidParameterValueException("Please ensure that your start IP and end IP are in the same subnet, as per the pod's CIDR size.");
-         }
- 
-         if (!NetUtils.sameSubnetCIDR(startIP, cidrAddress, cidrSize)) {
-             throw new InvalidParameterValueException("Please ensure that your start IP is in the same subnet as the pod's CIDR address.");
-         }
- 
-         if (endIP != null && !NetUtils.sameSubnetCIDR(endIP, cidrAddress, cidrSize)) {
-             throw new InvalidParameterValueException("Please ensure that your end IP is in the same subnet as the pod's CIDR address.");
-         }
-     }
  
      private String getCidrAddress(String cidr) {
          String[] cidrPair = cidr.split("\\/");
@@@ -4465,9 -4419,10 +4421,10 @@@
      		return null;
      	}
      }
 -
 +    
      // Note: This method will be used for entity name validations in the coming
      // releases (place holder for now)
+     @SuppressWarnings("unused")
      private void validateEntityName(String str) {
          String forbidden = "~!@#$%^&*()+=";
          char[] searchChars = forbidden.toCharArray();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
index 9db1858,421e53f..e05780e
--- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
+++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java
@@@ -678,19 -687,28 +678,28 @@@ public class ConsoleProxyManagerImpl ex
  
          DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
  
+         NetworkVO defaultNetwork = null;
+         if (dc.getNetworkType() == NetworkType.Advanced && dc.isSecurityGroupEnabled()) {
+             List<NetworkVO> networks = _networkDao.listByZoneSecurityGroup(dataCenterId);
+             if (networks == null || networks.size() == 0) {
+                 throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc);
+             }
+             defaultNetwork = networks.get(0);
+         } else {
 -            TrafficType defaultTrafficType = TrafficType.Public;
 -            if (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()) {
 -                defaultTrafficType = TrafficType.Guest;
 -            }
 -            List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, defaultTrafficType);
 +        TrafficType defaultTrafficType = TrafficType.Public;
 +        if (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()) {
 +            defaultTrafficType = TrafficType.Guest;
 +        }
- 
 +        List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, defaultTrafficType);
  
+             // api should never allow this situation to happen
 -            if (defaultNetworks.size() != 1) {
 +        if (defaultNetworks.size() != 1) {
-             throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
+                 throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type "
+                       + defaultTrafficType + " when expect to find 1");
+             }
+              defaultNetwork = defaultNetworks.get(0);
          }
  
-         NetworkVO defaultNetwork = defaultNetworks.get(0);
- 
          List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
          List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>(offerings.size() + 1);
          NicProfile defaultNic = new NicProfile();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
index b2a6849,795b526..fa326d8
--- a/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
+++ b/server/src/com/cloud/deploy/DeploymentPlanningManagerImpl.java
@@@ -398,16 -400,16 +398,16 @@@ public class DeploymentPlanningManagerI
                              return dest;
                          }
                          // reset the avoid input to the planners
-                         resetAvoidSet(avoids, PlannerAvoidOutput);
+                         resetAvoidSet(avoids, plannerAvoidOutput);
  
 -                    } else {
 +            } else {
                          return null;
 -                    }
 +            }
                  } else {
                      dest = planner.plan(vmProfile, plan, avoids);
 -                    if (dest != null) {
 +            if (dest != null) {
                          long hostId = dest.getHost().getId();
 -                        avoids.addHost(dest.getHost().getId());
 +                avoids.addHost(dest.getHost().getId());
  
                          if (checkIfHostFitsPlannerUsage(hostId, DeploymentPlanner.PlannerResourceUsage.Shared)) {
                              // found destination

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/hypervisor/HypervisorGuruBase.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/hypervisor/HypervisorGuruBase.java
index b9e3768,d8945af..e18c164
--- a/server/src/com/cloud/hypervisor/HypervisorGuruBase.java
+++ b/server/src/com/cloud/hypervisor/HypervisorGuruBase.java
@@@ -121,7 -125,10 +125,10 @@@ public abstract class HypervisorGuruBas
          // Workaround to make sure the TO has the UUID we need for Niciri integration
          VMInstanceVO vmInstance = _virtualMachineDao.findById(to.getId());
          to.setUuid(vmInstance.getUuid());
 -
 +        
+         //
+         to.setEnableDynamicallyScaleVm(Boolean.parseBoolean(_configServer.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.ConfigurationParameterScope.zone.toString(), vm.getDataCenterId())));
+ 
          return to;
      }
  

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/NetworkManagerImpl.java
index eb18eaa,cc149a5..13a93f0
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@@ -2254,8 -2252,9 +2253,9 @@@ public class NetworkManagerImpl extend
          }
      }
  
+ 
      @Override
 -    public void removeNic(VirtualMachineProfile<? extends VMInstanceVO> vm, Nic nic) {
 +    public void removeNic(VirtualMachineProfile vm, Nic nic) {
          removeNic(vm, _nicDao.findById(nic.getId()));
      }
  
@@@ -3620,9 -3618,17 +3618,17 @@@
          List<IPAddressVO> ipsToRelease = _ipAddressDao.listByAssociatedNetwork(networkId, null);
          for (IPAddressVO ipToRelease : ipsToRelease) {
              if (ipToRelease.getVpcId() == null) {
+                 if (!ipToRelease.isPortable()) {
 -                    IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId());
 -                    assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable.";
 -                } else {
 +                IPAddressVO ip = markIpAsUnavailable(ipToRelease.getId());
 +                assert (ip != null) : "Unable to mark the ip address id=" + ipToRelease.getId() + " as unavailable.";
 +            } else {
+                     // portable IP address are associated with owner, until explicitly requested to be disassociated
+                     // so as part of network clean up just break IP association with guest network
+                     ipToRelease.setAssociatedWithNetworkId(null);
+                     _ipAddressDao.update(ipToRelease.getId(), ipToRelease);
+                     s_logger.debug("Portable IP address " + ipToRelease + " is no longer associated with any network");
+                 }
+             } else {
                  _vpcMgr.unassignIPFromVpcNetwork(ipToRelease.getId(), network.getId());
              }
          }
@@@ -4127,40 -4132,42 +4132,42 @@@
      }
      
      @Override
 -    public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile<? extends VMInstanceVO> vmProfile, boolean prepare)
 +    public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare)
              throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
              ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
 -
 -        VirtualMachine vm = vmProfile.getVirtualMachine();
 -        DataCenter dc = _configMgr.getZone(network.getDataCenterId());
 -        Host host = _hostDao.findById(vm.getHostId()); 
 -        DeployDestination dest = new DeployDestination(dc, null, null, host);
 -
 -        NicProfile nic = getNicProfileForVm(network, requested, vm);
 -
 -        //1) allocate nic (if needed) Always allocate if it is a user vm
 -        if (nic == null || (vmProfile.getType() == VirtualMachine.Type.User)) {
 -            int deviceId = _nicDao.countNics(vm.getId());
 -            
 -            nic = allocateNic(requested, network, false, 
 -                    deviceId, vmProfile).first();
 -            
 -            if (nic == null) {
 -                throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
 +                
 +                VirtualMachine vm = vmProfile.getVirtualMachine();
 +                DataCenter dc = _configMgr.getZone(network.getDataCenterId());
 +                Host host = _hostDao.findById(vm.getHostId());
 +                DeployDestination dest = new DeployDestination(dc, null, null, host);
 +                
 +                NicProfile nic = getNicProfileForVm(network, requested, vm);
 +                
 +                //1) allocate nic (if needed) Always allocate if it is a user vm
 +                if (nic == null || (vmProfile.getType() == VirtualMachine.Type.User)) {
 +                    int deviceId = _nicDao.countNics(vm.getId());
 +                    
 +                    nic = allocateNic(requested, network, false,
 +                            deviceId, vmProfile).first();
 +                    
 +                    if (nic == null) {
 +                        throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
 +                    }
 +                    
 +                    s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network);
 +                }
 +                
 +                //2) prepare nic
 +                if (prepare) {
 +                    Pair<NetworkGuru, NetworkVO> implemented = implementNetwork(nic.getNetworkId(), dest, context);
 +                    nic = prepareNic(vmProfile, dest, context, nic.getId(), implemented.second());
 +                    s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
 +                }
 +                
 +                return nic;
              }
+ 
 -            s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network); 
 -        }
 -
 -        //2) prepare nic
 -        if (prepare) {
 -            Pair<NetworkGuru, NetworkVO> implemented = implementNetwork(nic.getNetworkId(), dest, context);
 -            nic = prepareNic(vmProfile, dest, context, nic.getId(), implemented.second());
 -            s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
 -        }
 -        
 -        return nic;
 -    }
 -
+ 
      @Override
      public List<NicProfile> getNicProfiles(VirtualMachine vm) {
          List<NicVO> nics = _nicDao.listByVmId(vm.getId());
@@@ -4241,7 -4250,8 +4250,8 @@@
          }
          return elements;
      }
 -
 +    
+ 
      @Override
      public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) {
          //only one provider per Static nat service is supoprted
@@@ -4272,10 -4283,11 +4283,11 @@@
          }
                  
          assert lbElement != null;
 -        assert lbElement instanceof LoadBalancingServiceProvider; 
 -        return (LoadBalancingServiceProvider)lbElement;        
 +        assert lbElement instanceof LoadBalancingServiceProvider;
 +        return (LoadBalancingServiceProvider)lbElement;
      }
 -
 +    
+ 
      @Override
      public boolean isNetworkInlineMode(Network network) {
          NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
@@@ -4291,47 -4303,50 +4303,50 @@@
          return rules.size();
      }
  
+ 
 -    @Override
 +         @Override
      public boolean isSecondaryIpSetForNic(long nicId) {
          NicVO nic = _nicDao.findById(nicId);
          return nic.getSecondaryIp();
      }
  
-          @Override
-         public boolean removeVmSecondaryIpsOfNic(long nicId) {
+ 
+     private boolean removeVmSecondaryIpsOfNic(long nicId) {
 -       Transaction txn = Transaction.currentTxn();
 -       txn.start();
 -       List <NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
 -       if (ipList != null) {
 -           for (NicSecondaryIpVO ip: ipList) {
 -               _nicSecondaryIpDao.remove(ip.getId());
 +           Transaction txn = Transaction.currentTxn();
 +           txn.start();
 +           List <NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
 +           if (ipList != null) {
 +               for (NicSecondaryIpVO ip: ipList) {
 +                   _nicSecondaryIpDao.remove(ip.getId());
 +               }
 +               s_logger.debug("Revoving nic secondary ip entry ...");
             }
 -           s_logger.debug("Revoving nic secondary ip entry ...");
 -       }
 -       txn.commit();
 -       return true;
 -    }
 +           txn.commit();
 +           return true;
 +        }
  
+ 
 -    @Override
 -    public String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod,Account owner,
 -            String requestedIp) throws InsufficientAddressCapacityException {
 -        PublicIp ip = assignPublicIpAddress(dc.getId(), null, owner, VlanType.DirectAttached, networkId, requestedIp, false);
 -        if (ip == null) {
 -            s_logger.debug("There is no free public ip address");
 -            return null;
 +        @Override
 +        public String allocatePublicIpForGuestNic(Long networkId, DataCenter dc, Pod pod,Account owner,
 +                String requestedIp) throws InsufficientAddressCapacityException {
 +            PublicIp ip = assignPublicIpAddress(dc.getId(), null, owner, VlanType.DirectAttached, networkId, requestedIp, false);
 +            if (ip == null) {
 +                s_logger.debug("There is no free public ip address");
 +                return null;
 +            }
 +            Ip ipAddr = ip.getAddress();
 +            return ipAddr.addr();
          }
 -        Ip ipAddr = ip.getAddress();
 -        return ipAddr.addr();
 -    }
 -
 +        
+ 
 -    @Override
 -    public NicVO savePlaceholderNic(Network network, String ip4Address, Type vmType) {
 -        NicVO nic = new NicVO(null, null, network.getId(), null); 
 -        nic.setIp4Address(ip4Address);
 -        nic.setReservationStrategy(ReservationStrategy.PlaceHolder);
 -        nic.setState(Nic.State.Reserved);
 -        nic.setVmType(vmType);
 -        return _nicDao.persist(nic);
 -    }
 +        @Override
 +        public NicVO savePlaceholderNic(Network network, String ip4Address, Type vmType) {
 +            NicVO nic = new NicVO(null, null, network.getId(), null);
 +            nic.setIp4Address(ip4Address);
 +            nic.setReservationStrategy(ReservationStrategy.PlaceHolder);
 +            nic.setState(Nic.State.Reserved);
 +            nic.setVmType(vmType);
 +            return _nicDao.persist(nic);
 +        }
          
   }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
index 4e01cdb,633357e..f9bbf1f
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java
@@@ -1980,7 -1990,11 +1991,11 @@@ public class LoadBalancingRulesManagerI
          if (zoneId != null) {
              sc.setJoinParameters("ipSearch", "zoneId", zoneId);
          }
 -        
 +
+         if (networkId != null) {
+             sc.setParameters("networkId", networkId);
+         }
+ 
          if (tags != null && !tags.isEmpty()) {
              int count = 0;
              sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.LoadBalancer.toString());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/resource/ResourceManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/server/ManagementServerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/storage/VolumeManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/VolumeManagerImpl.java
index d68b6d9,aedb68e..f91c971
--- a/server/src/com/cloud/storage/VolumeManagerImpl.java
+++ b/server/src/com/cloud/storage/VolumeManagerImpl.java
@@@ -385,10 -368,10 +386,10 @@@ public class VolumeManagerImpl extends 
  
          validateVolume(caller, ownerId, zoneId, volumeName, url, format);
          
-         VolumeVO volume = persistVolume(caller, ownerId, zoneId, volumeName,
+         VolumeVO volume = persistVolume(owner, zoneId, volumeName,
                  url, cmd.getFormat());
          
 -        VolumeInfo vol = this.volFactory.getVolume(volume.getId());
 +        VolumeInfo vol = volFactory.getVolume(volume.getId());
          
          RegisterVolumePayload payload = new RegisterVolumePayload(cmd.getUrl(), cmd.getChecksum(),
                  cmd.getFormat());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
index ba74985,c343286..10264d6
--- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
+++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java
@@@ -528,19 -538,27 +528,27 @@@ public class SecondaryStorageManagerImp
          DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
          DataCenter dc = _dcDao.findById(plan.getDataCenterId());
          
+         NetworkVO defaultNetwork = null;
+         if (dc.getNetworkType() == NetworkType.Advanced && dc.isSecurityGroupEnabled()) {
+             List<NetworkVO> networks = _networkDao.listByZoneSecurityGroup(dataCenterId);
+             if (networks == null || networks.size() == 0) {
+                 throw new CloudRuntimeException("Can not found security enabled network in SG Zone " + dc);
+             }
+             defaultNetwork = networks.get(0);
+         } else {
 -            TrafficType defaultTrafficType = TrafficType.Public;
 +        TrafficType defaultTrafficType = TrafficType.Public;
+ 
 -            if (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()) {
 -                defaultTrafficType = TrafficType.Guest;
 -            }
 -            List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, defaultTrafficType);
 +        if (dc.getNetworkType() == NetworkType.Basic || dc.isSecurityGroupEnabled()) {
 +        	defaultTrafficType = TrafficType.Guest;
 +        }
-         
 +        List<NetworkVO> defaultNetworks = _networkDao.listByZoneAndTrafficType(dataCenterId, defaultTrafficType);
-         
-         //api should never allow this situation to happen
+             // api should never allow this situation to happen
 -            if (defaultNetworks.size() != 1) {
 +        if (defaultNetworks.size() != 1) {
-         	throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type " + defaultTrafficType + " when expect to find 1");
+                 throw new CloudRuntimeException("Found " + defaultNetworks.size() + " networks of type "
+                                 + defaultTrafficType + " when expect to find 1");
+             }
+             defaultNetwork = defaultNetworks.get(0);
          }
-         
-         NetworkVO defaultNetwork = defaultNetworks.get(0);
  
          List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemControlNetwork, NetworkOfferingVO.SystemManagementNetwork, NetworkOfferingVO.SystemStorageNetwork);
          List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<Pair<NetworkVO, NicProfile>>(offerings.size() + 1);

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/template/TemplateManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/user/AccountManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/vm/UserVmManagerImpl.java
index 1d5b973,a734d44..06c1d5d
--- a/server/src/com/cloud/vm/UserVmManagerImpl.java
+++ b/server/src/com/cloud/vm/UserVmManagerImpl.java
@@@ -162,6 -167,6 +162,7 @@@ import com.cloud.projects.Project.ListP
  import com.cloud.projects.ProjectManager;
  import com.cloud.resource.ResourceManager;
  import com.cloud.resource.ResourceState;
++import com.cloud.server.ConfigurationServer;
  import com.cloud.server.Criteria;
  import com.cloud.service.ServiceOfferingVO;
  import com.cloud.service.dao.ServiceOfferingDao;
@@@ -1114,10 -1130,33 +1126,33 @@@ public class UserVmManagerImpl extends 
              throw new InvalidParameterValueException("Only scaling up the vm is supported, new service offering should have both cpu and memory greater than the old values");
          }
  
+         // Check resource limits
+         if (newCpu > currentCpu) {
+             _resourceLimitMgr.checkResourceLimit(caller, ResourceType.cpu,
+                     newCpu - currentCpu);
+         }
+         if (newMemory > currentMemory) {
+             _resourceLimitMgr.checkResourceLimit(caller, ResourceType.memory,
+                     newMemory - currentMemory);
+         }
+ 
          // Dynamically upgrade the running vms
 -        boolean success = false;
 +            boolean success = false;
          if(vmInstance.getState().equals(State.Running)){
              int retry = _scaleRetry;
+             boolean enableDynamicallyScaleVm = Boolean.parseBoolean(_configServer.getConfigValue(Config.EnableDynamicallyScaleVm.key(), Config.ConfigurationParameterScope.zone.toString(), vmInstance.getDataCenterId()));
+             if(!enableDynamicallyScaleVm){
+                throw new PermissionDeniedException("Dynamically scaling virtual machines is disabled for this zone, please contact your admin");
+             }
+ 
+             // Increment CPU and Memory count accordingly.
+             if (newCpu > currentCpu) {
+                 _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long (newCpu - currentCpu));
+             }
+             if (newMemory > currentMemory) {
+                 _resourceLimitMgr.incrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long (newMemory - currentMemory));
+             }
+ 
              while (retry-- != 0) { // It's != so that it can match -1.
                  try{
                      // #1 Check existing host has capacity
@@@ -1132,9 -1171,9 +1167,7 @@@
                      // #3 scale the vm now
                      _itMgr.upgradeVmDb(vmId, newServiceOfferingId);
                      vmInstance = _vmInstanceDao.findById(vmId);
-                     _itMgr.reConfigureVm(vmInstance, oldServiceOffering, existingHostHasCapacity);
-                     success = true;
-                     return success;
 -                    vmInstance = _itMgr.reConfigureVm(vmInstance, currentServiceOffering, existingHostHasCapacity);
 -                    success = true;
 -                    return success;
++                    return _itMgr.reConfigureVm(vmInstance, currentServiceOffering, existingHostHasCapacity);
                  }catch(InsufficientCapacityException e ){
                      s_logger.warn("Received exception while scaling ",e);
                  } catch (ResourceUnavailableException e) {
@@@ -1147,8 -1186,17 +1180,17 @@@
                      s_logger.warn("Received exception while scaling ",e);
                  }finally{
                      if(!success){
-                         _itMgr.upgradeVmDb(vmId, oldServiceOffering.getId()); // rollback
+                         _itMgr.upgradeVmDb(vmId, currentServiceOffering.getId()); // rollback
+                         // Decrement CPU and Memory count accordingly.
+                         if (newCpu > currentCpu) {
+                             _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.cpu, new Long (newCpu - currentCpu));
 -                        }
 +                    }
+                         if (newMemory > currentMemory) {
+                             _resourceLimitMgr.decrementResourceCount(caller.getAccountId(), ResourceType.memory, new Long (newMemory - currentMemory));
+                         }
+                     }
+ 
+ 
                  }
              }
          }
@@@ -4266,22 -4338,31 +4323,30 @@@
  
          if (needRestart) {
              try {
 -                _itMgr.stop(vm, user, caller);
 -            } catch (ResourceUnavailableException e) {
 -                s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
 -                CloudRuntimeException ex = new CloudRuntimeException(
 -                        "Stop vm failed for specified vmId");
 +                _itMgr.stop(vm.getUuid(), user, caller);
 +            } catch (CloudRuntimeException e) {
 +                s_logger.debug("Stop vm " + vm.getUuid() + " failed");
 +                CloudRuntimeException ex = new CloudRuntimeException("Stop vm failed for specified vmId");
-                 ex.addProxyObject(vm, vmId, "vmId");
+                 ex.addProxyObject(vm.getUuid(), "vmId");
                  throw ex;
              }
          }
  
-         /* If new template is provided allocate a new volume from new template otherwise allocate new volume from original template */
+         /* If new template/ISO is provided allocate a new volume from new template/ISO otherwise allocate new volume from original template/ISO */
          VolumeVO newVol = null;
-         if (newTemplateId != null){
+         if (newTemplateId != null) {
+             if (isISO) {
+                 newVol = volumeMgr.allocateDuplicateVolume(root, null);
+                 vm.setIsoId(newTemplateId);
+                 vm.setGuestOSId(template.getGuestOSId());
+                 vm.setTemplateId(newTemplateId);
+                 _vmDao.update(vmId, vm);
+             } else {
 -                newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
 -                vm.setGuestOSId(template.getGuestOSId());
 -                vm.setTemplateId(newTemplateId);
 -                _vmDao.update(vmId, vm);
 +            newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
 +            vm.setGuestOSId(template.getGuestOSId());
 +            vm.setTemplateId(newTemplateId);
 +            _vmDao.update(vmId, vm);
+             }
          } else {
              newVol = volumeMgr.allocateDuplicateVolume(root, null);
          }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/src/com/cloud/vm/VirtualMachineManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/test/com/cloud/network/MockNetworkManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/test/com/cloud/vm/UserVmManagerTest.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/vm/UserVmManagerTest.java
index d47c8e7,5eedfa5..5c4e5e4
--- a/server/test/com/cloud/vm/UserVmManagerTest.java
+++ b/server/test/com/cloud/vm/UserVmManagerTest.java
@@@ -201,9 -199,10 +200,10 @@@ public class UserVmManagerTest 
          doReturn(false).when(_rootVols).isEmpty();
          when(_rootVols.get(eq(0))).thenReturn(_volumeMock);
          doReturn(3L).when(_volumeMock).getTemplateId();
+         doReturn(ImageFormat.VHD).when(_templateMock).getFormat();
          when(_templateDao.findById(anyLong())).thenReturn(_templateMock);
          doNothing().when(_accountMgr).checkAccess(_account, null, true, _templateMock);
 -        when(_itMgr.stop(_vmMock, _userMock, _account)).thenReturn(true);
 +//        when(_itMgr.stop(null, _userMock, _account)).thenReturn(true);
          when(_storageMgr.allocateDuplicateVolume(_volumeMock, 14L)).thenReturn(_volumeMock);
          when(_templateMock.getGuestOSId()).thenReturn(5L);
          doNothing().when(_vmMock).setGuestOSId(anyLong());

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
----------------------------------------------------------------------
diff --cc server/test/com/cloud/vpc/MockNetworkManagerImpl.java
index 5e0f054,d46be7c..de998fe
--- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
+++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java
@@@ -1142,10 -1142,7 +1142,7 @@@ public class MockNetworkManagerImpl ext
          return false;
      }
  
 -    
 +
- 
- 
- 
      /* (non-Javadoc)
       * @see com.cloud.network.NetworkManager#releaseNic(com.cloud.vm.VirtualMachineProfile, com.cloud.vm.Nic)
       */
@@@ -1172,24 -1165,7 +1165,7 @@@
          return null;
      }
  
 -    
 +
- 
- 
- 
-     /* (non-Javadoc)
-      * @see com.cloud.network.NetworkManager#assignVpnGatewayIpAddress(long, com.cloud.user.Account, long)
-      */
-     @Override
-     public PublicIp assignVpnGatewayIpAddress(long dcId, Account owner, long vpcId)
-             throws InsufficientAddressCapacityException, ConcurrentOperationException {
-         // TODO Auto-generated method stub
-         return null;
-     }
- 
- 
- 
- 
- 
      /* (non-Javadoc)
       * @see com.cloud.network.NetworkManager#markPublicIpAsAllocated(com.cloud.network.IPAddressVO)
       */

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/setup/db/db/schema-410to420.sql
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/7bdddd07/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
----------------------------------------------------------------------
diff --cc utils/src/com/cloud/utils/exception/CloudRuntimeException.java
index 30d55b4,d3b4c19..0d72297
--- a/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
+++ b/utils/src/com/cloud/utils/exception/CloudRuntimeException.java
@@@ -17,10 -17,7 +17,9 @@@
  package com.cloud.utils.exception;
  
  import java.util.ArrayList;
 +import java.util.List;
  
- import com.cloud.utils.AnnotationHelper;
 +import com.cloud.utils.Pair;
  import com.cloud.utils.SerialVersionUID;
  
  /**
@@@ -30,11 -27,9 +29,11 @@@ public class CloudRuntimeException exte
  
      private static final long serialVersionUID = SerialVersionUID.CloudRuntimeException;
  
-     // This holds a list of uuids and their names. Add uuid:fieldname pairs
-     protected ArrayList<String> idList = new ArrayList<String>();
+     // This holds a list of uuids and their descriptive names.
+     protected ArrayList<ExceptionProxyObject> idList = new ArrayList<ExceptionProxyObject>();
  
 +    protected ArrayList<Pair<Class<?>, String>> uuidList = new ArrayList<Pair<Class<?>, String>>();
 +
      protected int csErrorCode;
  
  
@@@ -52,28 -47,21 +51,27 @@@
          super();
          setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName()));
      }
 -
 +    
-     public void addProxyObject(String uuid) {
-         idList.add(uuid);
-         return;
+     public void addProxyObject(ExceptionProxyObject obj){
+         idList.add(obj);
      }
 -    
 +
-     public void addProxyObject(Object voObj, Long id, String idFieldName) {
-         // Get the VO object's table name.
-         String tablename = AnnotationHelper.getTableName(voObj);
-         if (tablename != null) {
-             addProxyObject(tablename, id, idFieldName);
+     public void addProxyObject(String uuid) {
+         idList.add(new ExceptionProxyObject(uuid, null));
 -    }
 +        }
-         return;
+ 
+     public void addProxyObject(String voObjUuid, String description) {
+         ExceptionProxyObject proxy = new ExceptionProxyObject(voObjUuid, description);
+         idList.add(proxy);
      }
  
 +    @Override
 +    public CloudRuntimeException add(Class<?> entity, String uuid) {
 +        uuidList.add(new Pair<Class<?>, String>(entity, uuid));
 +        return this;
 +    }
 +
-     public ArrayList<String> getIdProxyList() {
+     public ArrayList<ExceptionProxyObject> getIdProxyList() {
          return idList;
      }
  


Mime
View raw message