You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ke...@apache.org on 2013/02/02 00:27:31 UTC

[38/50] [abbrv] Sync javelin with master up to 894cb8f7d9fc8b5561754a9fa541fef8f235148a

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
----------------------------------------------------------------------
diff --cc awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
index 9c0dc67,17752af..8a5a733
--- a/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
+++ b/awsapi/src/com/cloud/bridge/service/core/ec2/EC2Engine.java
@@@ -78,461 -83,449 +78,464 @@@ import com.cloud.utils.component.Manage
   * EC2Engine processes the ec2 commands and calls their cloudstack analogs
   *
   */
 -public class EC2Engine {
 -	protected final static Logger logger = Logger.getLogger(EC2Engine.class);
 -	String managementServer = null;
 -	String cloudAPIPort = null;
 -
 -	protected final CloudStackSvcOfferingDao scvoDao = ComponentLocator.inject(CloudStackSvcOfferingDaoImpl.class);
 -    protected final OfferingDaoImpl ofDao = ComponentLocator.inject(OfferingDaoImpl.class);
 -    CloudStackAccountDao accDao = ComponentLocator.inject(CloudStackAccountDaoImpl.class);
 -	private CloudStackApi _eng = null;
 -	
 -	private CloudStackAccount currentAccount = null;
 -
 -	public EC2Engine() throws IOException {
 -		loadConfigValues();
 +@Component
 +public class EC2Engine extends ManagerBase {
 +    protected final static Logger logger = Logger.getLogger(EC2Engine.class);
 +    String managementServer = null;
 +    String cloudAPIPort = null;
 +
 +    @Inject CloudStackSvcOfferingDao scvoDao;
 +    @Inject OfferingDao ofDao;
 +    @Inject CloudStackAccountDao accDao;
 +    
 +    private CloudStackApi _eng = null;
 +
 +    private CloudStackAccount currentAccount = null;
 +
 +    public EC2Engine() throws IOException {
 +    }
 +    
 +	@Override
 +	public boolean configure(String name, Map<String, Object> params)
 +			throws ConfigurationException {
 +		
 +		try {
 +			loadConfigValues();
 +		} catch(IOException e) {
 +			logger.error("EC2Engine Configuration failure", e);
 +			throw new ConfigurationException("EC2Engine configuration failure");
 +		}
 +        return true;
  	}
  
 -	/**
 -	 * Which management server to we talk to?  
 -	 * Load a mapping form Amazon values for 'instanceType' to cloud defined
 -	 * diskOfferingId and serviceOfferingId.
 -	 * 
 -	 * @throws IOException
 -	 */
 -	private void loadConfigValues() throws IOException {
 -		File propertiesFile = ConfigurationHelper.findConfigurationFile("ec2-service.properties");
 -		if (null != propertiesFile) {
 -			logger.info("Use EC2 properties file: " + propertiesFile.getAbsolutePath());
 -			Properties EC2Prop = new Properties();
 -			try {
 -				EC2Prop.load( new FileInputStream( propertiesFile ));
 -			} catch (FileNotFoundException e) {
 -				logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
 -			} catch (IOException e) {
 -				logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
 -			}
 -			managementServer = EC2Prop.getProperty( "managementServer" );
 -			cloudAPIPort = EC2Prop.getProperty( "cloudAPIPort", null );
 -			
 -			try {
 -				if(ofDao.getOfferingCount() == 0) {
 -					String strValue = EC2Prop.getProperty("m1.small.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m1.small", strValue);
  
 -					strValue = EC2Prop.getProperty("m1.large.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m1.large", strValue);
 +    /**
 +     * Which management server to we talk to?  
 +     * Load a mapping form Amazon values for 'instanceType' to cloud defined
 +     * diskOfferingId and serviceOfferingId.
 +     * 
 +     * @throws IOException
 +     */
 +    private void loadConfigValues() throws IOException {
 +        File propertiesFile = ConfigurationHelper.findConfigurationFile("ec2-service.properties");
 +        if (null != propertiesFile) {
 +            logger.info("Use EC2 properties file: " + propertiesFile.getAbsolutePath());
 +            Properties EC2Prop = new Properties();
 +            try {
 +                EC2Prop.load( new FileInputStream( propertiesFile ));
 +            } catch (FileNotFoundException e) {
 +                logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
 +            } catch (IOException e) {
 +                logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
 +            }
 +            managementServer = EC2Prop.getProperty( "managementServer" );
 +            cloudAPIPort = EC2Prop.getProperty( "cloudAPIPort", null );
 +
 +            try {
 +                if(ofDao.getOfferingCount() == 0) {
 +                    String strValue = EC2Prop.getProperty("m1.small.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m1.small", strValue);
  
 -					strValue = EC2Prop.getProperty("m1.xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m1.xlarge", strValue);
 +                    strValue = EC2Prop.getProperty("m1.large.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m1.large", strValue);
  
 -					strValue = EC2Prop.getProperty("c1.medium.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("c1.medium", strValue);
 +                    strValue = EC2Prop.getProperty("m1.xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m1.xlarge", strValue);
  
 -					strValue = EC2Prop.getProperty("c1.xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("c1.xlarge", strValue);
 +                    strValue = EC2Prop.getProperty("c1.medium.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("c1.medium", strValue);
  
 -					strValue = EC2Prop.getProperty("m2.xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m2.xlarge", strValue);
 +                    strValue = EC2Prop.getProperty("c1.xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("c1.xlarge", strValue);
  
 -					strValue = EC2Prop.getProperty("m2.2xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m2.2xlarge", strValue);
 +                    strValue = EC2Prop.getProperty("m2.xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m2.xlarge", strValue);
  
 -					strValue = EC2Prop.getProperty("m2.4xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("m2.4xlarge", strValue);
 +                    strValue = EC2Prop.getProperty("m2.2xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m2.2xlarge", strValue);
  
 -					strValue = EC2Prop.getProperty("cc1.4xlarge.serviceId");
 -					if(strValue != null) ofDao.setOfferMapping("cc1.4xlarge", strValue);
 -				}
 -			} catch(Exception e) {
 -				logger.error("Unexpected exception ", e);
 -			}
 -		} else logger.error( "ec2-service.properties not found" );
 -	}
 -	
 -	/**
 -	 * Helper function to manage the api connection
 -	 * 
 -	 * @return
 -	 */
 -	private CloudStackApi getApi() {
 -		if (_eng == null) {
 -		    _eng = new CloudStackApi(managementServer, cloudAPIPort, false);
 -		}
 -		// regardless of whether _eng is initialized, we must make sure 
 -		// access/secret keys are current with what's in the UserCredentials
 +                    strValue = EC2Prop.getProperty("m2.4xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("m2.4xlarge", strValue);
 +
 +                    strValue = EC2Prop.getProperty("cc1.4xlarge.serviceId");
 +                    if(strValue != null) ofDao.setOfferMapping("cc1.4xlarge", strValue);
 +                }
 +            } catch(Exception e) {
 +                logger.error("Unexpected exception ", e);
 +            }
 +        } else logger.error( "ec2-service.properties not found" );
 +    }
 +
 +    /**
 +     * Helper function to manage the api connection
 +     * 
 +     * @return
 +     */
 +    private CloudStackApi getApi() {
 +        if (_eng == null) {
 +            _eng = new CloudStackApi(managementServer, cloudAPIPort, false);
 +        }
 +        // regardless of whether _eng is initialized, we must make sure 
 +        // access/secret keys are current with what's in the UserCredentials
          _eng.setApiKey(UserContext.current().getAccessKey());
          _eng.setSecretKey(UserContext.current().getSecretKey());
 -		return _eng;
 -	}
 +        return _eng;
 +    }
  
  
 -	/**
 -	 * Verifies account can access CloudStack
 -	 * 
 -	 * @param accessKey
 -	 * @param secretKey
 -	 * @return
 -	 * @throws EC2ServiceException
 -	 */
 -	public boolean validateAccount( String accessKey, String secretKey ) throws EC2ServiceException {
 -		String oldApiKey = null;
 -		String oldSecretKey = null;
 +    /**
 +     * Verifies account can access CloudStack
 +     * 
 +     * @param accessKey
 +     * @param secretKey
 +     * @return
 +     * @throws EC2ServiceException
 +     */
 +    public boolean validateAccount( String accessKey, String secretKey ) throws EC2ServiceException {
 +        String oldApiKey = null;
 +        String oldSecretKey = null;
  
 -		if (accessKey == null || secretKey == null) {
 +        if (accessKey == null || secretKey == null) {
              return false;
          }
 -		
 -		// okay, instead of using the getApi() nonsense for validate, we are going to manage _eng
 -		if (_eng == null) {
 +
 +        // okay, instead of using the getApi() nonsense for validate, we are going to manage _eng
 +        if (_eng == null) {
              _eng = new CloudStackApi(managementServer, cloudAPIPort, false);
 -		}
 -		
 -		try {
 -		    oldApiKey = _eng.getApiKey(); 
 -		    oldSecretKey = _eng.getSecretKey();
 -		} catch(Exception e) {
 -		    // we really don't care, and expect this
 -		}
 +        }
 +
          try {
 -			_eng.setApiKey(accessKey);
 -			_eng.setSecretKey(secretKey);
 -			List<CloudStackAccount> accts = _eng.listAccounts(null, null, null, null, null, null, null, null);
 -			if (oldApiKey != null && oldSecretKey != null) {
 -				_eng.setApiKey(oldApiKey);
 -				_eng.setSecretKey(oldSecretKey);
 -			}
 -			if (accts == null) {
 -				return false;
 -			}
 -			return true;
 -		} catch(Exception e) {
 -			logger.error("Validate account failed!");
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            oldApiKey = _eng.getApiKey(); 
 +            oldSecretKey = _eng.getSecretKey();
 +        } catch(Exception e) {
 +            // we really don't care, and expect this
 +        }
 +        try {
 +            _eng.setApiKey(accessKey);
 +            _eng.setSecretKey(secretKey);
 +            List<CloudStackAccount> accts = _eng.listAccounts(null, null, null, null, null, null, null, null);
 +            if (oldApiKey != null && oldSecretKey != null) {
 +                _eng.setApiKey(oldApiKey);
 +                _eng.setSecretKey(oldSecretKey);
 +            }
 +            if (accts == null) {
 +                return false;
 +            }
 +            return true;
 +        } catch(Exception e) {
 +            logger.error("Validate account failed!");
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * Creates a security group
 -	 * 
 -	 * @param groupName
 -	 * @param groupDesc
 -	 * @return
 -	 */
 -	public Boolean createSecurityGroup(String groupName, String groupDesc) {
 -		try {
 -			CloudStackSecurityGroup grp = getApi().createSecurityGroup(groupName, null, groupDesc, null);
 -			if (grp != null && grp.getId() != null) {
 -				return true;
 -			}
 -			return false;
 -		} catch( Exception e ) {
 -			logger.error( "EC2 CreateSecurityGroup - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +    /**
 +     * Creates a security group
 +     * 
 +     * @param groupName
 +     * @param groupDesc
 +     * @return
 +     */
 +    public Boolean createSecurityGroup(String groupName, String groupDesc) {
 +        try {
 +            CloudStackSecurityGroup grp = getApi().createSecurityGroup(groupName, null, groupDesc, null);
 +            if (grp != null && grp.getId() != null) {
 +                return true;
 +            }
 +            return false;
 +        } catch( Exception e ) {
 +            logger.error( "EC2 CreateSecurityGroup - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * Deletes a security group
 -	 * 
 -	 * @param groupName
 -	 * @return
 -	 */
 -	public boolean deleteSecurityGroup(String groupName) {
 -		try {
 -			CloudStackInfoResponse resp = getApi().deleteSecurityGroup(null, null, null, groupName);
 -			if (resp != null) {
 -				return resp.getSuccess();
 -			}
 -			return false;
 -		} catch( Exception e ) {
 -			logger.error( "EC2 DeleteSecurityGroup - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +    /**
 +     * Deletes a security group
 +     * 
 +     * @param groupName
 +     * @return
 +     */
 +    public boolean deleteSecurityGroup(String groupName) {
 +        try {
 +            CloudStackInfoResponse resp = getApi().deleteSecurityGroup(null, null, null, groupName);
 +            if (resp != null) {
 +                return resp.getSuccess();
 +            }
 +            return false;
 +        } catch( Exception e ) {
 +            logger.error( "EC2 DeleteSecurityGroup - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * returns a list of security groups
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2DescribeSecurityGroupsResponse describeSecurityGroups(EC2DescribeSecurityGroups request) 
 -	{
 -		try {
 -			EC2DescribeSecurityGroupsResponse response = listSecurityGroups( request.getGroupSet());
 -			EC2GroupFilterSet gfs = request.getFilterSet();
 -
 -			if ( null == gfs )
 -				return response;
 -			else return gfs.evaluate( response );     
 -		} catch( Exception e ) {
 -			logger.error( "EC2 DescribeSecurityGroups - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occurred.");
 -		}
 -	}
 +    /**
 +     * returns a list of security groups
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2DescribeSecurityGroupsResponse describeSecurityGroups(EC2DescribeSecurityGroups request) 
 +    {
 +        try {
 +            EC2DescribeSecurityGroupsResponse response = listSecurityGroups( request.getGroupSet());
 +            EC2GroupFilterSet gfs = request.getFilterSet();
  
 -	/**
 -	 * CloudStack supports revoke only by using the ruleid of the ingress rule.   
 -	 * We list all security groups and find the matching group and use the first ruleId we find.
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public boolean revokeSecurityGroup( EC2AuthorizeRevokeSecurityGroup request ) 
 -	{
 -		if (null == request.getName()) throw new EC2ServiceException(ServerError.InternalError, "Name is a required parameter");
 -		try {   
 -			String[] groupSet = new String[1];
 -			groupSet[0] = request.getName();
 -			String ruleId = null;
 -	
 -			EC2IpPermission[] items = request.getIpPermissionSet();
 -
 -			EC2DescribeSecurityGroupsResponse response = listSecurityGroups( groupSet );
 -			EC2SecurityGroup[] groups = response.getGroupSet();
 -
 -			for (EC2SecurityGroup group : groups) {
 -				EC2IpPermission[] perms = group.getIpPermissionSet();
 -				for (EC2IpPermission perm : perms) {
 -					ruleId = doesRuleMatch( items[0], perm );
 -					if (ruleId != null) break;
 -				}
 -			}
 +            if ( null == gfs )
 +                return response;
 +            else return gfs.evaluate( response );     
 +        } catch( Exception e ) {
 +            logger.error( "EC2 DescribeSecurityGroups - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occurred.");
 +        }
 +    }
 +
 +    /**
 +     * CloudStack supports revoke only by using the ruleid of the ingress rule.   
 +     * We list all security groups and find the matching group and use the first ruleId we find.
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public boolean revokeSecurityGroup( EC2AuthorizeRevokeSecurityGroup request ) 
 +    {
 +        if (null == request.getName()) throw new EC2ServiceException(ServerError.InternalError, "Name is a required parameter");
 +        try {   
 +            String[] groupSet = new String[1];
 +            groupSet[0] = request.getName();
 +            String ruleId = null;
 +
 +            EC2IpPermission[] items = request.getIpPermissionSet();
 +
 +            EC2DescribeSecurityGroupsResponse response = listSecurityGroups( groupSet );
 +            EC2SecurityGroup[] groups = response.getGroupSet();
 +
 +            for (EC2SecurityGroup group : groups) {
 +                EC2IpPermission[] perms = group.getIpPermissionSet();
 +                for (EC2IpPermission perm : perms) {
 +                    ruleId = doesRuleMatch( items[0], perm );
 +                    if (ruleId != null) break;
 +                }
 +            }
  
 -			if (null == ruleId)
 -				throw new EC2ServiceException(ClientError.InvalidGroup_NotFound, "Cannot find matching ruleid.");
 +            if (null == ruleId)
 +                throw new EC2ServiceException(ClientError.InvalidGroup_NotFound, "Cannot find matching ruleid.");
  
 -			CloudStackInfoResponse resp = getApi().revokeSecurityGroupIngress(ruleId);
 +            CloudStackInfoResponse resp = getApi().revokeSecurityGroupIngress(ruleId);
-             if (resp != null && resp.getId() != null) {
+             if (resp != null) {
 -				return resp.getSuccess();
 -			}
 -			return false;
 -		} catch( Exception e ) {
 -			logger.error( "EC2 revokeSecurityGroupIngress" + " - " + e.getMessage());
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		} 	
 -	}
 +                return resp.getSuccess();
 +            }
 +            return false;
 +        } catch( Exception e ) {
 +            logger.error( "EC2 revokeSecurityGroupIngress" + " - " + e.getMessage());
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        } 	
 +    }
  
 -	/**
 -	 * authorizeSecurityGroup
 -	 * 
 -	 * @param request - ip permission parameters
 -	 */
 -	public boolean authorizeSecurityGroup(EC2AuthorizeRevokeSecurityGroup request ) 
 -	{
 -		if (null == request.getName()) throw new EC2ServiceException(ServerError.InternalError, "Name is a required parameter");
 +    /**
 +     * authorizeSecurityGroup
 +     * 
 +     * @param request - ip permission parameters
 +     */
 +    public boolean authorizeSecurityGroup(EC2AuthorizeRevokeSecurityGroup request ) 
 +    {
 +        if (null == request.getName()) throw new EC2ServiceException(ServerError.InternalError, "Name is a required parameter");
  
 -		EC2IpPermission[] items = request.getIpPermissionSet();
 +        EC2IpPermission[] items = request.getIpPermissionSet();
  
 -		try {
 -			for (EC2IpPermission ipPerm : items) {
 -				EC2SecurityGroup[] groups = ipPerm.getUserSet();
 -				
 -				List<CloudStackKeyValue> secGroupList = new ArrayList<CloudStackKeyValue>(); 
 -				for (EC2SecurityGroup group : groups) {
 -					CloudStackKeyValue pair = new CloudStackKeyValue();
 -					pair.setKeyValue(group.getAccount(), group.getName());
 -					secGroupList.add(pair);
 -				}
 +        try {
 +            for (EC2IpPermission ipPerm : items) {
 +                EC2SecurityGroup[] groups = ipPerm.getUserSet();
 +
 +                List<CloudStackKeyValue> secGroupList = new ArrayList<CloudStackKeyValue>(); 
 +                for (EC2SecurityGroup group : groups) {
 +                    CloudStackKeyValue pair = new CloudStackKeyValue();
 +                    pair.setKeyValue(group.getAccount(), group.getName());
 +                    secGroupList.add(pair);
 +                }
-                 CloudStackSecurityGroupIngress resp = null;
+                 CloudStackSecurityGroup resp = null;
 -				if (ipPerm.getProtocol().equalsIgnoreCase("icmp")) {
 -					resp = getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, 
 -							ipPerm.getIcmpCode(), ipPerm.getIcmpType(), ipPerm.getProtocol(), null, 
 -							request.getName(), null, secGroupList);
 -				} else {
 -					resp = getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, 
 -							ipPerm.getToPort().longValue(), null, null, ipPerm.getProtocol(), null, request.getName(), 
 -							ipPerm.getFromPort().longValue(), secGroupList);
 -				}
 +                if (ipPerm.getProtocol().equalsIgnoreCase("icmp")) {
 +                    resp = getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, null, 
 +                            ipPerm.getIcmpCode(), ipPerm.getIcmpType(), ipPerm.getProtocol(), null, 
 +                            request.getName(), null, secGroupList);
 +                } else {
 +                    resp = getApi().authorizeSecurityGroupIngress(null, constructList(ipPerm.getIpRangeSet()), null, 
 +                            ipPerm.getToPort().longValue(), null, null, ipPerm.getProtocol(), null, request.getName(), 
 +                            ipPerm.getFromPort().longValue(), secGroupList);
 +                }
-                 if (resp != null && resp.getRuleId() != null) {
-                     return true;
-                 }
+                 if (resp != null ){
+                     List<CloudStackIngressRule> ingressRules = resp.getIngressRules();
+                     for (CloudStackIngressRule ingressRule : ingressRules)
+                         if (ingressRule.getRuleId() == null) return false;
+                 } else {
 -                    return false;
 -                }
 +                return false;
 +            }
+ 			}
 -		} catch(Exception e) {
 -			logger.error( "EC2 AuthorizeSecurityGroupIngress - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -		return true;
 -	}
 +        } catch(Exception e) {
 +            logger.error( "EC2 AuthorizeSecurityGroupIngress - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +        return true;
 +    }
  
 -	/**
 -	 * Does the permission from the request (left) match the permission from the cloudStack query (right).
 -	 * If the cloudStack rule matches then we return its ruleId.
 -	 * 
 -	 * @param permLeft
 -	 * @param permRight
 -	 * @return ruleId of the cloudstack rule
 -	 */
 -	private String doesRuleMatch(EC2IpPermission permLeft, EC2IpPermission permRight)
 -	{
 -		int matches = 0;
 -
 -		if (null != permLeft.getIcmpType() && null != permLeft.getIcmpCode()) {
 -			if (null == permRight.getIcmpType() || null == permRight.getIcmpCode()) return null;
 -
 -			if (!permLeft.getIcmpType().equalsIgnoreCase( permRight.getIcmpType())) return null;
 -			if (!permLeft.getIcmpCode().equalsIgnoreCase( permRight.getIcmpCode())) return null;
 -			matches++;
 -		}
 +    /**
 +     * Does the permission from the request (left) match the permission from the cloudStack query (right).
 +     * If the cloudStack rule matches then we return its ruleId.
 +     * 
 +     * @param permLeft
 +     * @param permRight
 +     * @return ruleId of the cloudstack rule
 +     */
 +    private String doesRuleMatch(EC2IpPermission permLeft, EC2IpPermission permRight)
 +    {
 +        int matches = 0;
  
 -		// -> "Valid Values for EC2 security groups: tcp | udp | icmp or the corresponding protocol number (6 | 17 | 1)."
 -		if (null != permLeft.getProtocol()) {
 -			if (null == permRight.getProtocol()) return null;
 +        if (null != permLeft.getIcmpType() && null != permLeft.getIcmpCode()) {
 +            if (null == permRight.getIcmpType() || null == permRight.getIcmpCode()) return null;
  
 -			String protocol = permLeft.getProtocol();
 -			if (protocol.equals( "6"  )) protocol = "tcp";
 -			else if (protocol.equals( "17" )) protocol = "udp";
 -			else if (protocol.equals( "1"  )) protocol = "icmp";
 +            if (!permLeft.getIcmpType().equalsIgnoreCase( permRight.getIcmpType())) return null;
 +            if (!permLeft.getIcmpCode().equalsIgnoreCase( permRight.getIcmpCode())) return null;
 +            matches++;
 +        }
  
 -			if (!protocol.equalsIgnoreCase( permRight.getProtocol())) return null;
 -			matches++;
 -		}
 +        // -> "Valid Values for EC2 security groups: tcp | udp | icmp or the corresponding protocol number (6 | 17 | 1)."
 +        if (null != permLeft.getProtocol()) {
 +            if (null == permRight.getProtocol()) return null;
  
 +            String protocol = permLeft.getProtocol();
 +            if (protocol.equals( "6"  )) protocol = "tcp";
 +            else if (protocol.equals( "17" )) protocol = "udp";
 +            else if (protocol.equals( "1"  )) protocol = "icmp";
  
 -		if (null != permLeft.getCIDR()) {
 -			if (null == permRight.getCIDR()) return null;
 +            if (!protocol.equalsIgnoreCase( permRight.getProtocol())) return null;
 +            matches++;
 +        }
  
 -			if (!permLeft.getCIDR().equalsIgnoreCase( permRight.getCIDR())) return null;
 -			matches++;
 -		}
  
 -		// -> is the port(s) from the request (left) a match of the rule's port(s) 
 -		if (0 != permLeft.getFromPort()) {
 -			// -> -1 means all ports match
 -			if (-1 != permLeft.getFromPort()) {
 -				if (permLeft.getFromPort().compareTo(permRight.getFromPort()) != 0 || 
 -						permLeft.getToPort().compareTo(permRight.getToPort()) != 0) 
 -					return null;
 -			}
 -			matches++;
 -		}
 +        if (null != permLeft.getCIDR()) {
 +            if (null == permRight.getCIDR()) return null;
  
 +            if (!permLeft.getCIDR().equalsIgnoreCase( permRight.getCIDR())) return null;
 +            matches++;
 +        }
  
 -		// -> was permLeft set up properly with at least one property to match?
 -		if ( 0 == matches ) 
 -			return null;
 -		else return permRight.getRuleId();
 -	}
 -	
 -	/**
 -	 * Returns a list of all snapshots
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 +        // -> is the port(s) from the request (left) a match of the rule's port(s) 
 +        if (0 != permLeft.getFromPort()) {
 +            // -> -1 means all ports match
 +            if (-1 != permLeft.getFromPort()) {
 +                if (permLeft.getFromPort().compareTo(permRight.getFromPort()) != 0 || 
 +                        permLeft.getToPort().compareTo(permRight.getToPort()) != 0) 
 +                    return null;
 +            }
 +            matches++;
 +        }
 +
 +
 +        // -> was permLeft set up properly with at least one property to match?
 +        if ( 0 == matches ) 
 +            return null;
 +        else return permRight.getRuleId();
 +    }
 +
 +    /**
 +     * Returns a list of all snapshots
 +     * 
 +     * @param request
 +     * @return
 +     */
      public EC2DescribeSnapshotsResponse handleRequest( EC2DescribeSnapshots request ) 
 -	{
 -		EC2DescribeVolumesResponse volumes = new EC2DescribeVolumesResponse();
 -		EC2SnapshotFilterSet sfs = request.getFilterSet();
 +    {
 +        EC2DescribeVolumesResponse volumes = new EC2DescribeVolumesResponse();
 +        EC2SnapshotFilterSet sfs = request.getFilterSet();
          EC2TagKeyValue[] tagKeyValueSet = request.getResourceTagSet();
  
 -		try { 
 -			// -> query to get the volume size for each snapshot
 +        try { 
 +            // -> query to get the volume size for each snapshot
              EC2DescribeSnapshotsResponse response = listSnapshots( request.getSnapshotSet(),
                      getResourceTags(tagKeyValueSet));
 -			if (response == null) {
 -				return new EC2DescribeSnapshotsResponse();
 -			}
 -			EC2Snapshot[] snapshots = response.getSnapshotSet();
 -			for (EC2Snapshot snap : snapshots) {
 -				volumes = listVolumes(snap.getVolumeId(), null, volumes, null);
 -				EC2Volume[] volSet = volumes.getVolumeSet();
 -				if (0 < volSet.length) snap.setVolumeSize(volSet[0].getSize());
 -				volumes.reset();
 -			}
 +            if (response == null) {
 +                return new EC2DescribeSnapshotsResponse();
 +            }
 +            EC2Snapshot[] snapshots = response.getSnapshotSet();
 +            for (EC2Snapshot snap : snapshots) {
 +                volumes = listVolumes(snap.getVolumeId(), null, volumes, null);
 +                EC2Volume[] volSet = volumes.getVolumeSet();
 +                if (0 < volSet.length) snap.setVolumeSize(volSet[0].getSize());
 +                volumes.reset();
 +            }
  
 -			if ( null == sfs )
 -				return response;
 -			else return sfs.evaluate( response );
 -		} catch( EC2ServiceException error ) {
 -			logger.error( "EC2 DescribeSnapshots - ", error);
 -			throw error;
 +            if ( null == sfs )
 +                return response;
 +            else return sfs.evaluate( response );
 +        } catch( EC2ServiceException error ) {
 +            logger.error( "EC2 DescribeSnapshots - ", error);
 +            throw error;
  
 -		} catch( Exception e ) {
 -			logger.error( "EC2 DescribeSnapshots - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occurred.");
 -		}
 -	}
 +        } catch( Exception e ) {
 +            logger.error( "EC2 DescribeSnapshots - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, "An unexpected error occurred.");
 +        }
 +    }
  
 -	/**
 -	 * Creates a snapshot
 -	 * 
 -	 * @param volumeId
 -	 * @return
 -	 */
 -	public EC2Snapshot createSnapshot( String volumeId ) {
 -		try {
 -			
 -			CloudStackSnapshot snap = getApi().createSnapshot(volumeId, null, null, null);
 -			if (snap == null) {
 -				throw new EC2ServiceException(ServerError.InternalError, "Unable to create snapshot!");
 -			}
 -			EC2Snapshot ec2Snapshot = new EC2Snapshot();
 -
 -			ec2Snapshot.setId(snap.getId());
 -			ec2Snapshot.setName(snap.getName());
 -			ec2Snapshot.setType(snap.getSnapshotType());
 -			ec2Snapshot.setAccountName(snap.getAccountName());
 -			ec2Snapshot.setDomainId(snap.getDomainId());
 -			ec2Snapshot.setCreated(snap.getCreated());
 -			ec2Snapshot.setVolumeId(snap.getVolumeId());
 -			
 -			List<CloudStackVolume> vols = getApi().listVolumes(null, null, null, snap.getVolumeId(), null, null, null, null, null, null, null, null);
 -
 -			if(vols.size() > 0) {
 -				assert(vols.get(0).getSize() != null);
 -				Long sizeInGB = vols.get(0).getSize().longValue()/1073741824;
 -				ec2Snapshot.setVolumeSize(sizeInGB);
 -			}
 +    /**
 +     * Creates a snapshot
 +     * 
 +     * @param volumeId
 +     * @return
 +     */
 +    public EC2Snapshot createSnapshot( String volumeId ) {
 +        try {
  
 -			return ec2Snapshot;
 -		} catch( Exception e ) {
 -			logger.error( "EC2 CreateSnapshot - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            CloudStackSnapshot snap = getApi().createSnapshot(volumeId, null, null, null);
 +            if (snap == null) {
 +                throw new EC2ServiceException(ServerError.InternalError, "Unable to create snapshot!");
 +            }
 +            EC2Snapshot ec2Snapshot = new EC2Snapshot();
 +
 +            ec2Snapshot.setId(snap.getId());
 +            ec2Snapshot.setName(snap.getName());
 +            ec2Snapshot.setType(snap.getSnapshotType());
 +            ec2Snapshot.setAccountName(snap.getAccountName());
 +            ec2Snapshot.setDomainId(snap.getDomainId());
 +            ec2Snapshot.setCreated(snap.getCreated());
 +            ec2Snapshot.setVolumeId(snap.getVolumeId());
 +
 +            List<CloudStackVolume> vols = getApi().listVolumes(null, null, null, snap.getVolumeId(), null, null, null, null, null, null, null, null);
 +
 +            if(vols.size() > 0) {
 +                assert(vols.get(0).getSize() != null);
 +                Long sizeInGB = vols.get(0).getSize().longValue()/1073741824;
 +                ec2Snapshot.setVolumeSize(sizeInGB);
 +            }
  
 -	/**
 -	 * Deletes a snapshot
 -	 * 
 -	 * @param snapshotId
 -	 * @return
 -	 */
 -	public boolean deleteSnapshot(String snapshotId) {
 -		try {
 -			
 -			CloudStackInfoResponse resp = getApi().deleteSnapshot(snapshotId);
 -			if(resp != null) {
 -			    return resp.getSuccess();
 -			}
 +            return ec2Snapshot;
 +        } catch( Exception e ) {
 +            logger.error( "EC2 CreateSnapshot - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -			return false;
 -		} catch(Exception e) {
 -			logger.error( "EC2 DeleteSnapshot - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 -		}
 -	}
 -	
 -	
 -	/** REST API calls this method.
 +    /**
 +     * Deletes a snapshot
 +     * 
 +     * @param snapshotId
 +     * @return
 +     */
 +    public boolean deleteSnapshot(String snapshotId) {
 +        try {
 +
 +            CloudStackInfoResponse resp = getApi().deleteSnapshot(snapshotId);
 +            if(resp != null) {
 +                return resp.getSuccess();
 +            }
 +
 +            return false;
 +        } catch(Exception e) {
 +            logger.error( "EC2 DeleteSnapshot - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 +        }
 +    }
 +
 +
 +    /** REST API calls this method.
       * Modify an existing template
       * 
       * @param request
@@@ -692,259 -685,217 +695,217 @@@
                  shot.addResourceTag(param);
              }
  
 -			snapshots.addSnapshot(shot);
 -		}
 -		return snapshots;
 -	}
 +            snapshots.addSnapshot(shot);
 +        }
 +        return snapshots;
 +    }
  
  
 -	// handlers
 -	/**
 -	 * return password data from the instance
 -	 * 
 -	 * @param instanceId
 -	 * @return
 -	 */
 -	public EC2PasswordData getPasswordData(String instanceId) {
 -		try {
 -			CloudStackPasswordData resp = getApi().getVMPassword(instanceId);
 -			EC2PasswordData passwdData = new EC2PasswordData();
 -			if (resp != null) {
 -				passwdData.setInstanceId(instanceId);
 -				passwdData.setEncryptedPassword(resp.getEncryptedpassword());
 -			}
 -			return passwdData;
 -		} catch(Exception e) {
 -			logger.error("EC2 GetPasswordData - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +    // handlers
 +    /**
 +     * return password data from the instance
 +     * 
 +     * @param instanceId
 +     * @return
 +     */
 +    public EC2PasswordData getPasswordData(String instanceId) {
 +        try {
 +            CloudStackPasswordData resp = getApi().getVMPassword(instanceId);
 +            EC2PasswordData passwdData = new EC2PasswordData();
 +            if (resp != null) {
 +                passwdData.setInstanceId(instanceId);
 +                passwdData.setEncryptedPassword(resp.getEncryptedpassword());
 +            }
 +            return passwdData;
 +        } catch(Exception e) {
 +            logger.error("EC2 GetPasswordData - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
+ 
 -	/**
 +    /**
-      * Lists SSH KeyPairs on the systme
+      * Lists SSH KeyPairs on the system
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2DescribeKeyPairsResponse describeKeyPairs( EC2DescribeKeyPairs request ) {
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2DescribeKeyPairsResponse describeKeyPairs( EC2DescribeKeyPairs request ) {
          try {
-             EC2KeyPairFilterSet filterSet = request.getKeyFilterSet();
-             String[] keyNames = request.getKeyNames();
-             List<CloudStackKeyPair> keyPairs = getApi().listSSHKeyPairs(null, null, null);
-             List<EC2SSHKeyPair> keyPairsList = new ArrayList<EC2SSHKeyPair>();
- 
-             if (keyPairs != null) {
-                 // Let's trim the list of keypairs to only the ones listed in keyNames
-                 List<CloudStackKeyPair> matchedKeyPairs = new ArrayList<CloudStackKeyPair>();
-                 if (keyNames != null && keyNames.length > 0) {
-                     for (CloudStackKeyPair keyPair : keyPairs) {
-                         boolean matched = false;
-                         for (String keyName : keyNames) {
-                             if (keyPair.getName().equalsIgnoreCase(keyName)) {
-                                 matched = true;
-                                 break;
-                             }
-                         }
-                         if (matched) {
-                             matchedKeyPairs.add(keyPair);
-                         }
-                     }
-                     if (matchedKeyPairs.isEmpty()) {
-                         throw new EC2ServiceException(ServerError.InternalError, "No matching keypairs found");
-                     }
-                 }else{
-                     matchedKeyPairs = keyPairs;
-                 }
- 
+             EC2DescribeKeyPairsResponse response = listKeyPairs(request.getKeyNames());
+             EC2KeyPairFilterSet kfs = request.getKeyFilterSet();
  
-                 // this should be reworked... converting from CloudStackKeyPairResponse to EC2SSHKeyPair is dumb
-                 for (CloudStackKeyPair respKeyPair: matchedKeyPairs) {
-                     EC2SSHKeyPair ec2KeyPair = new EC2SSHKeyPair();
-                     ec2KeyPair.setFingerprint(respKeyPair.getFingerprint());
-                     ec2KeyPair.setKeyName(respKeyPair.getName());
-                     ec2KeyPair.setPrivateKey(respKeyPair.getPrivatekey());
-                     keyPairsList.add(ec2KeyPair);
-                 }
-             }
-             return filterSet.evaluate(keyPairsList);
+             if (kfs == null)
+                 return response;
+             else
+                 return kfs.evaluate(response);
          } catch(Exception e) {
              logger.error("EC2 DescribeKeyPairs - ", e);
              throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
          }
      }
  
 -	/**
 -	 * Delete SSHKeyPair
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public boolean deleteKeyPair( EC2DeleteKeyPair request ) {
 -		try {
 -			CloudStackInfoResponse resp = getApi().deleteSSHKeyPair(request.getKeyName(), null, null);
 -			if (resp == null) { 
 -				throw new Exception("Ivalid CloudStack API response");
 -			}
 +    /**
 +     * Delete SSHKeyPair
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public boolean deleteKeyPair( EC2DeleteKeyPair request ) {
 +        try {
 +            CloudStackInfoResponse resp = getApi().deleteSSHKeyPair(request.getKeyName(), null, null);
 +            if (resp == null) { 
 +                throw new Exception("Ivalid CloudStack API response");
 +            }
  
 -			return resp.getSuccess();
 -		} catch(Exception e) {
 -			logger.error("EC2 DeleteKeyPair - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            return resp.getSuccess();
 +        } catch(Exception e) {
 +            logger.error("EC2 DeleteKeyPair - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * Create SSHKeyPair
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2SSHKeyPair createKeyPair(EC2CreateKeyPair request) {
 -		try {
 -			CloudStackKeyPair resp = getApi().createSSHKeyPair(request.getKeyName(), null, null);
 -			if (resp == null) {
 -				throw new Exception("Ivalid CloudStack API response");
 -			}
 +    /**
 +     * Create SSHKeyPair
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2SSHKeyPair createKeyPair(EC2CreateKeyPair request) {
 +        try {
 +            CloudStackKeyPair resp = getApi().createSSHKeyPair(request.getKeyName(), null, null);
 +            if (resp == null) {
 +                throw new Exception("Ivalid CloudStack API response");
 +            }
  
 -			EC2SSHKeyPair response = new EC2SSHKeyPair();
 -			response.setFingerprint(resp.getFingerprint());
 -			response.setKeyName(resp.getName());
 -			response.setPrivateKey(resp.getPrivatekey());
 +            EC2SSHKeyPair response = new EC2SSHKeyPair();
 +            response.setFingerprint(resp.getFingerprint());
 +            response.setKeyName(resp.getName());
 +            response.setPrivateKey(resp.getPrivatekey());
  
 -			return response;
 -		} catch (Exception e) {
 -			logger.error("EC2 CreateKeyPair - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            return response;
 +        } catch (Exception e) {
 +            logger.error("EC2 CreateKeyPair - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * Import an existing SSH KeyPair
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2SSHKeyPair importKeyPair( EC2ImportKeyPair request ) {
 -		try {
 -			CloudStackKeyPair resp = getApi().registerSSHKeyPair(request.getKeyName(), request.getPublicKeyMaterial());
 -			if (resp == null) {
 -				throw new Exception("Ivalid CloudStack API response");
 -			}
 +    /**
 +     * Import an existing SSH KeyPair
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2SSHKeyPair importKeyPair( EC2ImportKeyPair request ) {
 +        try {
 +            CloudStackKeyPair resp = getApi().registerSSHKeyPair(request.getKeyName(), request.getPublicKeyMaterial());
 +            if (resp == null) {
 +                throw new Exception("Ivalid CloudStack API response");
 +            }
  
 -			EC2SSHKeyPair response = new EC2SSHKeyPair();
 -			response.setFingerprint(resp.getFingerprint());
 -			response.setKeyName(resp.getName());
 -			response.setPrivateKey(resp.getPrivatekey());
 +            EC2SSHKeyPair response = new EC2SSHKeyPair();
 +            response.setFingerprint(resp.getFingerprint());
 +            response.setKeyName(resp.getName());
 +            response.setPrivateKey(resp.getPrivatekey());
  
 -			return response;
 -		} catch (Exception e) {
 -			logger.error("EC2 ImportKeyPair - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            return response;
 +        } catch (Exception e) {
 +            logger.error("EC2 ImportKeyPair - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * list ip addresses that have been allocated
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2DescribeAddressesResponse describeAddresses( EC2DescribeAddresses request ) {
 -		try {
 +    /**
 +     * list ip addresses that have been allocated
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2DescribeAddressesResponse describeAddresses( EC2DescribeAddresses request ) {
 +        try {
-             List<CloudStackIpAddress> addrList = getApi().listPublicIpAddresses(null, null, null, null, null, null, null, null, null);
- 
-             EC2AddressFilterSet filterSet = request.getFilterSet();
-             List<EC2Address> addressList = new ArrayList<EC2Address>();
-             if (addrList != null && addrList.size() > 0) {
-                 for (CloudStackIpAddress addr: addrList) {
-                     // remember, if no filters are set, request.inPublicIpSet always returns true
-                     if (request.inPublicIpSet(addr.getIpAddress())) {
-                         EC2Address ec2Address = new EC2Address();
-                         ec2Address.setIpAddress(addr.getIpAddress());
-                         if (addr.getVirtualMachineId() != null) 
-                             ec2Address.setAssociatedInstanceId(addr.getVirtualMachineId().toString());
-                         addressList.add(ec2Address);
-                     }
-                 }
-             }
+             EC2DescribeAddressesResponse response = listAddresses(request.getPublicIpsSet());
+             EC2AddressFilterSet afs = request.getFilterSet();
  
-             return filterSet.evaluate(addressList);
+             if (afs ==null)
+                 return response;
+             else
+                 return afs.evaluate(response);
 -		} catch(Exception e) {
 -			logger.error("EC2 DescribeAddresses - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +        } catch(Exception e) {
 +            logger.error("EC2 DescribeAddresses - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * release an IP Address
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public boolean releaseAddress(EC2ReleaseAddress request) {
 -		try {
 -			CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 -			CloudStackInfoResponse resp = getApi().disassociateIpAddress(cloudIp.getId());
 -			if (resp != null) {
 -				return resp.getSuccess();
 -			}
 -		} catch(Exception e) {
 -			logger.error("EC2 ReleaseAddress - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -		return false;
 -	}
 +    /**
 +     * release an IP Address
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public boolean releaseAddress(EC2ReleaseAddress request) {
 +        try {
 +            CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 +            CloudStackInfoResponse resp = getApi().disassociateIpAddress(cloudIp.getId());
 +            if (resp != null) {
 +                return resp.getSuccess();
 +            }
 +        } catch(Exception e) {
 +            logger.error("EC2 ReleaseAddress - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +        return false;
 +    }
  
 -	/**
 -	 * Associate an address with an instance
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public boolean associateAddress( EC2AssociateAddress request ) {
 -		try {
 -			CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 -	        CloudStackUserVm cloudVm = getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null).get(0);
 +    /**
 +     * Associate an address with an instance
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public boolean associateAddress( EC2AssociateAddress request ) {
 +        try {
 +            CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 +            CloudStackUserVm cloudVm = getApi().listVirtualMachines(null, null, true, null, null, null, null, request.getInstanceId(), null, null, null, null, null, null, null, null, null).get(0);
  
 -			CloudStackInfoResponse resp = getApi().enableStaticNat(cloudIp.getId(), cloudVm.getId());
 -			if (resp != null) {
 -				return resp.getSuccess();
 -			}
 -		} catch(Exception e) {
 -			logger.error( "EC2 AssociateAddress - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 -		}
 -		return false;
 -	}
 +            CloudStackInfoResponse resp = getApi().enableStaticNat(cloudIp.getId(), cloudVm.getId());
 +            if (resp != null) {
 +                return resp.getSuccess();
 +            }
 +        } catch(Exception e) {
 +            logger.error( "EC2 AssociateAddress - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 +        }
 +        return false;
 +    }
  
 -	/**
 -	 * Disassociate an address from an instance
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public boolean disassociateAddress( EC2DisassociateAddress request ) {
 -		try {
 -			CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 -			CloudStackInfoResponse resp = getApi().disableStaticNat(cloudIp.getId());
 -			if (resp != null) {
 -				return resp.getSuccess();
 -			}
 -		} catch(Exception e) {
 -			logger.error( "EC2 DisassociateAddress - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 -		}
 -		return false;
 -	}
 +    /**
 +     * Disassociate an address from an instance
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public boolean disassociateAddress( EC2DisassociateAddress request ) {
 +        try {
 +            CloudStackIpAddress cloudIp = getApi().listPublicIpAddresses(null, null, null, null, null, request.getPublicIp(), null, null, null).get(0);
 +            CloudStackInfoResponse resp = getApi().disableStaticNat(cloudIp.getId());
 +            if (resp != null) {
 +                return resp.getSuccess();
 +            }
 +        } catch(Exception e) {
 +            logger.error( "EC2 DisassociateAddress - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage() != null ? e.getMessage() : "An unexpected error occurred.");
 +        }
 +        return false;
 +    }
  
 -	/**
 -	 * Allocate an address
 -	 * 
 -	 * @param request
 -	 * @return
 -	 */
 -	public EC2Address allocateAddress()
 -	{
 -		try {
 +    /**
 +     * Allocate an address
 +     * 
 +     * @param request
 +     * @return
 +     */
 +    public EC2Address allocateAddress()
 +    {
 +        try {
              EC2Address ec2Address = new EC2Address();
              // this gets our networkId
              CloudStackAccount caller = getCurrentAccount();
@@@ -2024,184 -1975,249 +1985,249 @@@
                              param.setValue(resourceTag.getValue());
                          ec2Image.addResourceTag(param);
                      }
 -    				images.addImage(ec2Image);
 -    			}
 +                    images.addImage(ec2Image);
 +                }
              }
 -			return images;
 -		} catch(Exception e) {
 -			logger.error( "List Templates - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -	}
 +            return images;
 +        } catch(Exception e) {
 +            logger.error( "List Templates - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
 -	/**
 -	 * List security groups
 -	 * 
 -	 * @param interestedGroups
 -	 * @return
 -	 * @throws EC2ServiceException
 -	 * @throws UnsupportedEncodingException
 -	 * @throws SignatureException
 -	 * @throws IOException
 -	 * @throws SAXException
 -	 * @throws ParserConfigurationException
 -	 * @throws ParseException
 -	 */
 -	public EC2DescribeSecurityGroupsResponse listSecurityGroups( String[] interestedGroups ) throws Exception {
 -		try {
 -			EC2DescribeSecurityGroupsResponse groupSet = new EC2DescribeSecurityGroupsResponse();
 +    /**
 +     * List security groups
 +     * 
 +     * @param interestedGroups
 +     * @return
 +     * @throws EC2ServiceException
 +     * @throws UnsupportedEncodingException
 +     * @throws SignatureException
 +     * @throws IOException
 +     * @throws SAXException
 +     * @throws ParserConfigurationException
 +     * @throws ParseException
 +     */
 +    public EC2DescribeSecurityGroupsResponse listSecurityGroups( String[] interestedGroups ) throws Exception {
 +        try {
 +            EC2DescribeSecurityGroupsResponse groupSet = new EC2DescribeSecurityGroupsResponse();
  
              List<CloudStackSecurityGroup> groups = getApi().listSecurityGroups(null, null, null, true, null, null, null);
 -			if (groups != null && groups.size() > 0)
 -    			for (CloudStackSecurityGroup group : groups) {
 -    				boolean matched = false;
 -    				if (interestedGroups.length > 0) {
 -    					for (String groupName :interestedGroups) {
 -    						if (groupName.equalsIgnoreCase(group.getName())) {
 -    							matched = true;
 -    							break;
 -    						}
 -    					}
 -    				} else {
 -    					matched = true;
 -    				}
 -    				if (!matched) continue;
 -    				EC2SecurityGroup ec2Group = new EC2SecurityGroup();
 -    				// not sure if we should set both account and account name to accountname
 -    				ec2Group.setAccount(group.getAccountName());
 -    				ec2Group.setAccountName(group.getAccountName());
 -    				ec2Group.setName(group.getName());
 -    				ec2Group.setDescription(group.getDescription());
 -    				ec2Group.setDomainId(group.getDomainId());
 -    				ec2Group.setId(group.getId().toString());
 -    				toPermission(ec2Group, group);
 -    
 -    				groupSet.addGroup(ec2Group);
 -    			}
 -			return groupSet;
 -		} catch(Exception e) {
 -			logger.error( "List Security Groups - ", e);
 -			throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 -		}
 -			}
 +            if (groups != null && groups.size() > 0)
 +                for (CloudStackSecurityGroup group : groups) {
 +                    boolean matched = false;
 +                    if (interestedGroups.length > 0) {
 +                        for (String groupName :interestedGroups) {
 +                            if (groupName.equalsIgnoreCase(group.getName())) {
 +                                matched = true;
 +                                break;
 +                            }
 +                        }
 +                    } else {
 +                        matched = true;
 +                    }
 +                    if (!matched) continue;
 +                    EC2SecurityGroup ec2Group = new EC2SecurityGroup();
 +                    // not sure if we should set both account and account name to accountname
 +                    ec2Group.setAccount(group.getAccountName());
 +                    ec2Group.setAccountName(group.getAccountName());
 +                    ec2Group.setName(group.getName());
 +                    ec2Group.setDescription(group.getDescription());
 +                    ec2Group.setDomainId(group.getDomainId());
 +                    ec2Group.setId(group.getId().toString());
 +                    toPermission(ec2Group, group);
 +
 +                    groupSet.addGroup(ec2Group);
 +                }
 +            return groupSet;
 +        } catch(Exception e) {
 +            logger.error( "List Security Groups - ", e);
 +            throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
 +        }
 +    }
  
+     private EC2DescribeKeyPairsResponse listKeyPairs( String[] keyNames ) throws Exception {
+         try {
+             EC2DescribeKeyPairsResponse keyPairSet = new EC2DescribeKeyPairsResponse();
+ 
+             List<CloudStackKeyPair> keyPairs = getApi().listSSHKeyPairs(null, null, null);
+             if (keyPairs != null && keyPairs.size() > 0) {
+                 for (CloudStackKeyPair keyPair : keyPairs) {
+                     boolean matched = false;
+                     if (keyNames.length > 0) {
+                         for (String keyName : keyNames) {
+                             if (keyName.equalsIgnoreCase(keyPair.getName())) {
+                                 matched = true;
+                                 break;
+                             }
+                         }
+                     } else matched = true;
+                     if (!matched) continue;
+                     EC2SSHKeyPair ec2KeyPair = new EC2SSHKeyPair();
+                     ec2KeyPair.setFingerprint(keyPair.getFingerprint());
+                     ec2KeyPair.setKeyName(keyPair.getName());
+                     ec2KeyPair.setPrivateKey(keyPair.getPrivatekey());
+ 
+                     keyPairSet.addKeyPair(ec2KeyPair);
+                 }
+             }
+             return keyPairSet;
+         } catch(Exception e) {
+             logger.error( "List Keypairs - ", e);
+             throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
+         }
+     }
+ 
+     private EC2DescribeAddressesResponse listAddresses(String[] addressNames) throws Exception {
+         try {
+             EC2DescribeAddressesResponse addressSet = new EC2DescribeAddressesResponse();
+ 
+             List<CloudStackIpAddress> addresses = getApi().listPublicIpAddresses(null, null, null, null, null, null, null, null, null);
+             if (addresses != null && addresses.size() > 0) {
+                 for (CloudStackIpAddress address : addresses) {
+                     boolean matched = false;
+                     if ( addressNames.length > 0) {
+                         for (String addressName : addressNames) {
+                             if (address.getIpAddress().equalsIgnoreCase(addressName)) {
+                                 matched = true;
+                                 break;
+                             }
+                         }
+                     } else matched = true;
+ 
+                     if (!matched) continue ;
+ 
+                     EC2Address ec2Address = new EC2Address();
+                     ec2Address.setIpAddress(address.getIpAddress());
+                     if (address.getVirtualMachineId() != null)
+                         ec2Address.setAssociatedInstanceId(address.getVirtualMachineId().toString());
+                     addressSet.addAddress(ec2Address);
+                 }
+             }
+             return addressSet;
+         } catch(Exception e) {
+             logger.error( "List Addresses - ", e);
+             throw new EC2ServiceException(ServerError.InternalError, e.getMessage());
+         }
+     }
+ 
 -	/**
 -	 * Convert ingress rule to EC2IpPermission records
 -	 * 
 -	 * @param response
 -	 * @param group
 -	 * @return
 -	 */
 -	private boolean toPermission(EC2SecurityGroup response, CloudStackSecurityGroup group ) {
 -		List<CloudStackIngressRule> rules = group.getIngressRules();
 -
 -		if (rules == null || rules.isEmpty()) return false;
 -
 -		for (CloudStackIngressRule rule : rules) {
 -			EC2IpPermission perm = new EC2IpPermission();
 -			perm.setProtocol(rule.getProtocol());
 -			perm.setFromPort(rule.getStartPort());
 -			perm.setToPort(rule.getEndPort());
 -			perm.setRuleId(rule.getRuleId() != null ? rule.getRuleId().toString() : new String());
 -			perm.setIcmpCode(rule.getIcmpCode() != null ? rule.getIcmpCode().toString() : new String());
 -			perm.setIcmpType(rule.getIcmpType() != null ? rule.getIcmpType().toString() : new String());
 -			perm.setCIDR(rule.getCidr());
 -			perm.addIpRange(rule.getCidr());
 -
 -			if (rule.getAccountName() != null && rule.getSecurityGroupName() != null) {
 -				EC2SecurityGroup newGroup = new EC2SecurityGroup();
 -				newGroup.setAccount(rule.getAccountName());
 -				newGroup.setName(rule.getSecurityGroupName());
 -				perm.addUser(newGroup);
 -			}
 -			response.addIpPermission(perm);
 -		}
 -		return true;
 -	}
 +    /**
 +     * Convert ingress rule to EC2IpPermission records
 +     * 
 +     * @param response
 +     * @param group
 +     * @return
 +     */
 +    private boolean toPermission(EC2SecurityGroup response, CloudStackSecurityGroup group ) {
 +        List<CloudStackIngressRule> rules = group.getIngressRules();
 +
 +        if (rules == null || rules.isEmpty()) return false;
 +
 +        for (CloudStackIngressRule rule : rules) {
 +            EC2IpPermission perm = new EC2IpPermission();
 +            perm.setProtocol(rule.getProtocol());
 +            perm.setFromPort(rule.getStartPort());
 +            perm.setToPort(rule.getEndPort());
 +            perm.setRuleId(rule.getRuleId() != null ? rule.getRuleId().toString() : new String());
 +            perm.setIcmpCode(rule.getIcmpCode() != null ? rule.getIcmpCode().toString() : new String());
 +            perm.setIcmpType(rule.getIcmpType() != null ? rule.getIcmpType().toString() : new String());
 +            perm.setCIDR(rule.getCidr());
 +            perm.addIpRange(rule.getCidr());
 +
 +            if (rule.getAccountName() != null && rule.getSecurityGroupName() != null) {
 +                EC2SecurityGroup newGroup = new EC2SecurityGroup();
 +                newGroup.setAccount(rule.getAccountName());
 +                newGroup.setName(rule.getSecurityGroupName());
 +                perm.addUser(newGroup);
 +            }
 +            response.addIpPermission(perm);
 +        }
 +        return true;
 +    }
  
 -	/**
 -	 * Find the current account based on the SecretKey
 -	 * 
 -	 * @return
 -	 * @throws Exception
 -	 */
 -	public CloudStackAccount getCurrentAccount() throws Exception {
 -	    if (currentAccount != null) {
 -	        // verify this is the same account!!!
 -	        for (CloudStackUser user : currentAccount.getUser()) { 
 -	            if (user.getSecretkey() != null && user.getSecretkey().equalsIgnoreCase(UserContext.current().getSecretKey())) {
 -	                return currentAccount;
 -	            }
 -	        }
 -	    }
 -	    // otherwise let's find this user/account
 -		List<CloudStackAccount> accounts = getApi().listAccounts(null, null, null, null, null, null, null, null);
 -		for (CloudStackAccount account : accounts) {
 -			CloudStackUser[] users = account.getUser();
 -			for (CloudStackUser user : users) {
 -			    String userSecretKey = user.getSecretkey();
 -				if (userSecretKey != null && userSecretKey.equalsIgnoreCase(UserContext.current().getSecretKey())) {
 -				    currentAccount = account;
 -					return account;
 -				}
 -			}
 -		}
 -		// if we get here, there is something wrong...
 -		return null;
 -	}
 +    /**
 +     * Find the current account based on the SecretKey
 +     * 
 +     * @return
 +     * @throws Exception
 +     */
 +    public CloudStackAccount getCurrentAccount() throws Exception {
 +        if (currentAccount != null) {
 +            // verify this is the same account!!!
 +            for (CloudStackUser user : currentAccount.getUser()) { 
 +                if (user.getSecretkey() != null && user.getSecretkey().equalsIgnoreCase(UserContext.current().getSecretKey())) {
 +                    return currentAccount;
 +                }
 +            }
 +        }
 +        // otherwise let's find this user/account
 +        List<CloudStackAccount> accounts = getApi().listAccounts(null, null, null, null, null, null, null, null);
 +        for (CloudStackAccount account : accounts) {
 +            CloudStackUser[] users = account.getUser();
 +            for (CloudStackUser user : users) {
 +                String userSecretKey = user.getSecretkey();
 +                if (userSecretKey != null && userSecretKey.equalsIgnoreCase(UserContext.current().getSecretKey())) {
 +                    currentAccount = account;
 +                    return account;
 +                }
 +            }
 +        }
 +        // if we get here, there is something wrong...
 +        return null;
 +    }
  
 -	/**
 -	 * List networkOfferings by zone with securityGroup enabled
 -	 * 
 -	 * @param zoneId
 -	 * @return
 -	 * @throws Exception
 -	 */
 -	private CloudStackNetwork getNetworksWithSecurityGroupEnabled(String zoneId) throws Exception {
 -		List<CloudStackNetwork> networks = getApi().listNetworks(null, null, null, null, null, null, null, null, null, zoneId);
 -		List<CloudStackNetwork> netWithSecGroup = new ArrayList<CloudStackNetwork>();
 -		for (CloudStackNetwork network : networks ) {
 -			if (!network.getNetworkOfferingAvailability().equalsIgnoreCase("unavailable") && network.getSecurityGroupEnabled()) 
 -				netWithSecGroup.add(network);
 -		}
 -		// we'll take the first one
 -		return netWithSecGroup.get(0);
 -	}
 +    /**
 +     * List networkOfferings by zone with securityGroup enabled
 +     * 
 +     * @param zoneId
 +     * @return
 +     * @throws Exception
 +     */
 +    private CloudStackNetwork getNetworksWithSecurityGroupEnabled(String zoneId) throws Exception {
 +        List<CloudStackNetwork> networks = getApi().listNetworks(null, null, null, null, null, null, null, null, null, zoneId);
 +        List<CloudStackNetwork> netWithSecGroup = new ArrayList<CloudStackNetwork>();
 +        for (CloudStackNetwork network : networks ) {
 +            if (!network.getNetworkOfferingAvailability().equalsIgnoreCase("unavailable") && network.getSecurityGroupEnabled()) 
 +                netWithSecGroup.add(network);
 +        }
 +        // we'll take the first one
 +        return netWithSecGroup.get(0);
 +    }
  
 -	/**
 -	 * Create a network 
 -	 * 
 -	 * @param zoneId
 -	 * @param offering
 -	 * @param owner
 -	 * @return
 -	 * @throws Exception
 -	 */
 -	private CloudStackNetwork createDefaultGuestNetwork(String zoneId, CloudStackNetworkOffering offering, CloudStackAccount owner) throws Exception {
 -		return getApi().createNetwork(owner.getName() + "-network", owner.getName() + "-network",  offering.getId(), zoneId, owner.getName(), 
 -				owner.getDomainId(), true, null, null, null, null, null, null, null, null);
 -	}
 +    /**
 +     * Create a network 
 +     * 
 +     * @param zoneId
 +     * @param offering
 +     * @param owner
 +     * @return
 +     * @throws Exception
 +     */
 +    private CloudStackNetwork createDefaultGuestNetwork(String zoneId, CloudStackNetworkOffering offering, CloudStackAccount owner) throws Exception {
 +        return getApi().createNetwork(owner.getName() + "-network", owner.getName() + "-network",  offering.getId(), zoneId, owner.getName(), 
 +                owner.getDomainId(), true, null, null, null, null, null, null, null, null);
 +    }
  
 -	/**
 -	 * List of networks without securityGroup enabled by zone
 -	 * 
 -	 * @param zoneId
 -	 * @return
 -	 * @throws Exception
 -	 */
 -	private CloudStackNetwork getNetworksWithoutSecurityGroupEnabled(String zoneId) throws Exception {
 -		// grab current account
 -		CloudStackAccount caller = getCurrentAccount();
 -		
 -		//check if account has any networks in the system
 -		List<CloudStackNetwork> networks = getApi().listNetworks(caller.getName(), caller.getDomainId(), null, true, null, null, null, null, null, zoneId);
 -       
 -		//listRequired offerings in the system - the network created from this offering has to be specified in deployVm command
 -		List<CloudStackNetworkOffering> reuquiredOfferings = getApi().listNetworkOfferings("Required", null, null, null, true,  null, null, null, null, null, zoneId);
 -		if (reuquiredOfferings != null && !reuquiredOfferings.isEmpty()) {
 -		    if (networks != null && !networks.isEmpty()) {
 -		        //pick up the first required network from the network list
 -		        for (CloudStackNetwork network : networks)  {
 +    /**
 +     * List of networks without securityGroup enabled by zone
 +     * 
 +     * @param zoneId
 +     * @return
 +     * @throws Exception
 +     */
 +    private CloudStackNetwork getNetworksWithoutSecurityGroupEnabled(String zoneId) throws Exception {
 +        // grab current account
 +        CloudStackAccount caller = getCurrentAccount();
 +
 +        //check if account has any networks in the system
 +        List<CloudStackNetwork> networks = getApi().listNetworks(caller.getName(), caller.getDomainId(), null, true, null, null, null, null, null, zoneId);
 +
 +        //listRequired offerings in the system - the network created from this offering has to be specified in deployVm command
 +        List<CloudStackNetworkOffering> reuquiredOfferings = getApi().listNetworkOfferings("Required", null, null, null, true,  null, null, null, null, null, zoneId);
 +        if (reuquiredOfferings != null && !reuquiredOfferings.isEmpty()) {
 +            if (networks != null && !networks.isEmpty()) {
 +                //pick up the first required network from the network list
 +                for (CloudStackNetwork network : networks)  {
                      for (CloudStackNetworkOffering requiredOffering : reuquiredOfferings) { 
                          logger.debug("[reqd/virtual} offering: " + requiredOffering.getId() + " network " + network.getNetworkOfferingId());
                          if (network.getNetworkOfferingId().equals(requiredOffering.getId())) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/client/tomcatconf/componentContext.xml.in
----------------------------------------------------------------------
diff --cc client/tomcatconf/componentContext.xml.in
index 1377925,0000000..48ed9f5
mode 100644,000000..100644
--- a/client/tomcatconf/componentContext.xml.in
+++ b/client/tomcatconf/componentContext.xml.in
@@@ -1,257 -1,0 +1,257 @@@
 +<!--
 +  Licensed to the Apache Software Foundation (ASF) under one
 +  or more contributor license agreements. See the NOTICE file
 +  distributed with this work for additional information
 +  regarding copyright ownership. The ASF licenses this file
 +  to you under the Apache License, Version 2.0 (the
 +  "License"); you may not use this file except in compliance
 +  with the License. You may obtain a copy of the License at
 +
 +  http://www.apache.org/licenses/LICENSE-2.0
 +
 +  Unless required by applicable law or agreed to in writing,
 +  software distributed under the License is distributed on an
 +  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 +  KIND, either express or implied. See the License for the
 +  specific language governing permissions and limitations
 +  under the License.
 +-->
 +<beans xmlns="http://www.springframework.org/schema/beans"
 +  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 +  xmlns:context="http://www.springframework.org/schema/context"
 +  xmlns:tx="http://www.springframework.org/schema/tx" 
 +  xmlns:aop="http://www.springframework.org/schema/aop"
 +  xsi:schemaLocation="http://www.springframework.org/schema/beans
 +                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 +                      http://www.springframework.org/schema/tx 
 +                      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 +                      http://www.springframework.org/schema/aop
 +                      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 +                      http://www.springframework.org/schema/context
 +                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">                     
 +
 +
 +  <!--
 +      Compose a CloudStack deployment with selected components here
 +  -->
 +  <bean id="databaseUpgradeChecker" class="com.cloud.upgrade.DatabaseUpgradeChecker" />
 +  
 +  <bean id="management-server" class ="com.cloud.server.ManagementServerExtImpl" />
 +  <bean id="configuration-server" class="com.cloud.server.ConfigurationServerImpl" />
 +   
 +  <bean id="clusterManagerImpl" class="com.cloud.cluster.ClusterManagerImpl" />
 +  <bean id="clusteredAgentManagerImpl" class="com.cloud.agent.manager.ClusteredAgentManagerImpl" />
 +  <bean id="clusteredVirtualMachineManagerImpl" class="com.cloud.vm.ClusteredVirtualMachineManagerImpl" />
 +  <bean id="highAvailabilityManagerExtImpl" class="com.cloud.ha.HighAvailabilityManagerExtImpl" />
 +  <!-- bean id="bareMetalVmManagerImpl" class="com.cloud.baremetal.BareMetalVmManagerImpl" / -->
 +  <bean id="userVmManagerImpl" class="com.cloud.vm.UserVmManagerImpl" />
 +  <bean id="consoleProxyManagerImpl" class="com.cloud.consoleproxy.ConsoleProxyManagerImpl" />
 +  <bean id="securityGroupManagerImpl2" class="com.cloud.network.security.SecurityGroupManagerImpl2" />
 +  <bean id="premiumSecondaryStorageManagerImpl" class="com.cloud.secstorage.PremiumSecondaryStorageManagerImpl" />
 +  <bean id="randomlyIncreasingVMInstanceDaoImpl" class="com.cloud.vm.dao.RandomlyIncreasingVMInstanceDaoImpl" />
-     
++  <bean id="ipv6AddressManagerImpl" class="com.cloud.network.Ipv6AddressManagerImpl" />
 +   
 +  <!--
 +      Network Elements
 +  -->
 +  <bean id="Ovs" class="com.cloud.network.element.OvsElement">
 +    <property name="name" value="Ovs"/>
 +  </bean>
 +  <bean id="ExternalDhcpServer" class="com.cloud.network.element.ExternalDhcpElement">
 +    <property name="name" value="ExternalDhcpServer"/>
 +  </bean>
 +  <bean id="BareMetal" class="com.cloud.network.element.BareMetalElement">
 +    <property name="name" value="BareMetal"/>
 +  </bean>
 +  <bean id="SecurityGroupProvider" class="com.cloud.network.element.SecurityGroupElement">
 +    <property name="name" value="SecurityGroupProvider"/>
 +  </bean>
 +  <bean id="VirtualRouter" class="com.cloud.network.element.VirtualRouterElement">
 +    <property name="name" value="VirtualRouter"/>
 +  </bean>
 +  <bean id="VpcVirtualRouter" class="com.cloud.network.element.VpcVirtualRouterElement">
 +    <property name="name" value="VpcVirtualRouter"/>
 +  </bean>
 +  <bean id="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement">
 +    <property name="name" value="NiciraNvp"/>
 +  </bean>
 +                   
 +  <!--
 +     Adapters
 +  -->
 +  <bean id="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.FirstFitRoutingAllocator">
 +    <property name="name" value="FirstFitRouting"/>
 +  </bean>
 +  
 +  <!--
 +    Storage pool allocators
 +  -->
 +  <bean id="LocalStoragePoolAllocator" class="com.cloud.storage.allocator.LocalStoragePoolAllocator">
 +    <property name="name" value="LocalStorage"/>
 +  </bean>
 +  <bean id="FirstFitStoragePoolAllocator" class="com.cloud.storage.allocator.FirstFitStoragePoolAllocator">
 +    <property name="name" value="Storage"/>
 +  </bean>
 +
 +  <bean id="UserConcentratedAllocator" class="com.cloud.agent.manager.allocator.impl.UserConcentratedAllocator">
 +    <property name="name" value="User First"/>
 +  </bean>
 +
 +  <bean id="ConsoleProxyAllocator" class="com.cloud.consoleproxy.ConsoleProxyBalanceAllocator">
 +    <property name="name" value="Balance"/>
 +  </bean>
 +
 +  <bean id="StaticRoleBasedAPIAccessChecker" class="org.apache.cloudstack.acl.StaticRoleBasedAPIAccessChecker"/>
 +
 +  <bean id="ApiRateLimitServiceImpl" class="org.apache.cloudstack.ratelimit.ApiRateLimitServiceImpl"/>
 +
 +  <bean id="ExteralIpAddressAllocator" class="com.cloud.network.ExteralIpAddressAllocator">
 +    <property name="name" value="Basic"/>
 +  </bean>
 +
 +  <bean id="hyervisorTemplateAdapter" class="com.cloud.template.HyervisorTemplateAdapter">
 +    <property name="name" value="HypervisorAdapter"/>
 +  </bean>
 +
 +  <!--
 +    Authenticators
 +  -->
 +  <bean id="MD5UserAuthenticator" class="com.cloud.server.auth.MD5UserAuthenticator">
 +    <property name="name" value="MD5"/>
 +  </bean>
 +
 +  <bean id="LDAPUserAuthenticator" class="com.cloud.server.auth.LDAPUserAuthenticator">
 +    <property name="name" value="LDAP"/>
 +  </bean>
 +
 +  <!--
 +    Investigators
 +  -->
 +  <bean id="CheckOnAgentInvestigator" class="com.cloud.ha.CheckOnAgentInvestigator">
 +    <property name="name" value="SimpleInvestigator"/>
 +  </bean>
 +
 +  <bean id="XenServerInvestigator" class="com.cloud.ha.XenServerInvestigator">
 +    <property name="name" value="XenServerInvestigator"/>
 +  </bean>
 +  
 +  <bean id="UserVmDomRInvestigator" class="com.cloud.ha.UserVmDomRInvestigator">
 +    <property name="name" value="PingInvestigator"/>
 +  </bean>
 +
 +  <bean id="ManagementIPSystemVMInvestigator" class="com.cloud.ha.ManagementIPSystemVMInvestigator">
 +    <property name="name" value="ManagementIPSysVMInvestigator"/>
 +  </bean>
 +
 +  <!--
 +    Fencers
 +  -->
 +  <bean id="XenServerFencer" class="com.cloud.ha.XenServerFencer">
 +    <property name="name" value="XenServerFenceBuilder"/>
 +  </bean>
 +  <bean id="KVMFencer" class="com.cloud.ha.KVMFencer">
 +    <property name="name" value="KVMFenceBuilder"/>
 +  </bean>
 +  <bean id="OvmFencer" class="com.cloud.ovm.hypervisor.OvmFencer">
 +    <property name="name" value="OvmFenceBuilder"/>
 +  </bean>
 +
 +  <bean id="XcpServerDiscoverer" class="com.cloud.hypervisor.xen.discoverer.XcpServerDiscoverer">
 +    <property name="name" value="XCP Agent"/>
 +  </bean>
 +
 +  <bean id="SecondaryStorageDiscoverer" class="com.cloud.storage.secondary.SecondaryStorageDiscoverer">
 +    <property name="name" value="SecondaryStorage"/>
 +  </bean>
 +
 +  <bean id="KvmServerDiscoverer" class="com.cloud.hypervisor.kvm.discoverer.KvmServerDiscoverer">
 +    <property name="name" value="KVM Agent"/>
 +  </bean>
 +
 +  <bean id="BareMetalDiscoverer" class="com.cloud.baremetal.BareMetalDiscoverer">
 +    <property name="name" value="Bare Metal Agent"/>
 +  </bean>
 +
 +  <bean id="HypervServerDiscoverer" class="com.cloud.hypervisor.hyperv.HypervServerDiscoverer">
 +    <property name="name" value="SCVMMServer"/>
 +  </bean>
 +
 +  <bean id="OvmDiscoverer" class="com.cloud.ovm.hypervisor.OvmDiscoverer">
 +    <property name="name" value="Ovm Discover"/>
 +  </bean>
 +
 +  <bean id="FirstFitPlanner" class="com.cloud.deploy.FirstFitPlanner">
 +    <property name="name" value="First Fit"/>
 +  </bean>
 +
 +  <bean id="UserDispersingPlanner" class="com.cloud.deploy.UserDispersingPlanner">
 +    <property name="name" value="UserDispersing"/>
 +  </bean>
 +  
 +  <bean id="UserConcentratedPodPlanner" class="com.cloud.deploy.UserConcentratedPodPlanner">
 +    <property name="name" value="UserConcentratedPod"/>
 +  </bean>
 +
 +  <bean id="BareMetalPlanner" class="com.cloud.deploy.BareMetalPlanner">
 +    <property name="name" value="BareMetal Fit"/>
 +  </bean>
 +    
 +   
 +  <!--
 +    Network Gurus
 +  -->
 +  <bean id="StorageNetworkGuru" class="com.cloud.network.guru.StorageNetworkGuru">
 +    <property name="name" value="StorageNetworkGuru"/>
 +  </bean>
 +  <bean id="ExternalGuestNetworkGuru" class="com.cloud.network.guru.ExternalGuestNetworkGuru">
 +    <property name="name" value="ExternalGuestNetworkGuru"/>
 +  </bean>
 +  <bean id="PublicNetworkGuru" class="com.cloud.network.guru.PublicNetworkGuru">
 +    <property name="name" value="PublicNetworkGuru"/>
 +  </bean>
 +  <bean id="PodBasedNetworkGuru" class="com.cloud.network.guru.PodBasedNetworkGuru">
 +    <property name="name" value="PodBasedNetworkGuru"/>
 +  </bean>
 +  <bean id="ControlNetworkGuru" class="com.cloud.network.guru.ControlNetworkGuru">
 +    <property name="name" value="ControlNetworkGuru"/>
 +  </bean>
 +  <bean id="DirectNetworkGuru" class="com.cloud.network.guru.DirectNetworkGuru">
 +    <property name="name" value="DirectNetworkGuru"/>
 +  </bean>
 +  <bean id="DirectPodBasedNetworkGuru" class="com.cloud.network.guru.DirectPodBasedNetworkGuru">
 +    <property name="name" value="DirectPodBasedNetworkGuru"/>
 +  </bean>
 +  <bean id="OvsGuestNetworkGuru" class="com.cloud.network.guru.OvsGuestNetworkGuru">
 +    <property name="name" value="OvsGuestNetworkGuru"/>
 +  </bean>
 +  <bean id="PrivateNetworkGuru" class="com.cloud.network.guru.PrivateNetworkGuru">
 +    <property name="name" value="PrivateNetworkGuru"/>
 +  </bean>
 +  <bean id="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru">
 +    <property name="name" value="NiciraNvpGuestNetworkGuru"/>
 +  </bean>
 + 
 +  <!--
 +   Hypervisor Gurus
 +  -->
 +  <bean id="XenServerGuru" class="com.cloud.hypervisor.XenServerGuru">
 +    <property name="name" value="XenServerGuru"/>
 +  </bean>
 +  
 +  <bean id="KVMGuru" class="com.cloud.hypervisor.KVMGuru">
 +    <property name="name" value="KVMGuru"/>
 +  </bean>
 +  
 +  <bean id="BareMetalGuru" class="com.cloud.baremetal.BareMetalGuru">
 +    <property name="name" value="BareMetalGuru"/>
 +  </bean>
 +
 +  <bean id="HypervGuru" class="com.cloud.hypervisor.guru.HypervGuru">
 +    <property name="name" value="HypervGuru"/>
 +  </bean>
 +
 +  <bean id="OvmGuru" class="com.cloud.ovm.hypervisor.OvmGuru">
 +    <property name="name" value="OvmGuru"/>
 +  </bean>
 +  
 +</beans>

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
----------------------------------------------------------------------
diff --cc core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
index 5354d89,1767207..fc7f08f
--- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
+++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java
@@@ -579,7 -578,9 +579,9 @@@ public class VirtualRoutingResource imp
      protected synchronized Answer execute (final DhcpEntryCommand cmd) {
          final Script command  = new Script(_dhcpEntryPath, _timeout, s_logger);
          command.add("-r", cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP));
+         if (cmd.getVmIpAddress() != null) {
 -        	command.add("-v", cmd.getVmIpAddress());
 +        command.add("-v", cmd.getVmIpAddress());
+         }
          command.add("-m", cmd.getVmMac());
          command.add("-n", cmd.getVmName());
          
@@@ -593,7 -594,12 +595,12 @@@
          if (cmd.getDefaultDns() != null) {
          	command.add("-N", cmd.getDefaultDns());
          }
 -        
 +
+         if (cmd.getVmIp6Address() != null) {
+         	command.add("-6", cmd.getVmIp6Address());
+         	command.add("-u", cmd.getDuid());
+         }
+ 
          final String result = command.execute();
          return new Answer(cmd, result==null, result);
      }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
index 85a34eb,52358b3..a1b1336
--- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
+++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
@@@ -1651,22 -1652,29 +1651,29 @@@ public class VmwareResource implements 
          }
  
          // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null
-         String args = " " + cmd.getVmMac();
-         args += " " + cmd.getVmIpAddress();
-         args += " " + cmd.getVmName();
+         String args = " -m " + cmd.getVmMac();
+         if (cmd.getVmIpAddress() != null) {
+         	args += " -4 " + cmd.getVmIpAddress();
+         }
+         args += " -h " + cmd.getVmName();
 -        
 +
          if (cmd.getDefaultRouter() != null) {
-             args += " " + cmd.getDefaultRouter();
+             args += " -d " + cmd.getDefaultRouter();
          }
 -        
 +
          if (cmd.getDefaultDns() != null) {
-             args += " " + cmd.getDefaultDns();
+             args += " -n " + cmd.getDefaultDns();
          }
  
          if (cmd.getStaticRoutes() != null) {
-             args +=  " " + cmd.getStaticRoutes();
+             args += " -s " + cmd.getStaticRoutes();
+         }
+         
+         if (cmd.getVmIp6Address() != null) {
+         	args += " -6 " + cmd.getVmIp6Address();
+         	args += " -u " + cmd.getDuid();
          }
 -        
 +
          if (s_logger.isDebugEnabled()) {
              s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args);
          }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
index 4a74b64,e255070..71f2002
--- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
+++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/resource/CitrixResourceBase.java
@@@ -1759,7 -1752,9 +1759,9 @@@ public abstract class CitrixResourceBas
      protected synchronized Answer execute(final DhcpEntryCommand cmd) {
          Connection conn = getConnection();
          String args = "-r " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP);
+         if (cmd.getVmIpAddress() != null) {
 -        	args += " -v " + cmd.getVmIpAddress();
 +        args += " -v " + cmd.getVmIpAddress();
+         }
          args += " -m " + cmd.getVmMac();
          args += " -n " + cmd.getVmName();
          if (cmd.getDefaultRouter() != null) {
@@@ -1768,11 -1763,16 +1770,16 @@@
          if (cmd.getStaticRoutes() != null) {
              args += " -s " + cmd.getStaticRoutes();
          }
 -        
 +
          if (cmd.getDefaultDns() != null) {
 -        	args += " -N " + cmd.getDefaultDns();
 +            args += " -N " + cmd.getDefaultDns();
          }
 -        
 +
+         if (cmd.getVmIp6Address() != null) {
+         	args += " -6 " + cmd.getVmIp6Address();
+         	args += " -u " + cmd.getDuid();
+         }
+         
          String result = callHostPlugin(conn, "vmops", "saveDhcpEntry", "args", args);
          if (result == null || result.isEmpty()) {
              return new Answer(cmd, false, "DhcpEntry failed");

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --cc server/src/com/cloud/api/ApiResponseHelper.java
index d4ad82b,32bdf40..9aae154
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@@ -484,9 -481,21 +484,21 @@@ public class ApiResponseHelper implemen
  
          // get start ip and end ip of corresponding vlan
          String ipRange = vlan.getIpRange();
+         if (ipRange != null) {
 -        	String[] range = ipRange.split("-");
 -        	vlanResponse.setStartIp(range[0]);
 -        	vlanResponse.setEndIp(range[1]);
 +        String[] range = ipRange.split("-");
 +        vlanResponse.setStartIp(range[0]);
 +        vlanResponse.setEndIp(range[1]);
+         }
+ 
+         vlanResponse.setIp6Gateway(vlan.getIp6Gateway());
+         vlanResponse.setIp6Cidr(vlan.getIp6Cidr());
+         
+         String ip6Range = vlan.getIp6Range();
+         if (ip6Range != null) {
+         	String[] range = ip6Range.split("-");
+         	vlanResponse.setStartIpv6(range[0]);
+         	vlanResponse.setEndIpv6(range[1]);
+         }
  
          if (vlan.getNetworkId() != null) {
              Network nw = ApiDBUtils.findNetworkById(vlan.getNetworkId());
@@@ -2154,7 -2163,10 +2166,10 @@@
          if (network.getCidr() != null) {
              response.setNetmask(NetUtils.cidr2Netmask(network.getCidr()));
          }
 -        
 +
+         response.setIp6Gateway(network.getIp6Gateway());
+         response.setIp6Cidr(network.getIp6Cidr());
+ 
          //return vlan information only to Root admin
          if (network.getBroadcastUri() != null && UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) {
              String broadcastUri = network.getBroadcastUri().toString();

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/server/src/com/cloud/api/query/QueryManagerImpl.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/7bd8bec6/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java
----------------------------------------------------------------------