cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From prachida...@apache.org
Subject [21/91] [abbrv] [partial] Moved most of the VOs and DAOs from server package into engine-schema as well
Date Thu, 09 May 2013 00:20:32 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
new file mode 100755
index 0000000..c2fd648
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/UserVmDaoImpl.java
@@ -0,0 +1,585 @@
+// 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.vm.dao;
+
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+import javax.ejb.Local;
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.configuration.Resource;
+import com.cloud.server.ResourceTag.TaggedResourceType;
+import com.cloud.tags.dao.ResourceTagDao;
+import com.cloud.tags.dao.ResourceTagsDaoImpl;
+import com.cloud.user.Account;
+
+import com.cloud.utils.db.Attribute;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.GenericSearchBuilder;
+import com.cloud.utils.db.JoinBuilder;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Func;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.NicVO;
+import com.cloud.vm.UserVmVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachine.State;
+import com.cloud.vm.dao.UserVmData.NicData;
+import com.cloud.vm.dao.UserVmData.SecurityGroupData;
+
+
+@Local(value={UserVmDao.class})
+public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements UserVmDao {
+    public static final Logger s_logger = Logger.getLogger(UserVmDaoImpl.class);
+
+    protected SearchBuilder<UserVmVO> AccountPodSearch;
+    protected SearchBuilder<UserVmVO> AccountDataCenterSearch;
+    protected SearchBuilder<UserVmVO> AccountSearch;
+    protected SearchBuilder<UserVmVO> HostSearch;
+    protected SearchBuilder<UserVmVO> LastHostSearch;
+    protected SearchBuilder<UserVmVO> HostUpSearch;
+    protected SearchBuilder<UserVmVO> HostRunningSearch;
+    protected SearchBuilder<UserVmVO> StateChangeSearch;
+    protected SearchBuilder<UserVmVO> AccountHostSearch;
+
+    protected SearchBuilder<UserVmVO> DestroySearch;
+    protected SearchBuilder<UserVmVO> AccountDataCenterVirtualSearch;
+    protected GenericSearchBuilder<UserVmVO, Long> CountByAccountPod;
+    protected GenericSearchBuilder<UserVmVO, Long> CountByAccount;
+    protected GenericSearchBuilder<UserVmVO, Long> PodsHavingVmsForAccount;
+
+    protected SearchBuilder<UserVmVO> UserVmSearch;
+    protected SearchBuilder<UserVmVO> UserVmByIsoSearch;
+    protected Attribute _updateTimeAttr;
+    // ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
+    @Inject ResourceTagDao _tagsDao;
+
+    private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " +
+		"GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC";
+
+    private static String VM_DETAILS = "select vm_instance.id, " +
+            "account.id, account.account_name, account.type, domain.name, instance_group.id, instance_group.name," +
+            "data_center.id, data_center.name, data_center.is_security_group_enabled, host.id, host.name, " +
+            "vm_template.id, vm_template.name, vm_template.display_text, iso.id, iso.name, " +
+            "vm_template.enable_password, service_offering.id, disk_offering.name, storage_pool.id, storage_pool.pool_type, " +
+            "service_offering.cpu, service_offering.speed, service_offering.ram_size, volumes.id, volumes.device_id, volumes.volume_type, security_group.id, security_group.name, " +
+            "security_group.description, nics.id, nics.ip4_address, nics.default_nic, nics.gateway, nics.network_id, nics.netmask, nics.mac_address, nics.broadcast_uri, nics.isolation_uri, " +
+            "networks.traffic_type, networks.guest_type, user_ip_address.id, user_ip_address.public_ip_address from vm_instance " +
+            "left join account on vm_instance.account_id=account.id  " +
+            "left join domain on vm_instance.domain_id=domain.id " +
+            "left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id " +
+            "left join instance_group on instance_group_vm_map.group_id=instance_group.id " +
+            "left join data_center on vm_instance.data_center_id=data_center.id " +
+            "left join host on vm_instance.host_id=host.id " +
+            "left join vm_template on vm_instance.vm_template_id=vm_template.id " +
+            "left join user_vm on vm_instance.id=user_vm.id " +
+            "left join vm_template iso on iso.id=user_vm.iso_id " +
+            "left join service_offering on vm_instance.service_offering_id=service_offering.id " +
+            "left join disk_offering  on vm_instance.service_offering_id=disk_offering.id " +
+            "left join volumes on vm_instance.id=volumes.instance_id " +
+            "left join storage_pool on volumes.pool_id=storage_pool.id " +
+            "left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id " +
+            "left join security_group on security_group_vm_map.security_group_id=security_group.id " +
+            "left join nics on vm_instance.id=nics.instance_id " +
+            "left join networks on nics.network_id=networks.id " +
+            "left join user_ip_address on user_ip_address.vm_id=vm_instance.id " +
+            "where vm_instance.id in (";
+
+    private static final int VM_DETAILS_BATCH_SIZE=100;
+
+    @Inject protected UserVmDetailsDao _detailsDao;
+    @Inject protected NicDao _nicDao;
+
+    public UserVmDaoImpl() {
+    }
+
+    @PostConstruct
+    void init() {
+        AccountSearch = createSearchBuilder();
+        AccountSearch.and("account", AccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountSearch.done();
+        
+        HostSearch = createSearchBuilder();
+        HostSearch.and("host", HostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
+        HostSearch.done();
+        
+        LastHostSearch = createSearchBuilder();
+        LastHostSearch.and("lastHost", LastHostSearch.entity().getLastHostId(), SearchCriteria.Op.EQ);
+        LastHostSearch.and("state", LastHostSearch.entity().getState(), SearchCriteria.Op.EQ);
+        LastHostSearch.done();
+        
+        HostUpSearch = createSearchBuilder();
+        HostUpSearch.and("host", HostUpSearch.entity().getHostId(), SearchCriteria.Op.EQ);
+        HostUpSearch.and("states", HostUpSearch.entity().getState(), SearchCriteria.Op.NIN);
+        HostUpSearch.done();
+        
+        HostRunningSearch = createSearchBuilder();
+        HostRunningSearch.and("host", HostRunningSearch.entity().getHostId(), SearchCriteria.Op.EQ);
+        HostRunningSearch.and("state", HostRunningSearch.entity().getState(), SearchCriteria.Op.EQ);
+        HostRunningSearch.done();
+        
+        AccountPodSearch = createSearchBuilder();
+        AccountPodSearch.and("account", AccountPodSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountPodSearch.and("pod", AccountPodSearch.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ);
+        AccountPodSearch.done();
+
+        AccountDataCenterSearch = createSearchBuilder();
+        AccountDataCenterSearch.and("account", AccountDataCenterSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountDataCenterSearch.and("dc", AccountDataCenterSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        AccountDataCenterSearch.done();
+
+        StateChangeSearch = createSearchBuilder();
+        StateChangeSearch.and("id", StateChangeSearch.entity().getId(), SearchCriteria.Op.EQ);
+        StateChangeSearch.and("states", StateChangeSearch.entity().getState(), SearchCriteria.Op.EQ);
+        StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), SearchCriteria.Op.EQ);
+        StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), SearchCriteria.Op.EQ);
+        StateChangeSearch.done();
+        
+        DestroySearch = createSearchBuilder();
+        DestroySearch.and("state", DestroySearch.entity().getState(), SearchCriteria.Op.IN);
+        DestroySearch.and("updateTime", DestroySearch.entity().getUpdateTime(), SearchCriteria.Op.LT);
+        DestroySearch.done();
+
+        AccountHostSearch = createSearchBuilder();
+        AccountHostSearch.and("accountId", AccountHostSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountHostSearch.and("hostId", AccountHostSearch.entity().getHostId(), SearchCriteria.Op.EQ);
+        AccountHostSearch.done();
+
+        CountByAccountPod = createSearchBuilder(Long.class);
+        CountByAccountPod.select(null, Func.COUNT, null);
+        CountByAccountPod.and("account", CountByAccountPod.entity().getAccountId(), SearchCriteria.Op.EQ);
+        CountByAccountPod.and("pod", CountByAccountPod.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ);
+        CountByAccountPod.done();
+
+        CountByAccount = createSearchBuilder(Long.class);
+        CountByAccount.select(null, Func.COUNT, null);
+        CountByAccount.and("account", CountByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
+        CountByAccount.and("type", CountByAccount.entity().getType(), SearchCriteria.Op.EQ);
+        CountByAccount.and("state", CountByAccount.entity().getState(), SearchCriteria.Op.NIN);        
+        CountByAccount.done();
+        
+        
+        SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
+        nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
+        nicSearch.and("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL);
+
+        AccountDataCenterVirtualSearch = createSearchBuilder();
+        AccountDataCenterVirtualSearch.and("account", AccountDataCenterVirtualSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
+        AccountDataCenterVirtualSearch.and("dc", AccountDataCenterVirtualSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
+        AccountDataCenterVirtualSearch.join("nicSearch", nicSearch, AccountDataCenterVirtualSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
+        AccountDataCenterVirtualSearch.done();
+
+        UserVmByIsoSearch = createSearchBuilder();
+        UserVmByIsoSearch.and("isoId", UserVmByIsoSearch.entity().getIsoId(), SearchCriteria.Op.EQ);
+        UserVmByIsoSearch.done();
+
+        _updateTimeAttr = _allAttributes.get("updateTime");
+        assert _updateTimeAttr != null : "Couldn't get this updateTime attribute";
+    }
+
+    @Override
+    public List<UserVmVO> listByAccountAndPod(long accountId, long podId) {
+	SearchCriteria<UserVmVO> sc = AccountPodSearch.create();
+	sc.setParameters("account", accountId);
+	sc.setParameters("pod", podId);
+
+	return listIncludingRemovedBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listByAccountAndDataCenter(long accountId, long dcId) {
+        SearchCriteria<UserVmVO> sc = AccountDataCenterSearch.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("dc", dcId);
+
+        return listIncludingRemovedBy(sc);
+    }
+
+    @Override
+    public void updateVM(long id, String displayName, boolean enable, Long osTypeId, String userData) {
+        UserVmVO vo = createForUpdate();
+        vo.setDisplayName(displayName);
+        vo.setHaEnabled(enable);
+        vo.setGuestOSId(osTypeId);
+        vo.setUserData(userData);
+        update(id, vo);
+    }
+
+    @Override
+    public List<UserVmVO> findDestroyedVms(Date date) {
+	SearchCriteria<UserVmVO> sc = DestroySearch.create();
+	sc.setParameters("state", State.Destroyed, State.Expunging, State.Error);
+	sc.setParameters("updateTime", date);
+
+	return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listByAccountId(long id) {
+        SearchCriteria<UserVmVO> sc = AccountSearch.create();
+        sc.setParameters("account", id);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listByHostId(Long id) {
+        SearchCriteria<UserVmVO> sc = HostSearch.create();
+        sc.setParameters("host", id);
+
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listByIsoId(Long isoId) {
+        SearchCriteria<UserVmVO> sc = UserVmByIsoSearch.create();
+        sc.setParameters("isoId", isoId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listUpByHostId(Long hostId) {
+        SearchCriteria<UserVmVO> sc = HostUpSearch.create();
+        sc.setParameters("host", hostId);
+        sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging});
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listRunningByHostId(long hostId) {
+        SearchCriteria<UserVmVO> sc = HostRunningSearch.create();
+        sc.setParameters("host", hostId);
+        sc.setParameters("state", State.Running);
+
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listVirtualNetworkInstancesByAcctAndZone(long accountId, long dcId, long networkId) {
+
+        SearchCriteria<UserVmVO> sc = AccountDataCenterVirtualSearch.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("dc", dcId);
+        sc.setJoinParameters("nicSearch", "networkId", networkId);
+
+        return listBy(sc);
+    }
+
+    @Override
+    public List<UserVmVO> listByNetworkIdAndStates(long networkId, State... states) {
+        if (UserVmSearch == null) {
+            SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
+            nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
+            nicSearch.and().op("ip4Address", nicSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL);
+            nicSearch.or("ip6Address", nicSearch.entity().getIp6Address(), SearchCriteria.Op.NNULL);
+            nicSearch.cp();
+
+            UserVmSearch = createSearchBuilder();
+            UserVmSearch.and("states", UserVmSearch.entity().getState(), SearchCriteria.Op.IN);
+            UserVmSearch.join("nicSearch", nicSearch, UserVmSearch.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
+            UserVmSearch.done();
+        }
+
+        SearchCriteria<UserVmVO> sc = UserVmSearch.create();
+        if (states != null && states.length != 0) {
+            sc.setParameters("states", (Object[]) states);
+        }
+        sc.setJoinParameters("nicSearch", "networkId", networkId);
+
+        return listBy(sc);
+    }
+
+	@Override
+	public List<UserVmVO> listByLastHostId(Long hostId) {
+		SearchCriteria<UserVmVO> sc = LastHostSearch.create();
+		sc.setParameters("lastHost", hostId);
+		sc.setParameters("state", State.Stopped);
+		return listBy(sc);
+	}
+
+	@Override
+	public List<UserVmVO> listByAccountIdAndHostId(long accountId, long hostId) {
+		SearchCriteria<UserVmVO> sc = AccountHostSearch.create();
+		sc.setParameters("hostId", hostId);
+		sc.setParameters("accountId", accountId);
+		return listBy(sc);
+	}
+
+	@Override
+	public void loadDetails(UserVmVO vm) {
+        Map<String, String> details = _detailsDao.findDetails(vm.getId());
+        vm.setDetails(details);
+	}
+
+	@Override
+    public void saveDetails(UserVmVO vm) {
+        Map<String, String> details = vm.getDetails();
+        if (details == null) {
+            return;
+        }
+        _detailsDao.persist(vm.getId(), details);
+    }
+
+    @Override
+    public List<Long> listPodIdsHavingVmsforAccount(long zoneId, long accountId){
+	Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        List<Long> result = new ArrayList<Long>();
+
+        try {
+            String sql = LIST_PODS_HAVING_VMS_FOR_ACCOUNT;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setLong(1, zoneId);
+            pstmt.setLong(2, accountId);
+
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                result.add(rs.getLong(1));
+            }
+            return result;
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + LIST_PODS_HAVING_VMS_FOR_ACCOUNT, e);
+        }
+    }
+
+    @Override
+    public Hashtable<Long, UserVmData> listVmDetails(Hashtable<Long, UserVmData> userVmDataHash){
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+
+        try {
+            int curr_index=0;
+
+            List<UserVmData> userVmDataList = new ArrayList(userVmDataHash.values());
+
+            if (userVmDataList.size() > VM_DETAILS_BATCH_SIZE){
+                pstmt = txn.prepareStatement(VM_DETAILS + getQueryBatchAppender(VM_DETAILS_BATCH_SIZE));
+                while ( (curr_index + VM_DETAILS_BATCH_SIZE) <= userVmDataList.size()){
+                    // set the vars value
+                    for (int k=1,j=curr_index;j<curr_index+VM_DETAILS_BATCH_SIZE;j++,k++){
+                        pstmt.setLong(k, userVmDataList.get(j).getId());
+                    }
+                    ResultSet rs = pstmt.executeQuery();
+                    while(rs.next()){
+                        long vm_id=rs.getLong("vm_instance.id");
+                        //check if the entry is already there
+                        UserVmData uvm=userVmDataHash.get(vm_id);
+                        if (uvm == null){
+                            uvm = new UserVmData();
+                            uvm.setId(vm_id);
+                        }
+                        // initialize the data with this row
+                        setUserVmData(uvm, rs);
+                    }
+                    rs.close();
+                    curr_index+=VM_DETAILS_BATCH_SIZE;
+                }
+            }
+
+
+            if (curr_index < userVmDataList.size()){
+                int batch_size = (userVmDataList.size() - curr_index);
+                pstmt = txn.prepareStatement(VM_DETAILS + getQueryBatchAppender(batch_size));
+                // set the vars value
+                for (int k=1,j=curr_index;j<curr_index+batch_size;j++,k++){
+                    pstmt.setLong(k, userVmDataList.get(j).getId());
+                }
+                ResultSet rs = pstmt.executeQuery();
+                while(rs.next()){
+                    long vm_id=rs.getLong("vm_instance.id");
+                    //check if the entry is already there
+                    UserVmData uvm=userVmDataHash.get(vm_id);
+                    if (uvm == null){
+                        uvm = new UserVmData();
+                        uvm.setId(vm_id);
+                    }
+                    // initialize the data with this row
+                    setUserVmData(uvm, rs);
+                }
+                rs.close();
+            }
+
+            if (pstmt!=null)pstmt.close();
+            return userVmDataHash;
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + VM_DETAILS, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + VM_DETAILS, e);
+        }
+    }
+
+
+
+    public static UserVmData setUserVmData(UserVmData userVmData, ResultSet rs)
+        throws SQLException
+    {
+
+        if (!userVmData.isInitialized()){
+
+            //account.account_name, account.type, domain.name,  instance_group.id, instance_group.name,"
+            userVmData.setAccountId(rs.getLong("account.id"));
+            userVmData.setAccountName(rs.getString("account.account_name"));
+            userVmData.setDomainName(rs.getString("domain.name"));
+
+            long grp_id = rs.getLong("instance_group.id");
+            if (grp_id > 0){
+                userVmData.setGroupId(grp_id);
+                userVmData.setGroup(rs.getString("instance_group.name"));
+            }
+
+            //"data_center.id, data_center.name, host.id, host.name, vm_template.id, vm_template.name, vm_template.display_text, vm_template.enable_password,
+            userVmData.setZoneId(rs.getLong("data_center.id"));
+            userVmData.setZoneName(rs.getString("data_center.name"));
+
+            userVmData.setHostId(rs.getLong("host.id"));
+            userVmData.setHostName(rs.getString("host.name"));
+
+            long template_id = rs.getLong("vm_template.id");
+            if (template_id > 0){
+                userVmData.setTemplateId(template_id);
+                userVmData.setTemplateName(rs.getString("vm_template.name"));
+                userVmData.setTemplateDisplayText(rs.getString("vm_template.display_text"));
+                userVmData.setPasswordEnabled(rs.getBoolean("vm_template.enable_password"));
+            }
+            else {
+                userVmData.setTemplateId(-1L);
+                userVmData.setTemplateName("ISO Boot");
+                userVmData.setTemplateDisplayText("ISO Boot");
+                userVmData.setPasswordEnabled(false);
+            }
+
+            long iso_id = rs.getLong("iso.id");
+            if (iso_id > 0){
+                userVmData.setIsoId(iso_id);
+                userVmData.setIsoName(rs.getString("iso.name"));
+            }
+
+
+            //service_offering.id, disk_offering.name, "
+            //"service_offering.cpu, service_offering.speed, service_offering.ram_size,
+            userVmData.setServiceOfferingId(rs.getLong("service_offering.id"));
+            userVmData.setServiceOfferingName(rs.getString("disk_offering.name"));
+            userVmData.setCpuNumber(rs.getInt("service_offering.cpu"));
+            userVmData.setCpuSpeed(rs.getInt("service_offering.speed"));
+            userVmData.setMemory(rs.getInt("service_offering.ram_size"));
+
+            // volumes.device_id, volumes.volume_type,
+            long vol_id = rs.getLong("volumes.id");
+            if (vol_id > 0){
+                userVmData.setRootDeviceId(rs.getLong("volumes.device_id"));
+                userVmData.setRootDeviceType(rs.getString("volumes.volume_type"));
+                // storage pool
+                long pool_id = rs.getLong("storage_pool.id");
+                if (pool_id > 0){
+                    userVmData.setRootDeviceType(rs.getString("storage_pool.pool_type"));
+                }
+                else {
+                    userVmData.setRootDeviceType("Not created");
+                }
+            }
+            userVmData.setInitialized();
+        }
+
+
+        Long securityGroupId = rs.getLong("security_group.id");
+        if (securityGroupId != null && securityGroupId.longValue() != 0){
+            SecurityGroupData resp = userVmData.newSecurityGroupData();
+            resp.setId(rs.getLong("security_group.id"));
+            resp.setName(rs.getString("security_group.name"));
+            resp.setDescription(rs.getString("security_group.description"));
+            resp.setObjectName("securitygroup");
+            userVmData.addSecurityGroup(resp);
+        }
+
+        long nic_id = rs.getLong("nics.id");
+        if (nic_id > 0){
+            NicData nicResponse = userVmData.newNicData();
+            nicResponse.setId(nic_id);
+            nicResponse.setIpaddress(rs.getString("nics.ip4_address"));
+            nicResponse.setGateway(rs.getString("nics.gateway"));
+            nicResponse.setNetmask(rs.getString("nics.netmask"));
+            nicResponse.setNetworkid(rs.getLong("nics.network_id"));
+            nicResponse.setMacAddress(rs.getString("nics.mac_address"));
+
+            int account_type = rs.getInt("account.type");
+            if (account_type == Account.ACCOUNT_TYPE_ADMIN) {
+                nicResponse.setBroadcastUri(rs.getString("nics.broadcast_uri"));
+                nicResponse.setIsolationUri(rs.getString("nics.isolation_uri"));
+            }
+
+
+            nicResponse.setTrafficType(rs.getString("networks.traffic_type"));
+            nicResponse.setType(rs.getString("networks.guest_type"));
+            nicResponse.setIsDefault(rs.getBoolean("nics.default_nic"));
+            nicResponse.setObjectName("nic");
+            userVmData.addNic(nicResponse);
+        }
+
+        long publicIpId = rs.getLong("user_ip_address.id");
+        if (publicIpId > 0){
+            userVmData.setPublicIpId(publicIpId);
+            userVmData.setPublicIp(rs.getString("user_ip_address.public_ip_address"));
+        }
+
+        return userVmData;
+    }
+
+    public String getQueryBatchAppender(int count){
+        StringBuilder sb = new StringBuilder();
+        for (int i=0;i<count;i++){
+            sb.append(" ?,");
+        }
+        sb.deleteCharAt(sb.length()-1).append(")");
+        return sb.toString();
+    }
+
+
+    @Override
+    public Long countAllocatedVMsForAccount(long accountId) {
+	SearchCriteria<Long> sc = CountByAccount.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("type", VirtualMachine.Type.User);
+		sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging});
+        return customSearch(sc, null).get(0);
+    }
+
+    @Override
+    public boolean remove(Long id) {
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+        _tagsDao.removeByIdAndType(id, TaggedResourceType.UserVm);
+        boolean result = super.remove(id);
+        txn.commit();
+        return result;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/UserVmData.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmData.java b/engine/schema/src/com/cloud/vm/dao/UserVmData.java
new file mode 100644
index 0000000..674fc00
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/UserVmData.java
@@ -0,0 +1,723 @@
+// 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.vm.dao;
+
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.cloudstack.api.response.SecurityGroupRuleResponse;
+
+public class UserVmData {
+    private Long id;
+    private String name;
+    private String uuid;
+    private String displayName;
+    private String ipAddress;
+    private String accountName;
+    private Long domainId;
+    private String domainName;
+    private Date created;
+    private String state;
+    private Boolean haEnable;
+    private Long groupId;
+    private String group;
+    private Long zoneId;
+    private String zoneName;
+    private Long hostId;
+    private String hostName;
+    private Long templateId;
+    private String templateName;
+    private String templateDisplayText;
+    private Boolean passwordEnabled;
+    private Long isoId;
+    private String isoName;
+    private String isoDisplayText;
+    private Long serviceOfferingId;
+    private String serviceOfferingName;
+    private Boolean forVirtualNetwork;
+    private Integer cpuNumber;
+    private Integer cpuSpeed;
+    private Integer memory;
+    private String cpuUsed;
+    private Long networkKbsRead;
+    private Long networkKbsWrite;
+    private Long guestOsId;
+    private Long rootDeviceId;
+    private String rootDeviceType;
+    private Set<SecurityGroupData> securityGroupList;
+    private String password;
+    private Long jobId;
+    private Integer jobStatus;
+    private Set<NicData> nics;
+    private String hypervisor;
+    private long accountId;
+    private Long publicIpId;
+    private String publicIp;
+    private String instanceName;
+    private String sshPublicKey;
+    
+    private boolean initialized;
+    
+    public UserVmData(){
+        securityGroupList = new HashSet<SecurityGroupData>();
+        nics = new HashSet<NicData>();
+        initialized = false;
+    }
+    
+    public void setInitialized(){
+        initialized = true;
+    }
+    
+    public boolean isInitialized(){
+        return initialized;
+    }
+    
+    public NicData newNicData(){
+        return new NicData();
+    }
+    
+    public SecurityGroupData newSecurityGroupData(){
+        return new SecurityGroupData();
+    }
+        
+    public String getHypervisor() {
+        return hypervisor;
+    }
+
+    public void setHypervisor(String hypervisor) {
+        this.hypervisor = hypervisor;
+    }
+
+    public Long getObjectId() {
+        return getId();
+    }
+    
+    public Long getId() {
+        return id;
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+    
+    public String getUuid() {
+    	return this.uuid;
+    }
+    
+    public void setUuid(String uuid) {
+    	this.uuid = uuid;
+    }
+
+    public String getDisplayName() {
+        return displayName;
+    }
+
+    public void setDisplayName(String displayName) {
+        this.displayName = displayName;
+    }
+
+    public String getIpAddress() {
+        return ipAddress;
+    }
+
+    public void setIpAddress(String ipAddress) {
+        this.ipAddress = ipAddress;
+    }
+
+    public String getAccountName() {
+        return accountName;
+    }
+
+    public void setAccountName(String accountName) {
+        this.accountName = accountName;
+    }
+
+    public Long getDomainId() {
+        return domainId;
+    }
+
+    public void setDomainId(Long domainId) {
+        this.domainId = domainId;
+    }
+
+    public String getDomainName() {
+        return domainName;
+    }
+
+    public void setDomainName(String domainName) {
+        this.domainName = domainName;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    public void setCreated(Date created) {
+        this.created = created;
+    }
+
+    public String getState() {
+        return state;
+    }
+
+    public void setState(String state) {
+        this.state = state;
+    }
+
+    public Boolean getHaEnable() {
+        return haEnable;
+    }
+
+    public void setHaEnable(Boolean haEnable) {
+        this.haEnable = haEnable;
+    }
+
+    public Long getGroupId() {
+        return groupId;
+    }
+
+    public void setGroupId(Long groupId) {
+        this.groupId = groupId;
+    }
+
+    public String getGroup() {
+        return group;
+    }
+
+    public void setGroup(String group) {
+        this.group = group;
+    }
+
+    public Long getZoneId() {
+        return zoneId;
+    }
+
+    public void setZoneId(Long zoneId) {
+        this.zoneId = zoneId;
+    }
+
+    public String getZoneName() {
+        return zoneName;
+    }
+
+    public void setZoneName(String zoneName) {
+        this.zoneName = zoneName;
+    }
+
+    public Long getHostId() {
+        return hostId;
+    }
+
+    public void setHostId(Long hostId) {
+        this.hostId = hostId;
+    }
+
+    public String getHostName() {
+        return hostName;
+    }
+
+    public void setHostName(String hostName) {
+        this.hostName = hostName;
+    }
+
+    public Long getTemplateId() {
+        return templateId;
+    }
+
+    public void setTemplateId(Long templateId) {
+        this.templateId = templateId;
+    }
+
+    public String getTemplateName() {
+        return templateName;
+    }
+
+    public void setTemplateName(String templateName) {
+        this.templateName = templateName;
+    }
+
+    public String getTemplateDisplayText() {
+        return templateDisplayText;
+    }
+
+    public void setTemplateDisplayText(String templateDisplayText) {
+        this.templateDisplayText = templateDisplayText;
+    }
+
+    public Boolean getPasswordEnabled() {
+        return passwordEnabled;
+    }
+
+    public void setPasswordEnabled(Boolean passwordEnabled) {
+        this.passwordEnabled = passwordEnabled;
+    }
+
+    public Long getIsoId() {
+        return isoId;
+    }
+
+    public void setIsoId(Long isoId) {
+        this.isoId = isoId;
+    }
+
+    public String getIsoName() {
+        return isoName;
+    }
+
+    public void setIsoName(String isoName) {
+        this.isoName = isoName;
+    }
+
+    public String getIsoDisplayText() {
+        return isoDisplayText;
+    }
+
+    public void setIsoDisplayText(String isoDisplayText) {
+        this.isoDisplayText = isoDisplayText;
+    }
+
+    public Long getServiceOfferingId() {
+        return serviceOfferingId;
+    }
+
+    public void setServiceOfferingId(Long serviceOfferingId) {
+        this.serviceOfferingId = serviceOfferingId;
+    }
+
+    public String getServiceOfferingName() {
+        return serviceOfferingName;
+    }
+
+    public void setServiceOfferingName(String serviceOfferingName) {
+        this.serviceOfferingName = serviceOfferingName;
+    }
+
+    public Integer getCpuNumber() {
+        return cpuNumber;
+    }
+
+    public void setCpuNumber(Integer cpuNumber) {
+        this.cpuNumber = cpuNumber;
+    }
+
+    public Integer getCpuSpeed() {
+        return cpuSpeed;
+    }
+
+    public void setCpuSpeed(Integer cpuSpeed) {
+        this.cpuSpeed = cpuSpeed;
+    }
+
+    public Integer getMemory() {
+        return memory;
+    }
+
+    public void setMemory(Integer memory) {
+        this.memory = memory;
+    }
+
+    public String getCpuUsed() {
+        return cpuUsed;
+    }
+
+    public void setCpuUsed(String cpuUsed) {
+        this.cpuUsed = cpuUsed;
+    }
+
+    public Long getNetworkKbsRead() {
+        return networkKbsRead;
+    }
+
+    public void setNetworkKbsRead(Long networkKbsRead) {
+        this.networkKbsRead = networkKbsRead;
+    }
+
+    public Long getNetworkKbsWrite() {
+        return networkKbsWrite;
+    }
+
+    public void setNetworkKbsWrite(Long networkKbsWrite) {
+        this.networkKbsWrite = networkKbsWrite;
+    }
+
+    public Long getGuestOsId() {
+        return guestOsId;
+    }
+
+    public void setGuestOsId(Long guestOsId) {
+        this.guestOsId = guestOsId;
+    }
+
+    public Long getRootDeviceId() {
+        return rootDeviceId;
+    }
+
+    public void setRootDeviceId(Long rootDeviceId) {
+        this.rootDeviceId = rootDeviceId;
+    }
+
+    public String getRootDeviceType() {
+        return rootDeviceType;
+    }
+
+    public void setRootDeviceType(String rootDeviceType) {
+        this.rootDeviceType = rootDeviceType;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public Long getJobId() {
+        return jobId;
+    }
+
+    public void setJobId(Long jobId) {
+        this.jobId = jobId;
+    }
+
+    public Integer getJobStatus() {
+        return jobStatus;
+    }
+
+    public void setJobStatus(Integer jobStatus) {
+        this.jobStatus = jobStatus;
+    }
+
+    public Boolean getForVirtualNetwork() {
+        return forVirtualNetwork;
+    }
+
+    public void setForVirtualNetwork(Boolean forVirtualNetwork) {
+        this.forVirtualNetwork = forVirtualNetwork;
+    }
+
+    public Set<NicData> getNics() {
+        return nics;
+    }
+
+    public void addNic(NicData nics) {
+        this.nics.add(nics);
+    }
+    
+    public Set<SecurityGroupData> getSecurityGroupList() {
+        return securityGroupList;
+    }
+
+    public void addSecurityGroup(SecurityGroupData securityGroups) {
+        this.securityGroupList.add(securityGroups);
+    }
+    
+
+    public class NicData {
+        private String objectName;
+        private Long id;
+        private Long networkid;
+        private String netmask;
+        private String gateway;
+        private String ipaddress;
+        private String isolationUri;
+        private String broadcastUri;
+        private String trafficType;
+        private String type;
+        private Boolean isDefault;
+        private String macAddress;
+
+        public String getObjectName() {
+            return objectName;
+        }
+
+        public void setObjectName(String objectName) {
+            this.objectName = objectName;
+        }
+        
+        public Long getId() {
+            return id;
+        }
+
+        public void setId(Long id) {
+            this.id = id;
+        }
+
+        public Long getNetworkid() {
+            return networkid;
+        }
+
+        public void setNetworkid(Long networkid) {
+            this.networkid = networkid;
+        }
+
+        public String getNetmask() {
+            return netmask;
+        }
+
+        public void setNetmask(String netmask) {
+            this.netmask = netmask;
+        }
+
+        public String getGateway() {
+            return gateway;
+        }
+
+        public void setGateway(String gateway) {
+            this.gateway = gateway;
+        }
+
+        public String getIpaddress() {
+            return ipaddress;
+        }
+
+        public void setIpaddress(String ipaddress) {
+            this.ipaddress = ipaddress;
+        }
+
+        public String getIsolationUri() {
+            return isolationUri;
+        }
+
+        public void setIsolationUri(String isolationUri) {
+            this.isolationUri = isolationUri;
+        }
+
+        public String getBroadcastUri() {
+            return broadcastUri;
+        }
+
+        public void setBroadcastUri(String broadcastUri) {
+            this.broadcastUri = broadcastUri;
+        }
+
+        public String getTrafficType() {
+            return trafficType;
+        }
+
+        public void setTrafficType(String trafficType) {
+            this.trafficType = trafficType;
+        }
+
+        public String getType() {
+            return type;
+        }
+
+        public void setType(String type) {
+            this.type = type;
+        }
+
+        public Boolean getIsDefault() {
+            return isDefault;
+        }
+
+        public void setIsDefault(Boolean isDefault) {
+            this.isDefault = isDefault;
+        }
+
+        public String getMacAddress() {
+            return macAddress;
+        }
+
+        public void setMacAddress(String macAddress) {
+            this.macAddress = macAddress;
+        }
+
+        @Override
+        public int hashCode() {
+            final int prime = 31;
+            int result = 1;
+            result = prime * result + ((id == null) ? 0 : id.hashCode());
+            return result;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj)
+                return true;
+            if (obj == null)
+                return false;
+            if (getClass() != obj.getClass())
+                return false;
+            NicData other = (NicData) obj;
+            if (id == null) {
+                if (other.id != null)
+                    return false;
+            } else if (!id.equals(other.id))
+                return false;
+            return true;
+        }
+    }
+
+    public class SecurityGroupData {
+        private String objectName;
+        private Long id;
+        private String name;
+        private String description;
+        private String accountName;
+        private Long domainId;
+        private String domainName;
+        private Long jobId;
+        private Integer jobStatus;
+        private List<SecurityGroupRuleResponse> securityGroupRules;
+        
+        public String getObjectName() {
+            return objectName;
+        }
+
+        public void setObjectName(String objectName) {
+            this.objectName = objectName;
+        }
+
+        public Long getId() {
+            return id;
+        }
+
+        public void setId(Long id) {
+            this.id = id;
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public void setName(String name) {
+            this.name = name;
+        }
+
+        public String getDescription() {
+            return description;
+        }
+
+        public void setDescription(String description) {
+            this.description = description;
+        }
+
+        public String getAccountName() {
+            return accountName;
+        }
+
+        public void setAccountName(String accountName) {
+            this.accountName = accountName;
+        }
+
+        public Long getDomainId() {
+            return domainId;
+        }
+
+        public void setDomainId(Long domainId) {
+            this.domainId = domainId;
+        }
+
+        public String getDomainName() {
+            return domainName;
+        }
+
+        public void setDomainName(String domainName) {
+            this.domainName = domainName;
+        }
+/* FIXME : the below functions are not used, so commenting out later need to include egress list 
+        public List<SecurityGroupRuleResponse> getIngressRules() {
+            return securityGroupRules;
+        }
+
+        public void setIngressRules(List<SecurityGroupRuleResponse> securityGroupRules) {
+            this.securityGroupRules = securityGroupRules;
+        } */
+
+        @Override
+        public int hashCode() {
+            final int prime = 31;
+            int result = 1;
+            result = prime * result + ((id == null) ? 0 : id.hashCode());
+            return result;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj)
+                return true;
+            if (obj == null)
+                return false;
+            if (getClass() != obj.getClass())
+                return false;
+            SecurityGroupData other = (SecurityGroupData) obj;
+            if (id == null) {
+                if (other.id != null)
+                    return false;
+            } else if (!id.equals(other.id))
+                return false;
+            return true;
+        }
+        
+    }
+    
+    public String toString(){
+        return "id=" + id + ", name=" + name;
+    }
+
+    public long getAccountId() {
+        return accountId;
+    }
+
+    public void setAccountId(long accountId) {
+        this.accountId = accountId;
+    }
+
+    public Long getPublicIpId() {
+        return publicIpId;
+    }
+
+    public void setPublicIpId(Long publicIpId) {
+        this.publicIpId = publicIpId;
+    }
+
+    public String getPublicIp() {
+        return publicIp;
+    }
+
+    public void setPublicIp(String publicIp) {
+        this.publicIp = publicIp;
+    }
+
+    public String getInstanceName() {
+        return instanceName;
+    }
+
+    public void setInstanceName(String instanceName) {
+        this.instanceName = instanceName;
+    }
+
+    public String getSshPublicKey() {
+        return sshPublicKey;
+    }
+
+    public void setSshPublicKey(String sshPublicKey) {
+        this.sshPublicKey = sshPublicKey;
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDao.java b/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDao.java
new file mode 100644
index 0000000..bdccec9
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDao.java
@@ -0,0 +1,32 @@
+// 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.vm.dao;
+
+import java.util.Map;
+
+import com.cloud.utils.db.GenericDao;
+import com.cloud.vm.UserVmDetailVO;
+
+public interface UserVmDetailsDao extends GenericDao<UserVmDetailVO, Long> {
+    Map<String, String> findDetails(long vmId);
+    
+    void persist(long vmId, Map<String, String> details);
+    
+    UserVmDetailVO findDetail(long vmId, String name);
+    
+	void deleteDetails(long vmId);
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDaoImpl.java
new file mode 100644
index 0000000..6ec6f68
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/UserVmDetailsDaoImpl.java
@@ -0,0 +1,99 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.vm.dao;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+import com.cloud.vm.UserVmDetailVO;
+
+@Component
+@Local(value=UserVmDetailsDao.class)
+public class UserVmDetailsDaoImpl extends GenericDaoBase<UserVmDetailVO, Long> implements UserVmDetailsDao {
+    protected final SearchBuilder<UserVmDetailVO> VmSearch;
+    protected final SearchBuilder<UserVmDetailVO> DetailSearch;
+
+	public UserVmDetailsDaoImpl() {
+		VmSearch = createSearchBuilder();
+		VmSearch.and("vmId", VmSearch.entity().getVmId(), SearchCriteria.Op.EQ);
+        VmSearch.done();
+		
+		DetailSearch = createSearchBuilder();
+        DetailSearch.and("vmId", DetailSearch.entity().getVmId(), SearchCriteria.Op.EQ);
+        DetailSearch.and("name", DetailSearch.entity().getName(), SearchCriteria.Op.EQ);
+        DetailSearch.done();
+	}
+    
+	@Override
+	public void deleteDetails(long vmId) {
+        SearchCriteria<UserVmDetailVO> sc = VmSearch.create();
+        sc.setParameters("vmId", vmId);
+        
+        List<UserVmDetailVO> results = search(sc, null);
+        for (UserVmDetailVO result : results) {
+        	remove(result.getId());
+        }		
+	}
+
+	@Override
+	public UserVmDetailVO findDetail(long vmId, String name) {
+        SearchCriteria<UserVmDetailVO> sc = DetailSearch.create();
+        sc.setParameters("vmId", vmId);
+        sc.setParameters("name", name);
+		
+        return findOneBy(sc);
+	}
+
+	@Override
+	public Map<String, String> findDetails(long vmId) {
+        SearchCriteria<UserVmDetailVO> sc = VmSearch.create();
+        sc.setParameters("vmId", vmId);
+        
+        List<UserVmDetailVO> results = search(sc, null);
+        Map<String, String> details = new HashMap<String, String>(results.size());
+        for (UserVmDetailVO result : results) {
+            details.put(result.getName(), result.getValue());
+        }
+        
+        return details;
+	}
+
+	@Override
+	public void persist(long vmId, Map<String, String> details) {
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+        SearchCriteria<UserVmDetailVO> sc = VmSearch.create();
+        sc.setParameters("vmId", vmId);
+        expunge(sc);
+        
+        for (Map.Entry<String, String> detail : details.entrySet()) {
+            UserVmDetailVO vo = new UserVmDetailVO(vmId, detail.getKey(), detail.getValue());
+            persist(vo);
+        }
+        txn.commit();		
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java b/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java
new file mode 100644
index 0000000..c604027
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/VMInstanceDao.java
@@ -0,0 +1,119 @@
+// 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.vm.dao;
+
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import com.cloud.utils.Pair;
+import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachine.State;
+
+
+/*
+ * Data Access Object for vm_instance table
+ */
+public interface VMInstanceDao extends GenericDao<VMInstanceVO, Long>, StateDao<State, VirtualMachine.Event, VirtualMachine> {
+    /**
+     * What are the vms running on this host?
+     * @param hostId host.
+     * @return list of VMInstanceVO running on that host.
+     */
+	List<VMInstanceVO> listByHostId(long hostId);
+	
+	/**
+	 * List VMs by zone ID
+	 * @param zoneId
+	 * @return list of VMInstanceVO in the specified zone
+	 */
+	List<VMInstanceVO> listByZoneId(long zoneId);
+	
+	/**
+     * List VMs by pod ID
+     * @param podId
+     * @return list of VMInstanceVO in the specified pod
+     */
+    List<VMInstanceVO> listByPodId(long podId);
+
+	/**
+	 * Lists non-expunged VMs by zone ID and templateId
+	 * @param zoneId
+	 * @return list of VMInstanceVO in the specified zone, deployed from the specified template, that are not expunged
+	 */
+	public List<VMInstanceVO> listNonExpungedByZoneAndTemplate(long zoneId, long templateId);
+	
+    /**
+     * Find vm instance with names like.
+     * 
+     * @param name name that fits SQL like.
+     * @return list of VMInstanceVO
+     */
+    List<VMInstanceVO> findVMInstancesLike(String name);
+    
+    List<VMInstanceVO> findVMInTransition(Date time, State... states);
+
+    List<VMInstanceVO> listByTypes(VirtualMachine.Type... types);
+    
+    VMInstanceVO findByIdTypes(long id, VirtualMachine.Type... types);
+    
+    VMInstanceVO findVMByInstanceName(String name);
+
+    void updateProxyId(long id, Long proxyId, Date time);
+
+    List<VMInstanceVO> listByHostIdTypes(long hostid, VirtualMachine.Type... types);
+    
+    List<VMInstanceVO> listUpByHostIdTypes(long hostid, VirtualMachine.Type... types);
+    List<VMInstanceVO> listByZoneIdAndType(long zoneId, VirtualMachine.Type type);
+	List<VMInstanceVO> listUpByHostId(Long hostId);
+	List<VMInstanceVO> listByLastHostId(Long hostId);
+	
+    List<VMInstanceVO> listByTypeAndState(VirtualMachine.Type type, State state);
+
+    List<VMInstanceVO> listByAccountId(long accountId);
+    public Long countAllocatedVirtualRoutersForAccount(long accountId);
+
+    List<VMInstanceVO> listByClusterId(long clusterId);  // this does not pull up VMs which are starting
+    List<VMInstanceVO> listLHByClusterId(long clusterId);  // get all the VMs even starting one on this cluster
+    
+    List<VMInstanceVO> listVmsMigratingFromHost(Long hostId);
+    
+    public Long countRunningByHostId(long hostId);
+
+    Pair<List<Long>, Map<Long, Double>> listClusterIdsInZoneByVmCount(long zoneId, long accountId);
+
+    Pair<List<Long>, Map<Long, Double>> listClusterIdsInPodByVmCount(long podId, long accountId);
+
+    Pair<List<Long>, Map<Long, Double>> listPodIdsInZoneByVmCount(long dataCenterId, long accountId);
+
+    List<Long> listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId);
+
+    Long countRunningByAccount(long accountId);
+    
+    List<VMInstanceVO> listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types);
+
+    /**
+     * @param networkId
+     * @param types
+     * @return
+     */
+    List<String> listDistinctHostNames(long networkId, VirtualMachine.Type... types);
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java b/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java
new file mode 100644
index 0000000..7198b7c
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/dao/VMInstanceDaoImpl.java
@@ -0,0 +1,628 @@
+// 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.vm.dao;
+
+
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+import javax.ejb.Local;
+import javax.inject.Inject;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.host.HostVO;
+import com.cloud.host.dao.HostDao;
+import com.cloud.server.ResourceTag.TaggedResourceType;
+import com.cloud.tags.dao.ResourceTagDao;
+import com.cloud.utils.Pair;
+import com.cloud.utils.db.Attribute;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.GenericSearchBuilder;
+import com.cloud.utils.db.JoinBuilder;
+import com.cloud.utils.db.JoinBuilder.JoinType;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.SearchCriteria.Func;
+import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.Transaction;
+import com.cloud.utils.db.UpdateBuilder;
+import com.cloud.utils.exception.CloudRuntimeException;
+import com.cloud.vm.NicVO;
+import com.cloud.vm.VMInstanceVO;
+import com.cloud.vm.VirtualMachine;
+import com.cloud.vm.VirtualMachine.Event;
+import com.cloud.vm.VirtualMachine.State;
+import com.cloud.vm.VirtualMachine.Type;
+
+@Component
+@Local(value = { VMInstanceDao.class })
+public class VMInstanceDaoImpl extends GenericDaoBase<VMInstanceVO, Long> implements VMInstanceDao {
+
+    public static final Logger s_logger = Logger.getLogger(VMInstanceDaoImpl.class);
+
+    protected SearchBuilder<VMInstanceVO> VMClusterSearch;
+    protected SearchBuilder<VMInstanceVO> LHVMClusterSearch;
+    protected SearchBuilder<VMInstanceVO> IdStatesSearch;
+    protected SearchBuilder<VMInstanceVO> AllFieldsSearch;
+    protected SearchBuilder<VMInstanceVO> ZoneTemplateNonExpungedSearch;
+    protected SearchBuilder<VMInstanceVO> NameLikeSearch;
+    protected SearchBuilder<VMInstanceVO> StateChangeSearch;
+    protected SearchBuilder<VMInstanceVO> TransitionSearch;
+    protected SearchBuilder<VMInstanceVO> TypesSearch;
+    protected SearchBuilder<VMInstanceVO> IdTypesSearch;
+    protected SearchBuilder<VMInstanceVO> HostIdTypesSearch;
+    protected SearchBuilder<VMInstanceVO> HostIdUpTypesSearch;
+    protected SearchBuilder<VMInstanceVO> HostUpSearch;
+    protected SearchBuilder<VMInstanceVO> InstanceNameSearch;
+    protected GenericSearchBuilder<VMInstanceVO, Long> CountVirtualRoutersByAccount;
+    protected GenericSearchBuilder<VMInstanceVO, Long> CountRunningByHost;
+    protected GenericSearchBuilder<VMInstanceVO, Long> CountRunningByAccount;
+    protected SearchBuilder<VMInstanceVO> NetworkTypeSearch;
+    protected GenericSearchBuilder<VMInstanceVO, String> DistinctHostNameSearch;
+    
+    @Inject ResourceTagDao _tagsDao;
+    @Inject NicDao _nicDao;
+    
+    protected Attribute _updateTimeAttr;
+    
+    private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1 = 
+            "SELECT host.cluster_id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id WHERE ";
+    private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2 =
+            " AND host.type = 'Routing' GROUP BY host.cluster_id ORDER BY 2 ASC ";
+    
+    private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host_pod_ref` pod LEFT JOIN `cloud`.`vm_instance` vm ON pod.id = vm.pod_id WHERE pod.data_center_id = ? " +
+                                                                       " GROUP BY pod.id ORDER BY 2 ASC ";
+    
+    private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT =
+            "SELECT host.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id WHERE host.data_center_id = ? " +
+    		                                                            " AND host.pod_id = ? AND host.cluster_id = ? AND host.type = 'Routing' " +
+    		                                                            " GROUP BY host.id ORDER BY 2 ASC ";
+
+    @Inject protected HostDao _hostDao;
+    
+    public VMInstanceDaoImpl() {
+    }
+    
+    @PostConstruct
+    protected void init() {
+
+        IdStatesSearch = createSearchBuilder();
+        IdStatesSearch.and("id", IdStatesSearch.entity().getId(), Op.EQ);
+        IdStatesSearch.and("states", IdStatesSearch.entity().getState(), Op.IN);
+        IdStatesSearch.done();
+               
+        VMClusterSearch = createSearchBuilder();
+        SearchBuilder<HostVO> hostSearch = _hostDao.createSearchBuilder();
+        VMClusterSearch.join("hostSearch", hostSearch, hostSearch.entity().getId(), VMClusterSearch.entity().getHostId(), JoinType.INNER);
+        hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
+        VMClusterSearch.done();
+
+        
+        LHVMClusterSearch = createSearchBuilder();
+        SearchBuilder<HostVO> hostSearch1 = _hostDao.createSearchBuilder();
+        LHVMClusterSearch.join("hostSearch1", hostSearch1, hostSearch1.entity().getId(), LHVMClusterSearch.entity().getLastHostId(), JoinType.INNER);
+        LHVMClusterSearch.and("hostid", LHVMClusterSearch.entity().getHostId(), Op.NULL);
+        hostSearch1.and("clusterId", hostSearch1.entity().getClusterId(), SearchCriteria.Op.EQ);
+        LHVMClusterSearch.done();
+
+        
+        AllFieldsSearch = createSearchBuilder();
+        AllFieldsSearch.and("host", AllFieldsSearch.entity().getHostId(), Op.EQ);
+        AllFieldsSearch.and("lastHost", AllFieldsSearch.entity().getLastHostId(), Op.EQ);
+        AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ);
+        AllFieldsSearch.and("zone", AllFieldsSearch.entity().getDataCenterId(), Op.EQ);
+        AllFieldsSearch.and("type", AllFieldsSearch.entity().getType(), Op.EQ);
+        AllFieldsSearch.and("account", AllFieldsSearch.entity().getAccountId(), Op.EQ);
+        AllFieldsSearch.done();
+
+        ZoneTemplateNonExpungedSearch = createSearchBuilder();
+        ZoneTemplateNonExpungedSearch.and("zone", ZoneTemplateNonExpungedSearch.entity().getDataCenterId(), Op.EQ);
+        ZoneTemplateNonExpungedSearch.and("template", ZoneTemplateNonExpungedSearch.entity().getTemplateId(), Op.EQ);
+        ZoneTemplateNonExpungedSearch.and("state", ZoneTemplateNonExpungedSearch.entity().getState(), Op.NEQ);
+        ZoneTemplateNonExpungedSearch.done();
+
+        NameLikeSearch = createSearchBuilder();
+        NameLikeSearch.and("name", NameLikeSearch.entity().getHostName(), Op.LIKE);
+        NameLikeSearch.done();
+
+        StateChangeSearch = createSearchBuilder();
+        StateChangeSearch.and("id", StateChangeSearch.entity().getId(), Op.EQ);
+        StateChangeSearch.and("states", StateChangeSearch.entity().getState(), Op.EQ);
+        StateChangeSearch.and("host", StateChangeSearch.entity().getHostId(), Op.EQ);
+        StateChangeSearch.and("update", StateChangeSearch.entity().getUpdated(), Op.EQ);
+        StateChangeSearch.done();
+
+        TransitionSearch = createSearchBuilder();
+        TransitionSearch.and("updateTime", TransitionSearch.entity().getUpdateTime(), Op.LT);
+        TransitionSearch.and("states", TransitionSearch.entity().getState(), Op.IN);
+        TransitionSearch.done();
+
+        TypesSearch = createSearchBuilder();
+        TypesSearch.and("types", TypesSearch.entity().getType(), Op.IN);
+        TypesSearch.done();
+
+        IdTypesSearch = createSearchBuilder();
+        IdTypesSearch.and("id", IdTypesSearch.entity().getId(), Op.EQ);
+        IdTypesSearch.and("types", IdTypesSearch.entity().getType(), Op.IN);
+        IdTypesSearch.done();
+        
+        HostIdTypesSearch = createSearchBuilder();
+        HostIdTypesSearch.and("hostid", HostIdTypesSearch.entity().getHostId(), Op.EQ);
+        HostIdTypesSearch.and("types", HostIdTypesSearch.entity().getType(), Op.IN);
+        HostIdTypesSearch.done();
+        
+        HostIdUpTypesSearch = createSearchBuilder();
+        HostIdUpTypesSearch.and("hostid", HostIdUpTypesSearch.entity().getHostId(), Op.EQ);
+        HostIdUpTypesSearch.and("types", HostIdUpTypesSearch.entity().getType(), Op.IN);
+        HostIdUpTypesSearch.and("states", HostIdUpTypesSearch.entity().getState(), Op.NIN);
+        HostIdUpTypesSearch.done();
+        
+        HostUpSearch = createSearchBuilder();
+        HostUpSearch.and("host", HostUpSearch.entity().getHostId(), Op.EQ);
+        HostUpSearch.and("states", HostUpSearch.entity().getState(), Op.IN);
+        HostUpSearch.done();
+        
+        InstanceNameSearch = createSearchBuilder();
+        InstanceNameSearch.and("instanceName", InstanceNameSearch.entity().getInstanceName(), Op.EQ);
+        InstanceNameSearch.done();
+
+        CountVirtualRoutersByAccount = createSearchBuilder(Long.class);
+        CountVirtualRoutersByAccount.select(null, Func.COUNT, null);
+        CountVirtualRoutersByAccount.and("account", CountVirtualRoutersByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
+        CountVirtualRoutersByAccount.and("type", CountVirtualRoutersByAccount.entity().getType(), SearchCriteria.Op.EQ);
+        CountVirtualRoutersByAccount.and("state", CountVirtualRoutersByAccount.entity().getState(), SearchCriteria.Op.NIN);        
+        CountVirtualRoutersByAccount.done();
+        
+        CountRunningByHost = createSearchBuilder(Long.class);
+        CountRunningByHost.select(null, Func.COUNT, null);
+        CountRunningByHost.and("host", CountRunningByHost.entity().getHostId(), SearchCriteria.Op.EQ);
+        CountRunningByHost.and("state", CountRunningByHost.entity().getState(), SearchCriteria.Op.EQ);
+        CountRunningByHost.done();        
+
+        CountRunningByAccount = createSearchBuilder(Long.class);
+        CountRunningByAccount.select(null, Func.COUNT, null);
+        CountRunningByAccount.and("account", CountRunningByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
+        CountRunningByAccount.and("state", CountRunningByAccount.entity().getState(), SearchCriteria.Op.EQ);
+        CountRunningByAccount.done();        
+        
+        _updateTimeAttr = _allAttributes.get("updateTime");
+        assert _updateTimeAttr != null : "Couldn't get this updateTime attribute";
+    }
+
+    @Override
+    public List<VMInstanceVO> listByAccountId(long accountId) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("account", accountId);
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> findVMInstancesLike(String name) {
+        SearchCriteria<VMInstanceVO> sc = NameLikeSearch.create();
+        sc.setParameters("name", "%" + name + "%");
+        return listBy(sc);
+    }
+
+    @Override
+    public List<VMInstanceVO> listByHostId(long hostid) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("host", hostid);
+
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listByZoneId(long zoneId) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("zone", zoneId);
+
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listByPodId(long podId) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("pod", podId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<VMInstanceVO> listByClusterId(long clusterId) {
+        SearchCriteria<VMInstanceVO> sc = VMClusterSearch.create();
+        sc.setJoinParameters("hostSearch", "clusterId", clusterId);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<VMInstanceVO> listLHByClusterId(long clusterId) {
+        SearchCriteria<VMInstanceVO> sc = LHVMClusterSearch.create();
+        sc.setJoinParameters("hostSearch1", "clusterId", clusterId);
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listByZoneIdAndType(long zoneId, VirtualMachine.Type type) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("zone", zoneId);
+        sc.setParameters("type", type.toString());
+        return listBy(sc);
+    }
+    
+    
+    @Override
+    public List<VMInstanceVO> listNonExpungedByZoneAndTemplate(long zoneId, long templateId) {
+        SearchCriteria<VMInstanceVO> sc = ZoneTemplateNonExpungedSearch.create();
+
+        sc.setParameters("zone", zoneId);
+        sc.setParameters("template", templateId);
+        sc.setParameters("state", State.Expunging);
+
+        return listBy(sc);
+    }
+
+    @Override
+    public List<VMInstanceVO> findVMInTransition(Date time, State... states) {
+        SearchCriteria<VMInstanceVO> sc = TransitionSearch.create();
+
+        sc.setParameters("states", (Object[]) states);
+        sc.setParameters("updateTime", time);
+
+        return search(sc, null);
+    }
+
+    @Override
+    public List<VMInstanceVO> listByHostIdTypes(long hostid, Type... types) {
+        SearchCriteria<VMInstanceVO> sc = HostIdTypesSearch.create();
+        sc.setParameters("hostid", hostid);
+        sc.setParameters("types", (Object[]) types);
+        return listBy(sc);
+    }
+
+    @Override
+    public List<VMInstanceVO> listUpByHostIdTypes(long hostid, Type... types) {
+        SearchCriteria<VMInstanceVO> sc = HostIdUpTypesSearch.create();
+        sc.setParameters("hostid", hostid);
+        sc.setParameters("types", (Object[]) types);
+        sc.setParameters("states", new Object[] {State.Destroyed, State.Stopped, State.Expunging});
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listUpByHostId(Long hostId) {
+        SearchCriteria<VMInstanceVO> sc = HostUpSearch.create();
+        sc.setParameters("host", hostId);
+        sc.setParameters("states", new Object[] {State.Starting, State.Running});
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listByTypes(Type... types) {
+        SearchCriteria<VMInstanceVO> sc = TypesSearch.create();
+        sc.setParameters("types", (Object[]) types);
+        return listBy(sc);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listByTypeAndState(VirtualMachine.Type type, State state) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("type", type);
+        sc.setParameters("state", state);
+        return listBy(sc);
+    }
+
+    @Override
+    public VMInstanceVO findByIdTypes(long id, Type... types) {
+        SearchCriteria<VMInstanceVO> sc = IdTypesSearch.create();
+        sc.setParameters("id", id);
+        sc.setParameters("types", (Object[]) types);
+        return findOneIncludingRemovedBy(sc);
+    }
+
+    @Override
+    public VMInstanceVO findVMByInstanceName(String name) {
+        SearchCriteria<VMInstanceVO> sc = InstanceNameSearch.create();
+        sc.setParameters("instanceName", name);
+        return findOneBy(sc);
+    }
+   
+    @Override
+    public void updateProxyId(long id, Long proxyId, Date time) {
+        VMInstanceVO vo = createForUpdate();
+        vo.setProxyId(proxyId);
+        vo.setProxyAssignTime(time);
+        update(id, vo);
+    }
+
+    @Override
+    public boolean updateState(State oldState, Event event,	State newState, VirtualMachine vm, Object opaque) {
+    	if (newState == null) {
+    		if (s_logger.isDebugEnabled()) {
+    			s_logger.debug("There's no way to transition from old state: " + oldState.toString() + " event: " + event.toString());
+    		}
+    		return false;
+    	}
+
+    	@SuppressWarnings("unchecked")
+		Pair<Long, Long> hosts = (Pair<Long,Long>)opaque;
+		Long newHostId = hosts.second();
+    	
+    	VMInstanceVO vmi = (VMInstanceVO)vm;
+    	Long oldHostId = vmi.getHostId();
+    	Long oldUpdated = vmi.getUpdated();
+    	Date oldUpdateDate = vmi.getUpdateTime();
+    	
+    	SearchCriteria<VMInstanceVO> sc = StateChangeSearch.create();
+    	sc.setParameters("id", vmi.getId());
+    	sc.setParameters("states", oldState);
+    	sc.setParameters("host", vmi.getHostId());
+    	sc.setParameters("update", vmi.getUpdated());
+
+    	vmi.incrUpdated();
+    	UpdateBuilder ub = getUpdateBuilder(vmi);
+    	
+    	ub.set(vmi, "state", newState);
+    	ub.set(vmi, "hostId", newHostId);
+    	ub.set(vmi, "podIdToDeployIn", vmi.getPodIdToDeployIn());
+    	ub.set(vmi, _updateTimeAttr, new Date());
+
+    	int result = update(vmi, sc);
+    	if (result == 0 && s_logger.isDebugEnabled()) {
+
+    		VMInstanceVO vo = findByIdIncludingRemoved(vm.getId());
+    		
+    		if (vo != null) {
+        		StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
+        		str.append(": DB Data={Host=").append(vo.getHostId()).append("; State=").append(vo.getState().toString()).append("; updated=").append(vo.getUpdated()).append("; time=").append(vo.getUpdateTime());
+        		str.append("} New Data: {Host=").append(vm.getHostId()).append("; State=").append(vm.getState().toString()).append("; updated=").append(vmi.getUpdated()).append("; time=").append(vo.getUpdateTime());
+        		str.append("} Stale Data: {Host=").append(oldHostId).append("; State=").append(oldState).append("; updated=").append(oldUpdated).append("; time=").append(oldUpdateDate).append("}");
+        		s_logger.debug(str.toString());
+
+    		} else {
+    		    s_logger.debug("Unable to update the vm id=" + vm.getId() + "; the vm either doesn't exist or already removed");
+    		}
+    	}
+    	return result > 0;
+    }
+    
+    @Override
+	public List<VMInstanceVO> listByLastHostId(Long hostId) {
+		SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+		sc.setParameters("lastHost", hostId);
+		sc.setParameters("state", State.Stopped);
+		return listBy(sc);
+	}
+    
+    @Override
+    public Long countAllocatedVirtualRoutersForAccount(long accountId) {
+    	SearchCriteria<Long> sc = CountVirtualRoutersByAccount.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("type", VirtualMachine.Type.DomainRouter);
+		sc.setParameters("state", new Object[] {State.Destroyed, State.Error, State.Expunging});
+        return customSearch(sc, null).get(0);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listVmsMigratingFromHost(Long hostId) {
+        SearchCriteria<VMInstanceVO> sc = AllFieldsSearch.create();
+        sc.setParameters("lastHost", hostId);
+        sc.setParameters("state", State.Migrating);
+        return listBy(sc);
+    }
+    
+    @Override
+    public Long countRunningByHostId(long hostId){
+        SearchCriteria<Long> sc = CountRunningByHost.create();
+        sc.setParameters("host", hostId);
+        sc.setParameters("state", State.Running);
+        return customSearch(sc, null).get(0);
+    }
+
+    @Override
+    public Pair<List<Long>, Map<Long, Double>> listClusterIdsInZoneByVmCount(long zoneId, long accountId) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        List<Long> result = new ArrayList<Long>();
+        Map<Long, Double> clusterVmCountMap = new HashMap<Long, Double>();
+
+        StringBuilder sql = new StringBuilder(ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1);
+        sql.append("host.data_center_id = ?");
+        sql.append(ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2);
+        try {
+            pstmt = txn.prepareAutoCloseStatement(sql.toString());
+            pstmt.setLong(1, accountId);
+            pstmt.setLong(2, zoneId);
+            
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                Long clusterId = rs.getLong(1);
+                result.add(clusterId);
+                clusterVmCountMap.put(clusterId, rs.getDouble(2));
+            }
+            return new Pair<List<Long>, Map<Long, Double>>(result, clusterVmCountMap);
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + sql, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + sql, e);
+        }
+    }
+
+    @Override
+    public Pair<List<Long>, Map<Long, Double>> listClusterIdsInPodByVmCount(long podId, long accountId) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        List<Long> result = new ArrayList<Long>();
+        Map<Long, Double> clusterVmCountMap = new HashMap<Long, Double>();
+
+        StringBuilder sql = new StringBuilder(ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1);
+        sql.append("host.pod_id = ?");
+        sql.append(ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2);
+        try {
+            pstmt = txn.prepareAutoCloseStatement(sql.toString());
+            pstmt.setLong(1, accountId);
+            pstmt.setLong(2, podId);
+            
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                Long clusterId = rs.getLong(1);
+                result.add(clusterId);                
+                clusterVmCountMap.put(clusterId, rs.getDouble(2));
+            }
+            return new Pair<List<Long>, Map<Long, Double>>(result, clusterVmCountMap);
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + sql, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + sql, e);
+        }
+
+    }
+
+    @Override
+    public Pair<List<Long>, Map<Long, Double>> listPodIdsInZoneByVmCount(long dataCenterId, long accountId) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        List<Long> result = new ArrayList<Long>();
+        Map<Long, Double> podVmCountMap = new HashMap<Long, Double>();
+        try {
+            String sql = ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setLong(1, accountId);
+            pstmt.setLong(2, dataCenterId);
+            
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                Long podId = rs.getLong(1);
+                result.add(podId);                
+                podVmCountMap.put(podId, rs.getDouble(2));
+            }
+            return new Pair<List<Long>, Map<Long, Double>>(result, podVmCountMap);
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT, e);
+        }        
+    }
+
+    @Override
+    public List<Long> listHostIdsByVmCount(long dcId, Long podId, Long clusterId, long accountId) {
+        Transaction txn = Transaction.currentTxn();
+        PreparedStatement pstmt = null;
+        List<Long> result = new ArrayList<Long>();
+        try {
+            String sql = ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT;
+            pstmt = txn.prepareAutoCloseStatement(sql);
+            pstmt.setLong(1, accountId);
+            pstmt.setLong(2, dcId);
+            pstmt.setLong(3, podId);
+            pstmt.setLong(4, clusterId);
+            
+            ResultSet rs = pstmt.executeQuery();
+            while (rs.next()) {
+                result.add(rs.getLong(1));
+            }
+            return result;
+        } catch (SQLException e) {
+            throw new CloudRuntimeException("DB Exception on: " + ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT, e);
+        } catch (Throwable e) {
+            throw new CloudRuntimeException("Caught: " + ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT, e);
+        }   
+    }
+    
+    @Override
+    public Long countRunningByAccount(long accountId){
+        SearchCriteria<Long> sc = CountRunningByAccount.create();
+        sc.setParameters("account", accountId);
+        sc.setParameters("state", State.Running);
+        return customSearch(sc, null).get(0);
+    }
+    
+    @Override
+    public List<VMInstanceVO> listNonRemovedVmsByTypeAndNetwork(long networkId, VirtualMachine.Type... types) {
+        if (NetworkTypeSearch == null) {
+            
+            SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
+            nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
+
+            NetworkTypeSearch = createSearchBuilder();
+            NetworkTypeSearch.and("types", NetworkTypeSearch.entity().getType(), SearchCriteria.Op.IN);
+            NetworkTypeSearch.and("removed", NetworkTypeSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
+            NetworkTypeSearch.join("nicSearch", nicSearch, NetworkTypeSearch.entity().getId(), 
+                    nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
+            NetworkTypeSearch.done();
+        }
+
+        SearchCriteria<VMInstanceVO> sc = NetworkTypeSearch.create();
+        if (types != null && types.length != 0) {
+            sc.setParameters("types", (Object[]) types);
+        }        
+        sc.setJoinParameters("nicSearch", "networkId", networkId);
+
+        return listBy(sc);
+    }
+    
+    
+    
+    @Override
+    public List<String> listDistinctHostNames(long networkId, VirtualMachine.Type... types) {
+        if (DistinctHostNameSearch == null) {
+            
+            SearchBuilder<NicVO> nicSearch = _nicDao.createSearchBuilder();
+            nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ);
+
+            DistinctHostNameSearch = createSearchBuilder(String.class);
+            DistinctHostNameSearch.selectField(DistinctHostNameSearch.entity().getHostName());
+            
+            DistinctHostNameSearch.and("types", DistinctHostNameSearch.entity().getType(), SearchCriteria.Op.IN);
+            DistinctHostNameSearch.and("removed", DistinctHostNameSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
+            DistinctHostNameSearch.join("nicSearch", nicSearch, DistinctHostNameSearch.entity().getId(), 
+                    nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER);
+            DistinctHostNameSearch.done();
+        }
+
+        SearchCriteria<String> sc = DistinctHostNameSearch.create();
+        if (types != null && types.length != 0) {
+            sc.setParameters("types", (Object[]) types);
+        }        
+        sc.setJoinParameters("nicSearch", "networkId", networkId);
+
+        return  customSearch(sc, null);
+    }
+    
+    @Override
+    @DB
+    public boolean remove(Long id) {
+        Transaction txn = Transaction.currentTxn();
+        txn.start();
+        VMInstanceVO vm = findById(id);
+        if (vm != null && vm.getType() == Type.User) {
+            _tagsDao.removeByIdAndType(id, TaggedResourceType.UserVm);
+        }
+        boolean result = super.remove(id);
+        txn.commit();
+        return result;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/572e71e5/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java
----------------------------------------------------------------------
diff --git a/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java
new file mode 100644
index 0000000..7532edf
--- /dev/null
+++ b/engine/schema/src/com/cloud/vm/snapshot/dao/VMSnapshotDao.java
@@ -0,0 +1,39 @@
+// 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.vm.snapshot.dao;
+
+import java.util.List;
+
+import com.cloud.utils.db.GenericDao;
+import com.cloud.utils.fsm.StateDao;
+import com.cloud.vm.snapshot.VMSnapshot;
+import com.cloud.vm.snapshot.VMSnapshotVO;
+
+public interface VMSnapshotDao extends GenericDao<VMSnapshotVO, Long>, StateDao<VMSnapshot.State, VMSnapshot.Event, VMSnapshot> {
+
+    List<VMSnapshotVO> findByVm(Long vmId);
+
+    List<VMSnapshotVO> listExpungingSnapshot();
+
+    List<VMSnapshotVO> listByInstanceId(Long vmId, VMSnapshot.State... status);
+
+	VMSnapshotVO findCurrentSnapshotByVmId(Long vmId);
+	
+	List<VMSnapshotVO> listByParent(Long vmSnapshotId);
+	
+	VMSnapshotVO findByName(Long vm_id, String name);
+}


Mime
View raw message