You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by pr...@apache.org on 2012/07/27 11:36:06 UTC

[9/11] AutoScale changes in Apache master

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
new file mode 100644
index 0000000..758ef65
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java
@@ -0,0 +1,1140 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import java.security.InvalidParameterException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ejb.Local;
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.acl.ControlledEntity;
+import com.cloud.api.ApiConstants;
+import com.cloud.api.ApiDBUtils;
+import com.cloud.api.ApiDispatcher;
+import com.cloud.api.BaseListAccountResourcesCmd;
+import com.cloud.api.commands.CreateAutoScalePolicyCmd;
+import com.cloud.api.commands.CreateAutoScaleVmGroupCmd;
+import com.cloud.api.commands.CreateAutoScaleVmProfileCmd;
+import com.cloud.api.commands.CreateConditionCmd;
+import com.cloud.api.commands.CreateCounterCmd;
+import com.cloud.api.commands.DeployVMCmd;
+import com.cloud.api.commands.ListAutoScalePoliciesCmd;
+import com.cloud.api.commands.ListAutoScaleVmGroupsCmd;
+import com.cloud.api.commands.ListAutoScaleVmProfilesCmd;
+import com.cloud.api.commands.ListConditionsCmd;
+import com.cloud.api.commands.ListCountersCmd;
+import com.cloud.api.commands.UpdateAutoScalePolicyCmd;
+import com.cloud.api.commands.UpdateAutoScaleVmGroupCmd;
+import com.cloud.api.commands.UpdateAutoScaleVmProfileCmd;
+import com.cloud.configuration.Config;
+import com.cloud.configuration.ConfigurationManager;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.dc.DataCenter;
+import com.cloud.dc.dao.DataCenterDao;
+import com.cloud.event.ActionEvent;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.ResourceInUseException;
+import com.cloud.network.LoadBalancerVO;
+import com.cloud.network.Network.Capability;
+import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao;
+import com.cloud.network.as.dao.AutoScalePolicyDao;
+import com.cloud.network.as.dao.AutoScaleVmGroupDao;
+import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao;
+import com.cloud.network.as.dao.AutoScaleVmProfileDao;
+import com.cloud.network.as.dao.ConditionDao;
+import com.cloud.network.as.dao.CounterDao;
+import com.cloud.network.dao.IPAddressDao;
+import com.cloud.network.dao.LoadBalancerDao;
+import com.cloud.network.dao.LoadBalancerVMMapDao;
+import com.cloud.network.dao.NetworkDao;
+import com.cloud.network.lb.LoadBalancingRulesManager;
+import com.cloud.offering.ServiceOffering;
+import com.cloud.projects.Project.ListProjectResourcesCriteria;
+import com.cloud.template.TemplateManager;
+import com.cloud.template.VirtualMachineTemplate;
+import com.cloud.user.Account;
+import com.cloud.user.AccountManager;
+import com.cloud.user.User;
+import com.cloud.user.UserContext;
+import com.cloud.user.dao.AccountDao;
+import com.cloud.user.dao.UserDao;
+import com.cloud.utils.IdentityProxy;
+import com.cloud.utils.Ternary;
+import com.cloud.utils.component.Inject;
+import com.cloud.utils.component.Manager;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Filter;
+import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.db.JoinBuilder;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.net.NetUtils;
+
+@Local(value = { AutoScaleService.class })
+public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
+    private static final Logger s_logger = Logger.getLogger(AutoScaleManagerImpl.class);
+
+    String _name;
+    @Inject
+    AccountDao _accountDao;
+    @Inject
+    AccountManager _accountMgr;
+    @Inject
+    ConfigurationManager _configMgr;
+    @Inject
+    TemplateManager _templateMgr;
+    @Inject
+    LoadBalancingRulesManager _lbRulesMgr;
+    @Inject
+    NetworkDao _networkDao;
+    @Inject
+    CounterDao _counterDao;
+    @Inject
+    ConditionDao _conditionDao;
+    @Inject
+    LoadBalancerVMMapDao _lb2VmMapDao;
+    @Inject
+    LoadBalancerDao _lbDao;
+    @Inject
+    AutoScaleVmProfileDao _autoScaleVmProfileDao;
+    @Inject
+    AutoScalePolicyDao _autoScalePolicyDao;
+    @Inject
+    AutoScalePolicyConditionMapDao _autoScalePolicyConditionMapDao;
+    @Inject
+    AutoScaleVmGroupDao _autoScaleVmGroupDao;
+    @Inject
+    AutoScaleVmGroupPolicyMapDao _autoScaleVmGroupPolicyMapDao;
+    @Inject
+    DataCenterDao _dcDao = null;
+    @Inject
+    UserDao _userDao;
+    @Inject
+    ConfigurationDao _configDao;
+    @Inject
+    IPAddressDao _ipAddressDao;
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+        _name = name;
+        return true;
+    }
+
+    @Override
+    public boolean start() {
+        return true;
+    }
+
+    @Override
+    public boolean stop() {
+        return true;
+    }
+
+    @Override
+    public String getName() {
+        return _name;
+    }
+
+    public List<String> getSupportedAutoScaleCounters(long networkid)
+    {
+        String autoScaleCapability = _lbRulesMgr.getLBCapability(networkid, Capability.AutoScaleCounters.getName());
+        if (autoScaleCapability == null || autoScaleCapability.length() == 0) {
+            return null;
+        }
+        return Arrays.asList(autoScaleCapability.split(","));
+    }
+
+    public void validateAutoScaleCounters(long networkid, List<Counter> counters)
+    {
+        List<String> supportedCounters = getSupportedAutoScaleCounters(networkid);
+        if (supportedCounters == null) {
+            throw new InvalidParameterException("AutoScale is not supported in the network");
+        }
+        for (Counter counter : counters) {
+            if (!supportedCounters.contains(counter.getSource().name().toString())) {
+                throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource() + "' is not supported " +
+                "in the network where lb is configured");
+            }
+        }
+    }
+
+    private <VO extends ControlledEntity> VO getEntityInDatabase(Account caller, String paramName, Long id, GenericDao<VO, Long> dao)
+    {
+
+        VO vo = dao.findById(id);
+
+        if (vo == null) {
+            throw new InvalidParameterValueException("Unable to find " + paramName);
+        }
+
+        _accountMgr.checkAccess(caller, null, false, (ControlledEntity) vo);
+
+        return vo;
+    }
+
+    private boolean isAutoScaleScaleUpPolicy(AutoScalePolicy policyVO)
+    {
+        return policyVO.getAction().equals("scaleup");
+    }
+
+    private List<AutoScalePolicyVO> getAutoScalePolicies(String paramName, List<Long> policyIds, List<Counter> counters, int interval, boolean scaleUpPolicies)
+    {
+        SearchBuilder<AutoScalePolicyVO> policySearch = _autoScalePolicyDao.createSearchBuilder();
+        policySearch.and("ids", policySearch.entity().getId(), Op.IN);
+        policySearch.done();
+        SearchCriteria<AutoScalePolicyVO> sc = policySearch.create();
+
+        sc.setParameters("ids", policyIds.toArray(new Object[0]));
+        List<AutoScalePolicyVO> policies = _autoScalePolicyDao.search(sc, null);
+
+        int prevQuietTime = 0;
+
+        for (AutoScalePolicyVO policy : policies) {
+            int quietTime = policy.getQuietTime();
+            if (prevQuietTime == 0) {
+                prevQuietTime = quietTime;
+            }
+            int duration = policy.getDuration();
+            if (duration < interval) {
+                throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval);
+            }
+
+            if (quietTime < interval) {
+                throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval);
+            }
+
+            if (quietTime != prevQuietTime) {
+                throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName);
+            }
+
+            if (scaleUpPolicies) {
+                if (!isAutoScaleScaleUpPolicy(policy)) {
+                    throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids");
+                }
+            }
+            else {
+                if (isAutoScaleScaleUpPolicy(policy)) {
+                    throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids");
+                }
+            }
+            List<AutoScalePolicyConditionMapVO> policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null);
+            for (AutoScalePolicyConditionMapVO policyConditionMapVO : policyConditionMapVOs) {
+                long conditionid = policyConditionMapVO.getConditionId();
+                Condition condition = _conditionDao.findById(conditionid);
+                Counter counter = _counterDao.findById(condition.getCounterid());
+                counters.add(counter);
+            }
+        }
+        return policies;
+    }
+
+    protected AutoScaleVmProfileVO checkValidityAndPersist(AutoScaleVmProfileVO vmProfile) {
+        long templateId = vmProfile.getTemplateId();
+        long autoscaleUserId = vmProfile.getAutoScaleUserId();
+        int destroyVmGraceperiod = vmProfile.getDestroyVmGraceperiod();
+
+        VirtualMachineTemplate template = _templateMgr.getTemplate(templateId);
+        // Make sure a valid template ID was specified
+        if (template == null) {
+            throw new InvalidParameterValueException("Unable to use the given template.");
+        }
+
+        if (destroyVmGraceperiod < 0) {
+            throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.");
+        }
+
+        User user = _userDao.findById(autoscaleUserId);
+        if (user.getAccountId() != vmProfile.getAccountId()) {
+            throw new InvalidParameterValueException("AutoScale User id does not belong to the same account");
+        }
+
+        String apiKey = user.getApiKey();
+        String secretKey = user.getSecretKey();
+        String csUrl = _configDao.getValue(Config.EndpointeUrl.key());
+
+        if(apiKey == null) {
+            throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it");
+        }
+
+        if(secretKey == null) {
+            throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it");
+        }
+
+        if(csUrl == null || csUrl.contains("localhost")) {
+            throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point");
+        }
+
+        vmProfile = _autoScaleVmProfileDao.persist(vmProfile);
+
+        return vmProfile;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_CREATE, eventDescription = "creating autoscale vm profile", create = true)
+    public AutoScaleVmProfile createAutoScaleVmProfile(CreateAutoScaleVmProfileCmd cmd) {
+
+        Account owner = _accountDao.findById(cmd.getAccountId());
+        Account caller = UserContext.current().getCaller();
+        _accountMgr.checkAccess(caller, null, true, owner);
+
+        long zoneId = cmd.getZoneId();
+        long serviceOfferingId = cmd.getServiceOfferingId();
+        Long autoscaleUserId = cmd.getAutoscaleUserId();
+
+        DataCenter zone = _configMgr.getZone(zoneId);
+
+        if (zone == null) {
+            throw new InvalidParameterValueException("Unable to find zone by id");
+        }
+
+        ServiceOffering serviceOffering = _configMgr.getServiceOffering(serviceOfferingId);
+        if (serviceOffering == null) {
+            throw new InvalidParameterValueException("Unable to find service offering by id");
+        }
+
+        // validations
+        HashMap<String, String> deployParams = cmd.getDeployParamMap();
+        /*
+         * Just for making sure the values are right in other deploy params.
+         * For ex. if projectId is given as a string instead of an long value, this
+         * will be throwing an error.
+         */
+        ApiDispatcher.setupParameters(new DeployVMCmd(), deployParams);
+
+        if (autoscaleUserId == null) {
+            autoscaleUserId = UserContext.current().getCallerUserId();
+        }
+
+
+        AutoScaleVmProfileVO profileVO = new AutoScaleVmProfileVO(cmd.getZoneId(), cmd.getDomainId(), cmd.getAccountId(), cmd.getServiceOfferingId(), cmd.getTemplateId(), cmd.getOtherDeployParams(),
+                cmd.getSnmpCommunity(), cmd.getSnmpPort(), cmd.getDestroyVmGraceperiod(), autoscaleUserId);
+        profileVO = checkValidityAndPersist(profileVO);
+        s_logger.info("Successfully create AutoScale Vm Profile with Id: " + profileVO.getId());
+
+        return profileVO;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_UPDATE, eventDescription = "updating autoscale vm profile")
+    public AutoScaleVmProfile updateAutoScaleVmProfile(UpdateAutoScaleVmProfileCmd cmd) {
+        Long profileId = cmd.getId();
+        Long templateId = cmd.getTemplateId();
+        Long autoscaleUserId = cmd.getAutoscaleUserId();
+        Integer snmpPort = cmd.getSnmpPort();
+        String snmpCommunity = cmd.getSnmpCommunity();
+        Integer destroyVmGraceperiod = cmd.getDestroyVmGraceperiod();
+
+        AutoScaleVmProfileVO vmProfile = getEntityInDatabase(UserContext.current().getCaller(), "Auto Scale Vm Profile", profileId, _autoScaleVmProfileDao);
+
+        if (templateId != null) {
+            vmProfile.setTemplateId(templateId);
+        }
+
+        if (autoscaleUserId != null) {
+            vmProfile.setAutoscaleUserId(autoscaleUserId);
+        }
+
+        if (snmpCommunity != null) {
+            vmProfile.setSnmpCommunity(snmpCommunity);
+        }
+
+        if (snmpPort != null) {
+            vmProfile.setSnmpPort(snmpPort);
+        }
+
+        if (destroyVmGraceperiod != null) {
+            vmProfile.setDestroyVmGraceperiod(destroyVmGraceperiod);
+        }
+
+        List<AutoScaleVmGroupVO> vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId);
+        for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) {
+            if (vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
+                throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state");
+            }
+        }
+
+        vmProfile = checkValidityAndPersist(vmProfile);
+        s_logger.info("Updated Auto Scale Vm Profile id:" + vmProfile.getId());
+
+        return vmProfile;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_DELETE, eventDescription = "deleting autoscale vm profile")
+    public boolean deleteAutoScaleVmProfile(long id) {
+        /* Check if entity is in database */
+        getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao);
+        if (_autoScaleVmGroupDao.isProfileInUse(id)) {
+            throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups");
+        }
+        boolean success = _autoScaleVmProfileDao.remove(id);
+        if (success) {
+            s_logger.info("Successfully deleted AutoScale Vm Profile with Id: " + id);
+        }
+        return success;
+    }
+
+    @Override
+    public List<? extends AutoScaleVmProfile> listAutoScaleVmProfiles(ListAutoScaleVmProfilesCmd cmd) {
+        Long id = cmd.getId();
+        Long templateId = cmd.getTemplateId();
+        String otherDeployParams = cmd.getOtherDeployParams();
+
+        SearchWrapper<AutoScaleVmProfileVO> searchWrapper = new SearchWrapper<AutoScaleVmProfileVO>(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId());
+        SearchBuilder<AutoScaleVmProfileVO> sb = searchWrapper.getSearchBuilder();
+
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
+        sb.and("otherDeployParams", sb.entity().getOtherDeployParams(), SearchCriteria.Op.LIKE);
+        SearchCriteria<AutoScaleVmProfileVO> sc = searchWrapper.buildSearchCriteria();
+
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+        if (templateId != null) {
+            sc.setParameters("templateId", templateId);
+        }
+        if (otherDeployParams != null) {
+            sc.addAnd("otherDeployParams", SearchCriteria.Op.LIKE, "%" + otherDeployParams + "%");
+        }
+        return searchWrapper.search();
+    }
+
+    @DB
+    protected AutoScalePolicyVO checkValidityAndPersist(AutoScalePolicyVO autoScalePolicyVO, List<Long> conditionIds) {
+        int duration = autoScalePolicyVO.getDuration();
+        int quietTime = autoScalePolicyVO.getQuietTime();
+
+        if (duration < 0) {
+            throw new InvalidParameterValueException("duration is an invalid value: " + duration);
+        }
+
+        if (quietTime < 0) {
+            throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime);
+        }
+
+        final Transaction txn = Transaction.currentTxn();
+        txn.start();
+
+        autoScalePolicyVO = _autoScalePolicyDao.persist(autoScalePolicyVO);
+
+        if (conditionIds != null) {
+            SearchBuilder<ConditionVO> conditionsSearch = _conditionDao.createSearchBuilder();
+            conditionsSearch.and("ids", conditionsSearch.entity().getId(), Op.IN);
+            conditionsSearch.done();
+            SearchCriteria<ConditionVO> sc = conditionsSearch.create();
+
+            sc.setParameters("ids", conditionIds.toArray(new Object[0]));
+            List<ConditionVO> conditions = _conditionDao.search(sc, null);
+
+            ControlledEntity[] sameOwnerEntities = conditions.toArray(new ControlledEntity[conditions.size() + 1]);
+            sameOwnerEntities[sameOwnerEntities.length - 1] = autoScalePolicyVO;
+            _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, sameOwnerEntities);
+
+            if (conditionIds.size() != conditions.size()) {
+                // TODO report the condition id which could not be found
+                throw new InvalidParameterValueException("Unable to find the condition specified");
+            }
+
+            ArrayList<Long> counterIds = new ArrayList<Long>();
+            for (ConditionVO condition : conditions) {
+                if (counterIds.contains(condition.getCounterid())) {
+                    throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter");
+                }
+                counterIds.add(condition.getCounterid());
+            }
+
+            /* For update case remove the existing mappings and create fresh ones */
+            _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(autoScalePolicyVO.getId());
+
+            for (Long conditionId : conditionIds) {
+                AutoScalePolicyConditionMapVO policyConditionMapVO = new AutoScalePolicyConditionMapVO(autoScalePolicyVO.getId(), conditionId);
+                _autoScalePolicyConditionMapDao.persist(policyConditionMapVO);
+            }
+        }
+
+        txn.commit();
+        return autoScalePolicyVO;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_CREATE, eventDescription = "creating autoscale policy", create = true)
+    public AutoScalePolicy createAutoScalePolicy(CreateAutoScalePolicyCmd cmd) {
+
+        int duration = cmd.getDuration();
+        Integer quietTime = cmd.getQuietTime();
+        String action = cmd.getAction();
+
+        if (quietTime == null) {
+            quietTime = NetUtils.DEFAULT_AUTOSCALE_POLICY_QUIET_TIME;
+        }
+
+        action = action.toLowerCase();
+        if (!NetUtils.isValidAutoScaleAction(action)) {
+            throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported");
+        }
+
+        AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, action);
+
+        policyVO = checkValidityAndPersist(policyVO, cmd.getConditionIds());
+        s_logger.info("Successfully created AutoScale Policy with Id: " + policyVO.getId());
+        return policyVO;
+    }
+
+    @Override
+    @DB
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_DELETE, eventDescription = "deleting autoscale policy")
+    public boolean deleteAutoScalePolicy(long id) {
+        /* Check if entity is in database */
+        getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Policy", id, _autoScalePolicyDao);
+
+        if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) {
+            throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups");
+        }
+
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+
+        boolean success = true;
+        success = _autoScalePolicyDao.remove(id);
+        if (!success) {
+            s_logger.warn("Failed to remove AutoScale Policy db object");
+            return false;
+        }
+        success = _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(id);
+        if (!success) {
+            s_logger.warn("Failed to remove AutoScale Policy Condition mappings");
+            return false;
+        }
+        txn.commit();
+        s_logger.info("Successfully deleted autoscale policy id : " + id);
+        return true; // successful
+    }
+
+    public void checkCallerAccess(String accountName, Long domainId)
+    {
+        Account caller = UserContext.current().getCaller();
+        Account owner = _accountDao.findActiveAccount(accountName, domainId);
+        if (owner == null) {
+            List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
+            idList.add(new IdentityProxy("domain", domainId, "domainId"));
+            throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId");
+        }
+        _accountMgr.checkAccess(caller, null, false, owner);
+    }
+
+    private class SearchWrapper<VO extends ControlledEntity> {
+        GenericDao<VO, Long> dao;
+        SearchBuilder<VO> searchBuilder;
+        SearchCriteria<VO> searchCriteria;
+        Long domainId;
+        boolean isRecursive;
+        List<Long> permittedAccounts = new ArrayList<Long>();
+        ListProjectResourcesCriteria listProjectResourcesCriteria;
+        Filter searchFilter;
+
+        public SearchWrapper(GenericDao<VO, Long> dao, Class<VO> entityClass, BaseListAccountResourcesCmd cmd, Long id)
+        {
+            this.dao = dao;
+            this.searchBuilder = dao.createSearchBuilder();
+            domainId = cmd.getDomainId();
+            String accountName = cmd.getAccountName();
+            isRecursive = cmd.isRecursive();
+            boolean listAll = cmd.listAll();
+            long startIndex = cmd.getStartIndex();
+            long pageSizeVal = cmd.getPageSizeVal();
+            Account caller = UserContext.current().getCaller();
+
+            Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
+            ListProjectResourcesCriteria>(domainId, isRecursive, null);
+            _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject,
+                    listAll, false);
+            domainId = domainIdRecursiveListProject.first();
+            isRecursive = domainIdRecursiveListProject.second();
+            ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
+            _accountMgr.buildACLSearchBuilder(searchBuilder, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
+            searchFilter = new Filter(entityClass, "id", false, startIndex, pageSizeVal);
+        }
+
+        public SearchBuilder<VO> getSearchBuilder() {
+            return searchBuilder;
+        }
+
+        public SearchCriteria<VO> buildSearchCriteria()
+        {
+            searchCriteria = searchBuilder.create();
+            _accountMgr.buildACLSearchCriteria(searchCriteria, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
+            return searchCriteria;
+        }
+
+        public List<VO> search() {
+            return dao.search(searchCriteria, searchFilter);
+        }
+    }
+
+    @Override
+    public List<? extends AutoScalePolicy> listAutoScalePolicies(ListAutoScalePoliciesCmd cmd) {
+        SearchWrapper<AutoScalePolicyVO> searchWrapper = new SearchWrapper<AutoScalePolicyVO>(_autoScalePolicyDao, AutoScalePolicyVO.class, cmd, cmd.getId());
+        SearchBuilder<AutoScalePolicyVO> sb = searchWrapper.getSearchBuilder();
+        Long id = cmd.getId();
+        Long conditionId = cmd.getConditionId();
+        String action = cmd.getAction();
+        Long vmGroupId = cmd.getVmGroupId();
+
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("action", sb.entity().getAction(), SearchCriteria.Op.EQ);
+
+        if (conditionId != null) {
+            SearchBuilder<AutoScalePolicyConditionMapVO> asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder();
+            asPolicyConditionSearch.and("conditionId", asPolicyConditionSearch.entity().getConditionId(), SearchCriteria.Op.EQ);
+            sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER);
+        }
+
+        if (vmGroupId != null) {
+            SearchBuilder<AutoScaleVmGroupPolicyMapVO> asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder();
+            asVmGroupPolicySearch.and("vmGroupId", asVmGroupPolicySearch.entity().getVmGroupId(), SearchCriteria.Op.EQ);
+            sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER);
+        }
+
+        SearchCriteria<AutoScalePolicyVO> sc = searchWrapper.buildSearchCriteria();
+
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+
+        if (action != null) {
+            sc.setParameters("action", action);
+        }
+
+        if (conditionId != null) {
+            sc.setJoinParameters("asPolicyConditionSearch", "conditionId", conditionId);
+        }
+
+        if (vmGroupId != null) {
+            sc.setJoinParameters("asVmGroupPolicySearch", "vmGroupId", vmGroupId);
+        }
+
+        return searchWrapper.search();
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_UPDATE, eventDescription = "updating autoscale policy")
+    public AutoScalePolicy updateAutoScalePolicy(UpdateAutoScalePolicyCmd cmd) {
+        Long policyId = cmd.getId();
+        Integer duration = cmd.getDuration();
+        Integer quietTime = cmd.getQuietTime();
+        List<Long> conditionIds = cmd.getConditionIds();
+        AutoScalePolicyVO policy = getEntityInDatabase(UserContext.current().getCaller(), "Auto Scale Policy", policyId, _autoScalePolicyDao);
+
+        if (duration != null) {
+            policy.setDuration(duration);
+        }
+
+        if (quietTime != null) {
+            policy.setQuietTime(quietTime);
+        }
+
+        List<AutoScaleVmGroupPolicyMapVO> vmGroupPolicyList = _autoScaleVmGroupPolicyMapDao.listByPolicyId(policyId);
+        for (AutoScaleVmGroupPolicyMapVO vmGroupPolicy : vmGroupPolicyList) {
+            AutoScaleVmGroupVO vmGroupVO = _autoScaleVmGroupDao.findById(vmGroupPolicy.getVmGroupId());
+            if(vmGroupVO == null) {
+                s_logger.warn("Stale database entry! There is an entry in VmGroupPolicyMap but the vmGroup is missing:" + vmGroupPolicy.getVmGroupId());
+
+                continue;
+
+            }
+            if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
+                throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state");
+            }
+            if (vmGroupVO.getInterval() < policy.getDuration()) {
+                throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval");
+            }
+            if (vmGroupVO.getInterval() < policy.getQuietTime()) {
+                throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval");
+            }
+        }
+
+        policy = checkValidityAndPersist(policy, conditionIds);
+        s_logger.info("Successfully updated Auto Scale Policy id:" + policyId);
+        return policy;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE, eventDescription = "creating autoscale vm group", create = true)
+    public AutoScaleVmGroup createAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) {
+        int minMembers = cmd.getMinMembers();
+        int maxMembers = cmd.getMaxMembers();
+        Integer interval = cmd.getInterval();
+
+        if (interval == null) {
+            interval = NetUtils.DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME;
+        }
+
+        LoadBalancerVO loadBalancer = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.LBID, cmd.getLbRuleId(), _lbDao);
+
+        Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId();
+
+        if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) {
+            throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted");
+        }
+
+        if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) {
+            throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule");
+        }
+
+        AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers,
+                loadBalancer.getDefaultPortStart(), interval, cmd.getProfileId(), AutoScaleVmGroup.State_New);
+
+        vmGroupVO = checkValidityAndPersist(vmGroupVO, cmd.getScaleUpPolicyIds(), cmd.getScaleDownPolicyIds());
+        s_logger.info("Successfully created Autoscale Vm Group with Id: " + vmGroupVO.getId());
+
+        return vmGroupVO;
+    }
+
+    @Override
+    public boolean configureAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) {
+        return configureAutoScaleVmGroup(cmd.getEntityId());
+    }
+
+    public boolean isLoadBalancerBasedAutoScaleVmGroup(AutoScaleVmGroup vmGroup) {
+        return vmGroup.getLoadBalancerId() != null;
+    }
+
+    public boolean configureAutoScaleVmGroup(long vmGroupid) {
+        AutoScaleVmGroup vmGroup = _autoScaleVmGroupDao.findById(vmGroupid);
+
+        if (isLoadBalancerBasedAutoScaleVmGroup(vmGroup)) {
+            try {
+                return _lbRulesMgr.configureLbAutoScaleVmGroup(vmGroupid);
+            } catch (RuntimeException re) {
+                s_logger.warn("Exception during configureLbAutoScaleVmGrouop in lb rules manager", re);
+            }
+        }
+
+        // This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup.
+        throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported");
+    }
+
+    @Override
+    @DB
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DELETE, eventDescription = "deleting autoscale vm group")
+    public boolean deleteAutoScaleVmGroup(long id) {
+        AutoScaleVmGroupVO autoScaleVmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
+
+        if (autoScaleVmGroupVO.getState().equals(AutoScaleVmGroup.State_New)) {
+            /* This condition is for handling failures during creation command */
+            return _autoScaleVmGroupDao.remove(id);
+        }
+        String bakupState = autoScaleVmGroupVO.getState();
+        autoScaleVmGroupVO.setState(AutoScaleVmGroup.State_Revoke);
+        _autoScaleVmGroupDao.persist(autoScaleVmGroupVO);
+        boolean success = false;
+
+        try {
+            success = configureAutoScaleVmGroup(id);
+        } finally {
+            if (!success) {
+                s_logger.warn("Could not delete AutoScale Vm Group id : " + id);
+                autoScaleVmGroupVO.setState(bakupState);
+                _autoScaleVmGroupDao.persist(autoScaleVmGroupVO);
+                return false;
+            }
+        }
+
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+        success = _autoScaleVmGroupDao.remove(id);
+
+        if (!success) {
+            s_logger.warn("Failed to remove AutoScale Group db object");
+            return false;
+        }
+
+        success = _autoScaleVmGroupPolicyMapDao.removeByGroupId(id);
+        if (!success) {
+            s_logger.warn("Failed to remove AutoScale Group Policy mappings");
+            return false;
+        }
+
+        txn.commit();
+        s_logger.info("Successfully deleted autoscale vm group id : " + id);
+        return success; // Successfull
+    }
+
+    @Override
+    public List<? extends AutoScaleVmGroup> listAutoScaleVmGroups(ListAutoScaleVmGroupsCmd cmd) {
+        Long id = cmd.getId();
+        Long policyId = cmd.getPolicyId();
+        Long loadBalancerId = cmd.getLoadBalancerId();
+        Long profileId = cmd.getProfileId();
+        Long zoneId = cmd.getZoneId();
+
+        SearchWrapper<AutoScaleVmGroupVO> searchWrapper = new SearchWrapper<AutoScaleVmGroupVO>(_autoScaleVmGroupDao, AutoScaleVmGroupVO.class, cmd, cmd.getId());
+        SearchBuilder<AutoScaleVmGroupVO> sb = searchWrapper.getSearchBuilder();
+
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("loadBalancerId", sb.entity().getLoadBalancerId(), SearchCriteria.Op.EQ);
+        sb.and("profileId", sb.entity().getProfileId(), SearchCriteria.Op.EQ);
+        sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.EQ);
+
+        if (policyId != null) {
+            SearchBuilder<AutoScaleVmGroupPolicyMapVO> asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder();
+            asVmGroupPolicySearch.and("policyId", asVmGroupPolicySearch.entity().getPolicyId(), SearchCriteria.Op.EQ);
+            sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getVmGroupId(), JoinBuilder.JoinType.INNER);
+        }
+
+        SearchCriteria<AutoScaleVmGroupVO> sc = searchWrapper.buildSearchCriteria();
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+        if (loadBalancerId != null) {
+            sc.setParameters("loadBalancerId", loadBalancerId);
+        }
+        if (profileId != null) {
+            sc.setParameters("profileId", profileId);
+        }
+        if (zoneId != null) {
+            sc.setParameters("zoneId", zoneId);
+        }
+        if (policyId != null) {
+            sc.setJoinParameters("asVmGroupPolicySearch", "policyId", policyId);
+        }
+        return searchWrapper.search();
+    }
+
+    @DB
+    protected AutoScaleVmGroupVO checkValidityAndPersist(AutoScaleVmGroupVO vmGroup, List<Long> scaleUpPolicyIds, List<Long> scaleDownPolicyIds) {
+        int minMembers = vmGroup.getMinMembers();
+        int maxMembers = vmGroup.getMaxMembers();
+        int interval = vmGroup.getInterval();
+        List<Counter> counters = new ArrayList<Counter>();
+        List<AutoScalePolicyVO> policies = new ArrayList<AutoScalePolicyVO>();
+        List<Long> policyIds = new ArrayList<Long>();
+
+        if (minMembers < 0) {
+            throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers);
+        }
+
+        if (maxMembers < 0) {
+            throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers);
+        }
+
+        if (minMembers > maxMembers) {
+            throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")");
+        }
+
+        if (interval < 0) {
+            throw new InvalidParameterValueException("interval is an invalid value: " + interval);
+        }
+
+        if (scaleUpPolicyIds != null) {
+            policies.addAll(getAutoScalePolicies("scaleuppolicyid", scaleUpPolicyIds, counters, interval, true));
+        }
+
+        if (scaleDownPolicyIds != null) {
+            policies.addAll(getAutoScalePolicies("scaledownpolicyid", scaleDownPolicyIds, counters, interval, false));
+        }
+
+        LoadBalancerVO loadBalancer = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.LBID, vmGroup.getLoadBalancerId(), _lbDao);
+        validateAutoScaleCounters(loadBalancer.getNetworkId(), counters);
+
+        AutoScaleVmProfileVO profileVO = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.VMPROFILE_ID, vmGroup.getProfileId(), _autoScaleVmProfileDao);
+
+        ControlledEntity[] sameOwnerEntities = policies.toArray(new ControlledEntity[policies.size() + 2]);
+        sameOwnerEntities[sameOwnerEntities.length - 2] = loadBalancer;
+        sameOwnerEntities[sameOwnerEntities.length - 1] = profileVO;
+        _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, sameOwnerEntities);
+
+        final Transaction txn = Transaction.currentTxn();
+        txn.start();
+        vmGroup = _autoScaleVmGroupDao.persist(vmGroup);
+
+        if (scaleUpPolicyIds != null || scaleDownPolicyIds != null) {
+            List<Long> bakupScaleUpPolicyIds = new ArrayList<Long>();
+            List<Long> bakupScaleDownPolicyIds = new ArrayList<Long>();
+            ApiDBUtils.getAutoScaleVmGroupPolicyIds(vmGroup.getId(), bakupScaleUpPolicyIds, bakupScaleDownPolicyIds);
+            if (scaleUpPolicyIds == null) {
+                policyIds.addAll(bakupScaleUpPolicyIds);
+            } else {
+                policyIds.addAll(scaleUpPolicyIds);
+            }
+            if (scaleDownPolicyIds == null) {
+                policyIds.addAll(bakupScaleDownPolicyIds);
+            } else {
+                policyIds.addAll(scaleDownPolicyIds);
+            }
+
+            _autoScaleVmGroupPolicyMapDao.removeByGroupId(vmGroup.getId());
+
+            for (Long policyId : policyIds) {
+                _autoScaleVmGroupPolicyMapDao.persist(new AutoScaleVmGroupPolicyMapVO(vmGroup.getId(), policyId));
+            }
+        }
+        txn.commit();
+
+        return vmGroup;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE, eventDescription = "updating autoscale vm group")
+    public AutoScaleVmGroup updateAutoScaleVmGroup(UpdateAutoScaleVmGroupCmd cmd) {
+        Long vmGroupId = cmd.getId();
+        Integer minMembers = cmd.getMinMembers();
+        Integer maxMembers = cmd.getMaxMembers();
+        Integer interval = cmd.getInterval();
+
+        List<Long> scaleUpPolicyIds = cmd.getScaleUpPolicyIds();
+        List<Long> scaleDownPolicyIds = cmd.getScaleDownPolicyIds();
+
+        AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao);
+
+        if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
+            throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state");
+        }
+
+        if (minMembers != null) {
+            vmGroupVO.setMinMembers(minMembers);
+        }
+
+        if (maxMembers != null) {
+            vmGroupVO.setMaxMembers(maxMembers);
+        }
+
+        if (interval != null) {
+            vmGroupVO.setInterval(interval);
+        }
+
+        vmGroupVO = checkValidityAndPersist(vmGroupVO, scaleUpPolicyIds, scaleDownPolicyIds);
+        if (vmGroupVO != null) {
+            s_logger.debug("Updated Auto Scale VmGroup id:" + vmGroupId);
+            return vmGroupVO;
+        } else
+            return null;
+    }
+
+    @Override
+    @DB
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE, eventDescription = "enabling autoscale vm group")
+    public AutoScaleVmGroup enableAutoScaleVmGroup(Long id) {
+        AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
+        boolean success = false;
+        if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) {
+            throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.");
+        }
+
+        try {
+            vmGroup.setState(AutoScaleVmGroup.State_Enabled);
+            vmGroup = _autoScaleVmGroupDao.persist(vmGroup);
+            success = configureAutoScaleVmGroup(id);
+
+        } finally {
+            if (!success) {
+                vmGroup.setState(AutoScaleVmGroup.State_Disabled);
+                _autoScaleVmGroupDao.persist(vmGroup);
+                s_logger.warn("Failed to enable AutoScale Vm Group id : " + id);
+                return null;
+            }
+            s_logger.info("Successfully enabled AutoScale Vm Group with Id:" + id);
+        }
+        return vmGroup;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE, eventDescription = "disabling autoscale vm group")
+    @DB
+    public AutoScaleVmGroup disableAutoScaleVmGroup(Long id) {
+        AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
+        boolean success = false;
+        if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) {
+            throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.");
+        }
+
+        try {
+            vmGroup.setState(AutoScaleVmGroup.State_Disabled);
+            vmGroup = _autoScaleVmGroupDao.persist(vmGroup);
+            success = configureAutoScaleVmGroup(id);
+        } finally {
+            if (!success) {
+                vmGroup.setState(AutoScaleVmGroup.State_Enabled);
+                _autoScaleVmGroupDao.persist(vmGroup);
+                s_logger.warn("Failed to disable AutoScale Vm Group id : " + id);
+                return null;
+            }
+            s_logger.info("Successfully disabled AutoScale Vm Group with Id:" + id);
+        }
+        return vmGroup;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_COUNTER_CREATE, eventDescription = "Counter", create = true)
+    @DB
+    public Counter createCounter(CreateCounterCmd cmd) {
+        String source = cmd.getSource().toLowerCase();
+        String name = cmd.getName();
+        Counter.Source src;
+        // Validate Source
+        try {
+            src = Counter.Source.valueOf(source);
+        } catch (Exception ex) {
+            throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter");
+        }
+
+        CounterVO counter = null;
+
+        s_logger.debug("Adding Counter " + name);
+        counter = _counterDao.persist(new CounterVO(src, name, cmd.getValue()));
+
+        UserContext.current().setEventDetails(" Id: " + counter.getId() + " Name: " + name);
+        return counter;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_CONDITION_CREATE, eventDescription = "Condition", create = true)
+    public Condition createCondition(CreateConditionCmd cmd) {
+        checkCallerAccess(cmd.getAccountName(), cmd.getDomainId());
+        String opr = cmd.getRelationalOperator().toUpperCase();
+        long cid = cmd.getCounterId();
+        long threshold = cmd.getThreshold();
+        Condition.Operator op;
+        // Validate Relational Operator
+        try {
+            op = Condition.Operator.valueOf(opr);
+        } catch (IllegalArgumentException ex) {
+            throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.");
+        }
+        // TODO - Validate threshold
+
+        CounterVO counter = _counterDao.findById(cid);
+
+        if (counter == null) {
+            throw new InvalidParameterValueException("Unable to find counter");
+        }
+        ConditionVO condition = null;
+
+        condition = _conditionDao.persist(new ConditionVO(cid, threshold, cmd.getEntityOwnerId(), cmd.getDomainId(), op));
+        s_logger.info("Successfully created condition with Id: " + condition.getId());
+
+        UserContext.current().setEventDetails(" Id: " + condition.getId());
+        return condition;
+    }
+
+    @Override
+    public List<? extends Counter> listCounters(ListCountersCmd cmd) {
+        String name = cmd.getName();
+        Long id = cmd.getId();
+        String source = cmd.getSource();
+        if (source != null)
+            source = source.toLowerCase();
+
+        Filter searchFilter = new Filter(CounterVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
+
+        List<CounterVO> counters = _counterDao.listCounters(id, name, source, cmd.getKeyword(), searchFilter);
+
+        return counters;
+    }
+
+    @Override
+    public List<? extends Condition> listConditions(ListConditionsCmd cmd) {
+        Long id = cmd.getId();
+        Long counterId = cmd.getCounterId();
+        Long policyId = cmd.getPolicyId();
+        SearchWrapper<ConditionVO> searchWrapper = new SearchWrapper<ConditionVO>(_conditionDao, ConditionVO.class, cmd, cmd.getId());
+        SearchBuilder<ConditionVO> sb = searchWrapper.getSearchBuilder();
+        if (policyId != null) {
+            SearchBuilder<AutoScalePolicyConditionMapVO> asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder();
+            asPolicyConditionSearch.and("policyId", asPolicyConditionSearch.entity().getPolicyId(), SearchCriteria.Op.EQ);
+            sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getConditionId(), JoinBuilder.JoinType.INNER);
+        }
+
+        sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
+        sb.and("counterId", sb.entity().getCounterid(), SearchCriteria.Op.EQ);
+
+        // now set the SC criteria...
+        SearchCriteria<ConditionVO> sc = searchWrapper.buildSearchCriteria();
+
+        if (id != null) {
+            sc.setParameters("id", id);
+        }
+
+        if (counterId != null) {
+            sc.setParameters("counterId", counterId);
+        }
+
+        if (policyId != null) {
+            sc.setJoinParameters("asPolicyConditionSearch", "policyId", policyId);
+        }
+
+        return searchWrapper.search();
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_COUNTER_DELETE, eventDescription = "counter")
+    public boolean deleteCounter(long counterId) throws ResourceInUseException {
+        // Verify Counter id
+        CounterVO counter = _counterDao.findById(counterId);
+        if (counter == null) {
+            throw new InvalidParameterValueException("Unable to find Counter");
+        }
+
+        // Verify if it is used in any Condition
+
+        ConditionVO condition = _conditionDao.findByCounterId(counterId);
+        if (condition != null) {
+            s_logger.info("Cannot delete counter " + counter.getName() + " as it is being used in a condition.");
+            throw new ResourceInUseException("Counter is in use.");
+        }
+
+        boolean success = _counterDao.remove(counterId);
+        if (success) {
+            s_logger.info("Successfully deleted counter with Id: " + counterId);
+        }
+
+        return success;
+    }
+
+    @Override
+    @ActionEvent(eventType = EventTypes.EVENT_CONDITION_DELETE, eventDescription = "condition")
+    public boolean deleteCondition(long conditionId) throws ResourceInUseException {
+        /* Check if entity is in database */
+        ConditionVO condition = getEntityInDatabase(UserContext.current().getCaller(), "Condition", conditionId, _conditionDao);
+        if (condition == null) {
+            throw new InvalidParameterValueException("Unable to find Condition");
+        }
+
+        // Verify if condition is used in any autoscale policy
+        if (_autoScalePolicyConditionMapDao.isConditionInUse(conditionId)) {
+            s_logger.info("Cannot delete condition " + conditionId + " as it is being used in a condition.");
+            throw new ResourceInUseException("Cannot delete Condition when it is in use by one or more AutoScale Policies.");
+        }
+        boolean success = _conditionDao.remove(conditionId);
+        if (success) {
+            s_logger.info("Successfully deleted condition " + condition.getId());
+        }
+        return success;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java
new file mode 100644
index 0000000..b387b93
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java
@@ -0,0 +1,59 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name=("autoscale_policy_condition_map"))
+public class AutoScalePolicyConditionMapVO {
+
+    @Id
+    @GeneratedValue(strategy=GenerationType.IDENTITY)
+    @Column(name="id")
+    private long id;
+
+    @Column(name="policy_id")
+    private long policyId;
+
+    @Column(name="condition_id")
+    private long conditionId;
+
+    public AutoScalePolicyConditionMapVO() { }
+
+    public AutoScalePolicyConditionMapVO(long policyId, long conditionId) {
+        this.policyId = policyId;
+        this.conditionId = conditionId;
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public long getPolicyId() {
+        return policyId;
+    }
+
+    public long getConditionId() {
+        return conditionId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScalePolicyVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScalePolicyVO.java b/server/src/com/cloud/network/as/AutoScalePolicyVO.java
new file mode 100644
index 0000000..e23e34d
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScalePolicyVO.java
@@ -0,0 +1,133 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import com.cloud.utils.db.GenericDao;
+
+@Entity
+@Table(name = "autoscale_policies")
+@Inheritance(strategy = InheritanceType.JOINED)
+public class AutoScalePolicyVO implements AutoScalePolicy {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    long id;
+
+    @Column(name = "uuid")
+    String uuid;
+
+    @Column(name = "domain_id")
+    private long domainId;
+
+    @Column(name = "account_id")
+    private long accountId;
+
+    @Column(name = "duration")
+    private int duration;
+
+    @Column(name = "quiet_time", updatable = true, nullable = false)
+    private int quietTime;
+
+    @Column(name = "action", updatable = false, nullable = false)
+    private String action;
+
+    @Column(name = GenericDao.REMOVED_COLUMN)
+    protected Date removed;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    protected Date created;
+
+    public AutoScalePolicyVO() {
+    }
+
+    public AutoScalePolicyVO(long domainId, long accountId, int duration, int quietTime, String action) {
+        this.uuid = UUID.randomUUID().toString();
+        this.domainId = domainId;
+        this.accountId = accountId;
+        this.duration = duration;
+        this.quietTime = quietTime;
+        this.action = action;
+    }
+
+    @Override
+    public String toString() {
+        return new StringBuilder("AutoScalePolicy[").append("id-").append(id).append("]").toString();
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    public String getUuid() {
+        return uuid;
+    }
+
+    @Override
+    public long getDomainId() {
+        return domainId;
+    }
+
+    @Override
+    public long getAccountId() {
+        return accountId;
+    }
+
+    @Override
+    public int getDuration() {
+        return duration;
+    }
+
+    @Override
+    public int getQuietTime() {
+        return quietTime;
+    }
+
+    @Override
+    public String getAction() {
+        return action;
+    }
+
+    public Date getRemoved() {
+        return removed;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    public void setDuration(Integer duration) {
+        this.duration = duration;
+    }
+
+    public void setQuietTime(Integer quietTime) {
+        this.quietTime = quietTime;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java
new file mode 100644
index 0000000..9ea6cab
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java
@@ -0,0 +1,62 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name=("autoscale_vmgroup_policy_map"))
+public class AutoScaleVmGroupPolicyMapVO {
+    @Id
+    @GeneratedValue(strategy=GenerationType.IDENTITY)
+    @Column(name="id")
+    private long id;
+
+    @Column(name="vmgroup_id")
+    private long vmGroupId;
+
+    @Column(name="policy_id")
+    private long policyId;
+
+    public AutoScaleVmGroupPolicyMapVO() { }
+
+    public AutoScaleVmGroupPolicyMapVO(long vmGroupId, long policyId) {
+        this.vmGroupId = vmGroupId;
+        this.policyId = policyId;
+    }
+
+    public AutoScaleVmGroupPolicyMapVO(long vmgroupId, long policyId, boolean revoke) {
+        this(vmgroupId, policyId);
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public long getVmGroupId() {
+        return vmGroupId;
+    }
+
+    public long getPolicyId() {
+        return policyId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java
new file mode 100644
index 0000000..3de9f9b
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java
@@ -0,0 +1,185 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import com.cloud.utils.db.GenericDao;
+
+@Entity
+@Table(name = "autoscale_vmgroups")
+@Inheritance(strategy = InheritanceType.JOINED)
+public class AutoScaleVmGroupVO implements AutoScaleVmGroup {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    long id;
+
+    @Column(name = "uuid")
+    String uuid;
+
+    @Column(name = "zone_id", updatable = false)
+    private long zoneId;
+
+    @Column(name = "domain_id", updatable = false)
+    private long domainId;
+
+    @Column(name = "account_id")
+    private long accountId;
+
+    @Column(name = "load_balancer_id")
+    private Long loadBalancerId;
+
+    @Column(name = "min_members", updatable = true)
+    private int minMembers;
+
+    @Column(name = "max_members", updatable = true)
+    private int maxMembers;
+
+    @Column(name = "member_port")
+    private int memberPort;
+
+    @Column(name = "interval")
+    private int interval;
+
+    @Column(name = "profile_id")
+    private long profileId;
+
+    @Column(name = GenericDao.REMOVED_COLUMN)
+    protected Date removed;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    protected Date created;
+
+    @Column(name = "state")
+    private String state;
+
+    public AutoScaleVmGroupVO() {
+    }
+
+    public AutoScaleVmGroupVO(long lbRuleId, long zoneId, long domainId, long accountId, int minMembers, int maxMembers, int memberPort, int interval, long profileId, String state) {
+        this.uuid = UUID.randomUUID().toString();
+        this.loadBalancerId = lbRuleId;
+        this.minMembers = minMembers;
+        this.maxMembers = maxMembers;
+        this.memberPort = memberPort;
+        this.profileId = profileId;
+        this.accountId = accountId;
+        this.domainId = domainId;
+        this.zoneId = zoneId;
+        this.state = state;
+        this.interval = interval;
+    }
+
+    @Override
+    public String toString() {
+        return new StringBuilder("AutoScaleVmGroupVO[").append("id").append("]").toString();
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    public long getZoneId() {
+        return zoneId;
+    }
+
+    @Override
+    public long getDomainId() {
+        return domainId;
+    }
+
+    @Override
+    public long getAccountId() {
+        return accountId;
+    }
+
+    @Override
+    public Long getLoadBalancerId() {
+        return loadBalancerId;
+    }
+
+    @Override
+    public int getMinMembers() {
+        return minMembers;
+    }
+
+    @Override
+    public int getMaxMembers() {
+        return maxMembers;
+    }
+
+    @Override
+    public int getMemberPort() {
+        return memberPort;
+    }
+
+    @Override
+    public int getInterval() {
+        return interval;
+    }
+
+    @Override
+    public long getProfileId() {
+        return profileId;
+    }
+
+    public Date getRemoved() {
+        return removed;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    @Override
+    public String getState() {
+        return state;
+    }
+
+    public void setState(String state) {
+        this.state = state;
+    }
+
+    public void setMinMembers(int minMembers) {
+        this.minMembers = minMembers;
+    }
+
+    public void setMaxMembers(int maxMembers) {
+        this.maxMembers = maxMembers;
+    }
+
+    public void setInterval(Integer interval) {
+        this.interval = interval;
+    }
+
+    public void setLoadBalancerId(Long loadBalancerId) {
+        this.loadBalancerId = loadBalancerId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java
new file mode 100644
index 0000000..d963eef
--- /dev/null
+++ b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java
@@ -0,0 +1,196 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+import com.cloud.api.Identity;
+import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.net.NetUtils;
+
+@Entity
+@Table(name = "autoscale_vmprofiles")
+@Inheritance(strategy = InheritanceType.JOINED)
+public class AutoScaleVmProfileVO implements AutoScaleVmProfile, Identity {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    protected long id;
+
+    @Column(name = "uuid")
+    protected String uuid;
+
+    @Column(name = "zone_id", updatable = true, nullable = false)
+    protected Long zoneId;
+
+    @Column(name = "domain_id", updatable = true)
+    private long domainId;
+
+    @Column(name = "account_id")
+    private long accountId;
+
+    @Column(name = "autoscale_user_id")
+    private long autoscaleUserId;
+
+    @Column(name = "service_offering_id", updatable = true, nullable = false)
+    private Long serviceOfferingId;
+
+    @Column(name = "template_id", updatable = true, nullable = false, length = 17)
+    private Long templateId;
+
+    @Column(name = "other_deploy_params", updatable = true, length = 1024)
+    private String otherDeployParams;
+
+    @Column(name = "destroy_vm_grace_period", updatable = true)
+    private Integer destroyVmGraceperiod = NetUtils.DEFAULT_AUTOSCALE_VM_DESTROY_TIME;
+
+    @Column(name = "snmp_community", updatable = true)
+    private String snmpCommunity = NetUtils.DEFAULT_SNMP_COMMUNITY;
+
+    @Column(name = "snmp_port", updatable = true)
+    private Integer snmpPort = NetUtils.DEFAULT_SNMP_PORT;
+
+    @Column(name = GenericDao.REMOVED_COLUMN)
+    protected Date removed;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    protected Date created;
+
+    public AutoScaleVmProfileVO() {
+    }
+
+    public AutoScaleVmProfileVO(long zoneId, long domainId, long accountId, long serviceOfferingId, long templateId, String otherDeployParams, String snmpCommunity, Integer snmpPort, Integer destroyVmGraceperiod,
+            long autoscaleUserId) {
+        this.uuid = UUID.randomUUID().toString();
+        this.zoneId = zoneId;
+        this.domainId = domainId;
+        this.accountId = accountId;
+        this.serviceOfferingId = serviceOfferingId;
+        this.templateId = templateId;
+        this.otherDeployParams = otherDeployParams;
+        this.autoscaleUserId = autoscaleUserId;
+        if (destroyVmGraceperiod != null) {
+            this.destroyVmGraceperiod = destroyVmGraceperiod;
+        }
+        if (snmpCommunity != null) {
+            this.snmpCommunity = snmpCommunity;
+        }
+        if (snmpPort != null) {
+            this.snmpPort = snmpPort;
+        }
+    }
+
+    @Override
+    public String toString() {
+        return new StringBuilder("AutoScaleVMProfileVO[").append("id").append(id).append("-").append("templateId").append("-").append(templateId).append("]").toString();
+    }
+
+    @Override
+    public Long getTemplateId() {
+        return templateId;
+    }
+
+    public void setTemplateId(Long templateId) {
+        this.templateId = templateId;
+    }
+
+    @Override
+    public Long getServiceOfferingId() {
+        return serviceOfferingId;
+    }
+
+    @Override
+    public String getOtherDeployParams() {
+        return otherDeployParams;
+    }
+
+    public void setOtherDeployParams(String otherDeployParams) {
+        this.otherDeployParams = otherDeployParams;
+    }
+
+    @Override
+    public String getSnmpCommunity() {
+        return snmpCommunity;
+    }
+
+    public void setSnmpCommunity(String snmpCommunity) {
+        this.snmpCommunity = snmpCommunity;
+    }
+
+    @Override
+    public Integer getSnmpPort() {
+        return snmpPort;
+    }
+
+    public void setSnmpPort(Integer snmpPort) {
+        this.snmpPort = snmpPort;
+    }
+
+    @Override
+    public String getUuid() {
+        return uuid;
+    }
+
+    public void setAutoscaleUserId(long autoscaleUserId) {
+        this.autoscaleUserId = autoscaleUserId;
+    }
+
+    @Override
+    public Long getZoneId() {
+        return zoneId;
+    }
+
+    @Override
+    public long getAccountId() {
+        return accountId;
+    }
+
+    @Override
+    public long getDomainId() {
+        return domainId;
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    @Override
+    public Integer getDestroyVmGraceperiod() {
+        return destroyVmGraceperiod;
+    }
+
+    public void setDestroyVmGraceperiod(Integer destroyVmGraceperiod) {
+        this.destroyVmGraceperiod = destroyVmGraceperiod;
+    }
+
+    @Override
+    public long getAutoScaleUserId() {
+        return autoscaleUserId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/ConditionVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/ConditionVO.java b/server/src/com/cloud/network/as/ConditionVO.java
new file mode 100644
index 0000000..f4d6c70
--- /dev/null
+++ b/server/src/com/cloud/network/as/ConditionVO.java
@@ -0,0 +1,128 @@
+//       Licensed to the Apache Software Foundation (ASF) under one
+//       or more contributor license agreements.  See the NOTICE file
+//       distributed with this work for additional information
+//       regarding copyright ownership.  The ASF licenses this file
+//       to you under the Apache License, Version 2.0 (the
+//       "License"); you may not use this file except in compliance
+//       with the License.  You may obtain a copy of the License at
+//
+//         http://www.apache.org/licenses/LICENSE-2.0
+//
+//       Unless required by applicable law or agreed to in writing,
+//       software distributed under the License is distributed on an
+//       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+//       KIND, either express or implied.  See the License for the
+//       specific language governing permissions and limitations
+//       under the License.
+
+package com.cloud.network.as;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import com.cloud.api.Identity;
+import com.cloud.utils.db.GenericDao;
+
+@Entity
+@Table(name = "conditions")
+public class ConditionVO implements Condition, Identity {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    private long id;
+
+    @Column(name = "counter_id")
+    private long counterid;
+
+    @Column(name = "threshold")
+    private long threshold;
+
+    @Column(name = "relational_operator")
+    @Enumerated(value = EnumType.STRING)
+    private Operator relationalOperator;
+
+    @Column(name = "domain_id")
+    protected long domainId;
+
+    @Column(name = "account_id")
+    protected long accountId;
+
+    @Column(name = "uuid")
+    private String uuid;
+
+    @Column(name = GenericDao.REMOVED_COLUMN)
+    Date removed;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    Date created;
+
+    public ConditionVO() {
+    }
+
+    public ConditionVO(long counterid, long threshold, long accountId, long domainId, Operator relationalOperator) {
+        this.counterid = counterid;
+        this.threshold = threshold;
+        this.relationalOperator = relationalOperator;
+        this.accountId = accountId;
+        this.domainId = domainId;
+        this.uuid = UUID.randomUUID().toString();
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    @Override
+    public String toString() {
+        return new StringBuilder("Condition[").append("id-").append(id).append("]").toString();
+    }
+
+    @Override
+    public long getCounterid() {
+        return counterid;
+    }
+
+    @Override
+    public long getThreshold() {
+        return threshold;
+    }
+
+    @Override
+    public Operator getRelationalOperator() {
+        return relationalOperator;
+    }
+
+    @Override
+    public long getAccountId() {
+        return accountId;
+    }
+
+    @Override
+    public long getDomainId() {
+        return domainId;
+    }
+
+    @Override
+    public String getUuid() {
+        return this.uuid;
+    }
+
+    public Date getRemoved() {
+        return removed;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/CounterVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/CounterVO.java b/server/src/com/cloud/network/as/CounterVO.java
new file mode 100644
index 0000000..894110b
--- /dev/null
+++ b/server/src/com/cloud/network/as/CounterVO.java
@@ -0,0 +1,110 @@
+//       Licensed to the Apache Software Foundation (ASF) under one
+//       or more contributor license agreements.  See the NOTICE file
+//       distributed with this work for additional information
+//       regarding copyright ownership.  The ASF licenses this file
+//       to you under the Apache License, Version 2.0 (the
+//       "License"); you may not use this file except in compliance
+//       with the License.  You may obtain a copy of the License at
+//
+//         http://www.apache.org/licenses/LICENSE-2.0
+//
+//       Unless required by applicable law or agreed to in writing,
+//       software distributed under the License is distributed on an
+//       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+//       KIND, either express or implied.  See the License for the
+//       specific language governing permissions and limitations
+//       under the License.
+
+package com.cloud.network.as;
+
+import java.util.Date;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import com.cloud.api.Identity;
+import com.cloud.utils.db.GenericDao;
+
+@Entity
+@Table(name = "counter")
+public class CounterVO implements Counter, Identity {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    private long id;
+
+    @Column(name = "source")
+    @Enumerated(value = EnumType.STRING)
+    private Source source;
+
+    @Column(name = "name")
+    private String name;
+
+    @Column(name = "value")
+    private String value;
+
+    @Column(name = "uuid")
+    private String uuid;
+
+    @Column(name = GenericDao.REMOVED_COLUMN)
+    Date removed;
+
+    @Column(name = GenericDao.CREATED_COLUMN)
+    Date created;
+
+    public CounterVO() {
+    }
+
+    public CounterVO(Source source, String name, String value) {
+        this.source = source;
+        this.name = name;
+        this.value = value;
+        this.uuid = UUID.randomUUID().toString();
+    }
+
+    @Override
+    public String toString() {
+        return new StringBuilder("Counter[").append("id-").append(id).append("]").toString();
+    }
+
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    @Override
+    public String getValue() {
+        return value;
+    }
+
+    @Override
+    public Source getSource() {
+        return source;
+    }
+
+    @Override
+    public long getId() {
+        return id;
+    }
+
+    @Override
+    public String getUuid() {
+        return this.uuid;
+    }
+
+    public Date getRemoved() {
+        return removed;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java
new file mode 100644
index 0000000..88755bb
--- /dev/null
+++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java
@@ -0,0 +1,28 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as.dao;
+
+import java.util.List;
+
+import com.cloud.network.as.AutoScalePolicyConditionMapVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface AutoScalePolicyConditionMapDao extends GenericDao<AutoScalePolicyConditionMapVO, Long> {
+    List<AutoScalePolicyConditionMapVO> listByAll(Long policyId, Long conditionId);
+    public boolean isConditionInUse(Long conditionId);
+	boolean removeByAutoScalePolicyId(long id);
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java
new file mode 100644
index 0000000..84dd191
--- /dev/null
+++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java
@@ -0,0 +1,58 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import com.cloud.network.as.AutoScalePolicyConditionMapVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchCriteria;
+
+@Local(value={AutoScalePolicyConditionMapDao.class})
+public class AutoScalePolicyConditionMapDaoImpl extends GenericDaoBase<AutoScalePolicyConditionMapVO, Long> implements AutoScalePolicyConditionMapDao {
+
+	private SearchCriteria<AutoScalePolicyConditionMapVO> getSearchCriteria(Long policyId, Long conditionId)
+	{
+        SearchCriteria<AutoScalePolicyConditionMapVO> sc = createSearchCriteria();
+
+        if(policyId != null)
+            sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId);
+
+        if(conditionId != null)
+            sc.addAnd("conditionId", SearchCriteria.Op.EQ, conditionId);
+
+        return sc;
+	}
+	
+    @Override
+    public List<AutoScalePolicyConditionMapVO> listByAll(Long policyId, Long conditionId) {
+        return listBy(getSearchCriteria(policyId, conditionId));
+    }
+    
+    public boolean isConditionInUse(Long conditionId) {
+        return findOneBy(getSearchCriteria(null, conditionId)) != null;
+    }
+
+	@Override
+	public boolean removeByAutoScalePolicyId(long policyId) {
+        SearchCriteria<AutoScalePolicyConditionMapVO> sc = createSearchCriteria();
+        sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId);
+		return expunge(sc) > 0;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java
new file mode 100644
index 0000000..8edfa94
--- /dev/null
+++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java
@@ -0,0 +1,23 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as.dao;
+
+import com.cloud.network.as.AutoScalePolicyVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface AutoScalePolicyDao extends GenericDao<AutoScalePolicyVO, Long> {
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java
new file mode 100644
index 0000000..5dfe080
--- /dev/null
+++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java
@@ -0,0 +1,26 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as.dao;
+
+import javax.ejb.Local;
+
+import com.cloud.network.as.AutoScalePolicyVO;
+import com.cloud.utils.db.GenericDaoBase;
+
+@Local(value = { AutoScalePolicyDao.class })
+public class AutoScalePolicyDaoImpl extends GenericDaoBase<AutoScalePolicyVO, Long>  implements AutoScalePolicyDao {
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/e245efed/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java
new file mode 100644
index 0000000..a11bedd
--- /dev/null
+++ b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java
@@ -0,0 +1,28 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.network.as.dao;
+
+import java.util.List;
+
+import com.cloud.network.as.AutoScaleVmGroupVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface AutoScaleVmGroupDao extends GenericDao<AutoScaleVmGroupVO, Long> {
+    List<AutoScaleVmGroupVO> listByAll(Long loadBalancerId, Long profileId);
+    boolean isProfileInUse(long profileId);
+    boolean isAutoScaleLoadBalancer(Long loadBalancerId);
+}