From af8832f6bdab38101ffb14149e6da8a0f9c969ca Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Fri, 27 Sep 2013 14:09:53 -0700 Subject: [PATCH 01/27] Unified both the SearchBuilder and SearchCriteriaService --- .../cloud/agent/manager/AgentManagerImpl.java | 6 +- .../manager/ClusteredAgentManagerImpl.java | 6 +- .../ClusterBasedAgentLoadBalancerPlanner.java | 4 +- .../dc/dao/StorageNetworkIpRangeDaoImpl.java | 8 +- .../com/cloud/user/AccountDetailsDaoImpl.java | 6 +- .../datastore/db/PrimaryDataStoreDaoImpl.java | 6 +- .../manager/StorageCacheManagerImpl.java | 4 +- .../StorageCacheReplacementAlgorithmLRU.java | 8 +- .../storage/snapshot/SnapshotObject.java | 4 +- .../endpoint/DefaultEndPointSelector.java | 6 +- .../db/TemplatePrimaryDataStoreDaoImpl.java | 6 +- .../db/src/com/cloud/utils/db/GenericDao.java | 4 - .../com/cloud/utils/db/GenericDaoBase.java | 41 ++-- .../cloud/utils/db/GenericSearchBuilder.java | 173 +---------------- .../src/com/cloud/utils/db/SearchBuilder.java | 5 +- .../com/cloud/utils/db/SearchCriteria.java | 4 +- .../com/cloud/utils/db/SearchCriteria2.java | 175 ++++++------------ .../cloud/utils/db/SearchCriteriaService.java | 29 --- .../BareMetalPingServiceImpl.java | 4 +- .../networkservice/BaremetalDhcpElement.java | 4 +- .../BaremetalDhcpManagerImpl.java | 4 +- .../BaremetalKickStartServiceImpl.java | 4 +- .../networkservice/BaremetalPxeElement.java | 4 +- .../BaremetalPxeManagerImpl.java | 4 +- .../com/cloud/ucs/manager/UcsManagerImpl.java | 14 +- .../xen/discoverer/XcpServerDiscoverer.java | 4 +- .../element/InternalLoadBalancerElement.java | 4 +- .../consoleproxy/ConsoleProxyManagerImpl.java | 4 +- .../cloud/ha/AbstractInvestigatorImpl.java | 4 +- .../network/StorageNetworkManagerImpl.java | 4 +- .../network/element/VirtualRouterElement.java | 4 +- .../cloud/resource/ResourceManagerImpl.java | 26 +-- .../com/cloud/storage/OCFS2ManagerImpl.java | 4 +- .../SecondaryStorageManagerImpl.java | 6 +- 34 files changed, 156 insertions(+), 437 deletions(-) delete mode 100755 framework/db/src/com/cloud/utils/db/SearchCriteriaService.java diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 6c88f6e1279..0b04d74e300 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -99,7 +99,7 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; @@ -1448,7 +1448,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl try { List behindAgents = findAgentsBehindOnPing(); for (Long agentId : behindAgents) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getId(), Op.EQ, agentId); HostVO h = sc.find(); if (h != null) { @@ -1470,7 +1470,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl } } - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getResourceState(), Op.IN, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); List hosts = sc.list(); diff --git a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index 61066ec7dbc..3d644734b73 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -89,7 +89,7 @@ import com.cloud.utils.Profiler; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; @@ -783,7 +783,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public void startRebalanceAgents() { s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); List allManagedAgents = sc.list(); @@ -1369,7 +1369,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust profilerAgentLB.start(); //initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold if (EnableLB.value() && !_agentLbHappened) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); List allManagedRoutingAgents = sc.list(); diff --git a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java index 535ba07cd0b..47e2b97c65a 100755 --- a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java +++ b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java @@ -38,7 +38,7 @@ import com.cloud.host.dao.HostDao; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; @Component @Local(value=AgentLoadBalancerPlanner.class) @@ -49,7 +49,7 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements @Override public List getHostsToRebalance(long msId, int avLoad) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId); List allHosts = sc.list(); diff --git a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java index d732e6fcb7a..db85c06962b 100755 --- a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java @@ -32,7 +32,7 @@ import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @@ -50,21 +50,21 @@ public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase listByPodId(long podId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); return sc.list(); } @Override public List listByRangeId(long rangeId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getId(), Op.EQ, rangeId); return sc.list(); } @Override public List listByDataCenterId(long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); return sc.list(); } diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java index 36fd5b4e605..6a0b2487cd7 100755 --- a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java @@ -31,7 +31,7 @@ import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.Transaction; @Local(value = {AccountDetailsDao.class}) @@ -46,7 +46,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public Map findDetails(long accountId) { - SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); + SearchCriteria2 sc = SearchCriteria2.create(AccountDetailVO.class); sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); List results = sc.list(); Map details = new HashMap(results.size()); @@ -72,7 +72,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public AccountDetailVO findDetail(long accountId, String name) { - SearchCriteriaService sc = SearchCriteria2.create(AccountDetailVO.class); + SearchCriteria2 sc = SearchCriteria2.create(AccountDetailVO.class); sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); sc.addAnd(sc.getEntity().getName(), Op.EQ, name); return sc.find(); diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index b39f8444c35..074a156a495 100644 --- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -40,7 +40,7 @@ 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.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @@ -316,7 +316,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase public List findZoneWideStoragePoolsByTags(long dcId, String[] tags) { List storagePools = null; if (tags == null || tags.length == 0) { - SearchCriteriaService sc = SearchCriteria2.create(StoragePoolVO.class); + SearchCriteria2 sc = SearchCriteria2.create(StoragePoolVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); @@ -421,7 +421,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase @Override public List findZoneWideStoragePoolsByHypervisor(long dataCenterId, HypervisorType hypervisorType) { - SearchCriteriaService sc = SearchCriteria2.create(StoragePoolVO.class); + SearchCriteria2 sc = SearchCriteria2.create(StoragePoolVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java index 083b7c1bf15..f14985d08d6 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java @@ -26,7 +26,7 @@ import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.engine.subsystem.api.storage.*; @@ -79,7 +79,7 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { } protected List getCacheStores() { - SearchCriteriaService sc = SearchCriteria2.create(ImageStoreVO.class); + SearchCriteria2 sc = SearchCriteria2.create(ImageStoreVO.class); sc.addAnd(sc.getEntity().getRole(), SearchCriteria.Op.EQ, DataStoreRole.ImageCache); List imageStoreVOs = sc.list(); List stores = new ArrayList(); diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java index 424a8fb73e7..9cd5995e346 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java @@ -22,7 +22,7 @@ import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import org.apache.cloudstack.engine.subsystem.api.storage.*; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; @@ -72,7 +72,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem cal.add(Calendar.DAY_OF_MONTH, -unusedTimeInterval.intValue()); Date bef = cal.getTime(); - SearchCriteriaService sc = SearchCriteria2.create(TemplateDataStoreVO.class); + SearchCriteria2 sc = SearchCriteria2.create(TemplateDataStoreVO.class); sc.addAnd(sc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); sc.addAnd(sc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); sc.addAnd(sc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); @@ -83,7 +83,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem return templateFactory.getTemplate(template.getTemplateId(), store); } - SearchCriteriaService volSc = SearchCriteria2.create(VolumeDataStoreVO.class); + SearchCriteria2 volSc = SearchCriteria2.create(VolumeDataStoreVO.class); volSc.addAnd(volSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); volSc.addAnd(volSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); volSc.addAnd(volSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); @@ -93,7 +93,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem return volumeFactory.getVolume(volume.getVolumeId(), store); } - SearchCriteriaService snapshotSc = SearchCriteria2.create(SnapshotDataStoreVO.class); + SearchCriteria2 snapshotSc = SearchCriteria2.create(SnapshotDataStoreVO.class); snapshotSc.addAnd(snapshotSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); snapshotSc.addAnd(snapshotSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); snapshotSc.addAnd(snapshotSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java index 7d823a3b407..730cec41489 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java @@ -44,7 +44,7 @@ import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -104,7 +104,7 @@ public class SnapshotObject implements SnapshotInfo { @Override public SnapshotInfo getChild() { - SearchCriteriaService sc = SearchCriteria2 + SearchCriteria2 sc = SearchCriteria2 .create(SnapshotDataStoreVO.class); sc.addAnd(sc.getEntity().getDataStoreId(), Op.EQ, this.store.getId()); sc.addAnd(sc.getEntity().getRole(), Op.EQ, this.store.getRole()); diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index 98c6a3fc001..65524e03212 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -45,7 +45,7 @@ import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.exception.CloudRuntimeException; @@ -220,7 +220,7 @@ public class DefaultEndPointSelector implements EndPointSelector { } private List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); if (dcId != null) { sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); } @@ -258,7 +258,7 @@ public class DefaultEndPointSelector implements EndPointSelector { endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); } else if (store.getScope().getScopeType() == ScopeType.CLUSTER) { - SearchCriteriaService sc = SearchCriteria2.create(HostVO.class); + SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, store.getScope().getScopeId()); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); List hosts = sc.find(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java index 7c986403636..8c43138e695 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java @@ -31,7 +31,7 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteriaService; +import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.UpdateBuilder; @Component @@ -50,7 +50,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2 + SearchCriteria2 sc = SearchCriteria2 .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); @@ -59,7 +59,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2 + SearchCriteria2 sc = SearchCriteria2 .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); diff --git a/framework/db/src/com/cloud/utils/db/GenericDao.java b/framework/db/src/com/cloud/utils/db/GenericDao.java index f32880f6ad4..6c7e928806f 100755 --- a/framework/db/src/com/cloud/utils/db/GenericDao.java +++ b/framework/db/src/com/cloud/utils/db/GenericDao.java @@ -258,10 +258,6 @@ public interface GenericDao { public K getRandomlyIncreasingNextInSequence(Class clazz, String name); - SearchCriteria2 createSearchCriteria2(Class resultType); - - SearchCriteria2 createSearchCriteria2(); - public T findOneBy(final SearchCriteria sc); /** diff --git a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java index a566ec54ce6..fd561713feb 100755 --- a/framework/db/src/com/cloud/utils/db/GenericDaoBase.java +++ b/framework/db/src/com/cloud/utils/db/GenericDaoBase.java @@ -59,6 +59,7 @@ import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.CallbackFilter; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.Factory; +import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.NoOp; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; @@ -169,11 +170,7 @@ public abstract class GenericDaoBase extends Compone @Override @SuppressWarnings("unchecked") @DB(txn=false) public GenericSearchBuilder createSearchBuilder(Class resultType) { - final T entity = (T)_searchEnhancer.create(); - final Factory factory = (Factory)entity; - GenericSearchBuilder builder = new GenericSearchBuilder(entity, resultType, _allAttributes); - factory.setCallback(0, builder); - return builder; + return new GenericSearchBuilder(_entityBeanType, resultType); } @Override @@ -181,6 +178,15 @@ public abstract class GenericDaoBase extends Compone return _allAttributes; } + + @SuppressWarnings("unchecked") + public T createSearchEntity(MethodInterceptor interceptor) { + T entity = (T)_searchEnhancer.create(); + final Factory factory = (Factory)entity; + factory.setCallback(0, interceptor); + return entity; + } + @SuppressWarnings("unchecked") protected GenericDaoBase() { super(); @@ -1781,14 +1787,9 @@ public abstract class GenericDaoBase extends Compone return (UpdateBuilder)factory.getCallback(1); } - @SuppressWarnings("unchecked") @Override @DB(txn=false) public SearchBuilder createSearchBuilder() { - final T entity = (T)_searchEnhancer.create(); - final Factory factory = (Factory)entity; - SearchBuilder builder = new SearchBuilder(entity, _allAttributes); - factory.setCallback(0, builder); - return builder; + return new SearchBuilder(_entityBeanType); } @Override @DB(txn=false) @@ -1797,24 +1798,6 @@ public abstract class GenericDaoBase extends Compone return builder.create(); } - @Override @DB(txn=false) - public SearchCriteria2 createSearchCriteria2(Class resultType) { - final T entity = (T)_searchEnhancer.create(); - final Factory factory = (Factory)entity; - SearchCriteria2 sc = new SearchCriteria2(entity, resultType, _allAttributes, this); - factory.setCallback(0, sc); - return sc; - } - - @Override @DB(txn=false) - public SearchCriteria2 createSearchCriteria2() { - final T entity = (T)_searchEnhancer.create(); - final Factory factory = (Factory)entity; - SearchCriteria2 sc = new SearchCriteria2(entity, entity.getClass(), _allAttributes, this); - factory.setCallback(0, sc); - return sc; - } - @Override public int getRegionId(){ return Transaction.s_region_id; diff --git a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java index bf28144236f..732527aa30a 100755 --- a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java @@ -17,19 +17,12 @@ package com.cloud.utils.db; import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.UUID; -import javax.persistence.Column; -import javax.persistence.Transient; - import net.sf.cglib.proxy.Factory; -import net.sf.cglib.proxy.MethodInterceptor; -import net.sf.cglib.proxy.MethodProxy; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @@ -43,30 +36,10 @@ import com.cloud.utils.db.SearchCriteria.SelectType; * @param VO object this Search is build for. * @param Result object that should contain the results. */ -public class GenericSearchBuilder implements MethodInterceptor { - final protected Map _attrs; - - protected ArrayList _conditions; - protected HashMap>> _joins; - protected ArrayList _selects; - private final HashMap _params = new HashMap(); - protected Class _resultType; - protected SelectType _selectType; - protected Class _entityBeanType; - - protected SearchCriteria2(T entity, Class resultType, final Map attrs, GenericDao dao) { - _entityBeanType = (Class)entity.getClass(); - _dao = dao; - _resultType = resultType; - _attrs = attrs; - _entity = entity; - _conditions = new ArrayList(); - _specifiedAttrs = new ArrayList(); +public class SearchCriteria2 extends SearchBase { + final HashMap _params = new HashMap(); + + protected SearchCriteria2(Class entityType, Class resultType) { + super(entityType, resultType); } - - static public SearchCriteria2 create(Class entityType, Class resultType) { - GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); - assert dao != null : "Can not find DAO for " + entityType.getName(); - SearchCriteria2 sc = dao.createSearchCriteria2(resultType); - return sc; - } - - static public SearchCriteria2 create(Class entityType) { - GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); - assert dao != null : "Can not find DAO for " + entityType.getName(); - SearchCriteria2 sc = dao.createSearchCriteria2(); - return sc; - } - - @Override - public void selectField(Object... useless) { + + @SuppressWarnings("unchecked") + static public SearchCriteria2 create(Class entityType, Class resultType) { + GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); + assert dao != null : "Can not find DAO for " + entityType.getName(); + return new SearchCriteria2(entityType, resultType); + } + + static public SearchCriteria2 create(Class entityType) { + return create(entityType, entityType); + } + + public void selectField(Object... useless) { assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes"; - + if (_selects == null) { _selects = new ArrayList(); } - + for (Attribute attr : _specifiedAttrs) { Field field = null; try { @@ -75,12 +58,12 @@ public class GenericSearchBuilder extends SearchBase { } _selects.add(new Select(Func.NATIVE, attr, field, null)); } - + _specifiedAttrs.clear(); - + return this; } - + /** * Specifies the field to select. * @@ -130,13 +113,6 @@ public class GenericSearchBuilder extends SearchBase { return this; } - @Override - protected void set(String name) { - Attribute attr = _attrs.get(name); - assert (attr != null) : "Searching for a field that's not there: " + name; - _specifiedAttrs.add(attr); - } - /** * Adds an AND condition to the SearchBuilder. * @@ -155,11 +131,6 @@ public class GenericSearchBuilder extends SearchBase { return this; } - public Preset and(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - public GenericSearchBuilder and() { constructCondition(null, " AND ", null, null); return this; @@ -182,10 +153,6 @@ public class GenericSearchBuilder extends SearchBase { return and(name, useless, op); } - public Preset where(Object useless, Op op) { - return and(useless, op); - } - public GenericSearchBuilder left(String name, Object useless, Op op) { constructCondition(name, " ( ", _specifiedAttrs.get(0), op); return this; @@ -196,19 +163,10 @@ public class GenericSearchBuilder extends SearchBase { return this; } - public Preset left(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - public GenericSearchBuilder op(Object useless, Op op, String name) { return left(useless, op, name); } - public Preset op(Object useless, Op op) { - return left(useless, op); - } - public GenericSearchBuilder op(String name, Object useless, Op op) { return left(name, useless, op); } @@ -221,19 +179,12 @@ public class GenericSearchBuilder extends SearchBase { return left(name, useless, op); } - public Preset openParen(Object useless, Op op) { - return left(useless, op); - } - - public GroupBy groupBy(Object... useless) { + public GroupBy, T, K> groupBy(Object... useless) { assert _groupBy == null : "Can't do more than one group bys"; - _groupBy = new GroupBy(this); + GroupBy, T, K> groupBy = new GroupBy, T, K>(this); + _groupBy = groupBy; - return _groupBy; - } - - protected List getSpecifiedAttributes() { - return _specifiedAttrs; + return groupBy; } /** @@ -254,11 +205,6 @@ public class GenericSearchBuilder extends SearchBase { return this; } - public Preset or(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - public GenericSearchBuilder join(String name, GenericSearchBuilder builder, Object useless, Object useless2, JoinBuilder.JoinType joinType) { assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; assert _specifiedAttrs.size() == 1 : "You didn't select the attribute."; @@ -266,9 +212,9 @@ public class GenericSearchBuilder extends SearchBase { assert builder._specifiedAttrs.size() == 1 : "You didn't select the attribute."; assert builder != this : "You can't add yourself, can you? Really think about it!"; - JoinBuilder> t = new JoinBuilder>(builder, _specifiedAttrs.get(0), builder._specifiedAttrs.get(0), joinType); + JoinBuilder> t = new JoinBuilder>(builder, _specifiedAttrs.get(0), builder._specifiedAttrs.get(0), joinType); if (_joins == null) { - _joins = new HashMap>>(); + _joins = new HashMap>>(); } _joins.put(name, t); @@ -277,29 +223,7 @@ public class GenericSearchBuilder extends SearchBase { return this; } - protected Condition constructCondition(String conditionName, String cond, Attribute attr, Op op) { - assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; - assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute."; - assert op != Op.SC : "Call join"; - - Condition condition = new Condition(conditionName, cond, attr, op); - _conditions.add(condition); - _specifiedAttrs.clear(); - return condition; - } - /** - * creates the SearchCriteria so the actual values can be filled in. - * - * @return SearchCriteria - */ - public SearchCriteria create() { - if (_entity != null) { - done(); - } - return new SearchCriteria(this); - } - public SearchCriteria create(String name, Object... values) { SearchCriteria sc = create(); sc.setParameters(name, values); @@ -320,62 +244,11 @@ public class GenericSearchBuilder extends SearchBase { return right(); } - public SelectType getSelectType() { - return _selectType; - } - /** * Marks the SearchBuilder as completed in building the search conditions. */ public synchronized void done() { - if (_entity != null) { - Factory factory = (Factory)_entity; - factory.setCallback(0, null); - _entity = null; - } - - if (_joins != null) { - for (JoinBuilder> join : _joins.values()) { - join.getT().done(); - } - } - - if (_selects == null || _selects.size() == 0) { - _selectType = SelectType.Entity; - assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType; - return; - } - - for (Select select : _selects) { - if (select.field == null) { - assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?"; - _selectType = SelectType.Single; - return; - } - if (select.func != null) { - _selectType = SelectType.Result; - return; - } - } - - _selectType = SelectType.Fields; + super.finalize(); } - public class Preset { - GenericSearchBuilder builder; - Condition condition; - - protected Preset(GenericSearchBuilder builder, Condition condition) { - this.builder = builder; - this.condition = condition; - } - - public GenericSearchBuilder values(Object... params) { - if (condition.op.getParams() > 0 && condition.op.params != params.length) { - throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op); - } - condition.setPresets(params); - return builder; - } - } } diff --git a/framework/db/src/com/cloud/utils/db/GroupBy.java b/framework/db/src/com/cloud/utils/db/GroupBy.java index 3b9cd19694f..b3f88da60ae 100644 --- a/framework/db/src/com/cloud/utils/db/GroupBy.java +++ b/framework/db/src/com/cloud/utils/db/GroupBy.java @@ -23,12 +23,12 @@ import com.cloud.utils.Pair; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; -public class GroupBy { - GenericSearchBuilder _builder; +public class GroupBy, T, R> { + J _builder; List> _groupBys; Having _having; - public GroupBy(GenericSearchBuilder builder) { + public GroupBy(J builder) { _builder = builder; _groupBys = new ArrayList>(); _having = null; @@ -38,19 +38,19 @@ public class GroupBy { _builder.getSpecifiedAttributes().clear(); } - public GroupBy group(Object useless) { + public GroupBy group(Object useless) { _groupBys.add(new Pair(null, _builder.getSpecifiedAttributes().get(0))); _builder.getSpecifiedAttributes().clear(); - return this; + return this; } - public GroupBy group(Func func, Object useless) { + public GroupBy group(Func func, Object useless) { _groupBys.add(new Pair(func, _builder.getSpecifiedAttributes().get(0))); _builder.getSpecifiedAttributes().clear(); return this; } - public GenericSearchBuilder having(Func func, Object obj, Op op, Object value) { + public J having(Func func, Object obj, Op op, Object value) { assert(_having == null) : "You can only specify one having in a group by"; List attrs = _builder.getSpecifiedAttributes(); assert attrs.size() == 1 : "You didn't specified an attribute"; diff --git a/framework/db/src/com/cloud/utils/db/JoinBuilder.java b/framework/db/src/com/cloud/utils/db/JoinBuilder.java index c4920c44354..f770ac432e6 100644 --- a/framework/db/src/com/cloud/utils/db/JoinBuilder.java +++ b/framework/db/src/com/cloud/utils/db/JoinBuilder.java @@ -16,64 +16,65 @@ // under the License. package com.cloud.utils.db; - public class JoinBuilder { - - public enum JoinType { - INNER ("INNER JOIN"), - LEFT ("LEFT JOIN"), - RIGHT ("RIGHT JOIN"), - RIGHTOUTER ("RIGHT OUTER JOIN"), - LEFTOUTER ("LEFT OUTER JOIN"); - - private final String _name; - - JoinType(String name) { - _name = name; - } - - public String getName() { return _name; } - } - - private T t; - private JoinType type; - private Attribute firstAttribute; - private Attribute secondAttribute; - - public JoinBuilder(T t, Attribute firstAttribute, - Attribute secondAttribute, JoinType type) { - this.t = t; - this.firstAttribute = firstAttribute; - this.secondAttribute = secondAttribute; - this.type = type; - } - - public T getT() { - return t; - } - public void setT(T t) { - this.t = t; - } - public JoinType getType() { - return type; - } - public void setType(JoinType type) { - this.type = type; - } - public Attribute getFirstAttribute() { - return firstAttribute; - } - public void setFirstAttribute(Attribute firstAttribute) { - this.firstAttribute = firstAttribute; - } - public Attribute getSecondAttribute() { - return secondAttribute; - } - public void setSecondAttribute(Attribute secondAttribute) { - this.secondAttribute = secondAttribute; - } + public enum JoinType { + INNER("INNER JOIN"), + LEFT("LEFT JOIN"), + RIGHT("RIGHT JOIN"), + RIGHTOUTER("RIGHT OUTER JOIN"), + LEFTOUTER("LEFT OUTER JOIN"); + + private final String _name; + + JoinType(String name) { + _name = name; + } + + public String getName() { + return _name; + } + } + + private final T t; + private JoinType type; + private Attribute firstAttribute; + private Attribute secondAttribute; + + public JoinBuilder(T t, Attribute firstAttribute, + Attribute secondAttribute, JoinType type) { + this.t = t; + this.firstAttribute = firstAttribute; + this.secondAttribute = secondAttribute; + this.type = type; + } + + public T getT() { + return t; + } + + public JoinType getType() { + return type; + } + + public void setType(JoinType type) { + this.type = type; + } + + public Attribute getFirstAttribute() { + return firstAttribute; + } + + public void setFirstAttribute(Attribute firstAttribute) { + this.firstAttribute = firstAttribute; + } + + public Attribute getSecondAttribute() { + return secondAttribute; + } + + public void setSecondAttribute(Attribute secondAttribute) { + this.secondAttribute = secondAttribute; + } } - - diff --git a/framework/db/src/com/cloud/utils/db/SearchBase.java b/framework/db/src/com/cloud/utils/db/SearchBase.java new file mode 100644 index 00000000000..b28ac17d42a --- /dev/null +++ b/framework/db/src/com/cloud/utils/db/SearchBase.java @@ -0,0 +1,279 @@ +package com.cloud.utils.db; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Transient; + +import net.sf.cglib.proxy.Factory; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.SearchCriteria.SelectType; +import com.cloud.utils.exception.CloudRuntimeException; + +public abstract class SearchBase { + + final Map _attrs; + final Class _entityBeanType; + final Class _resultType; + final GenericDaoBase _dao; + + final ArrayList _conditions; + final ArrayList _specifiedAttrs; + + protected HashMap>> _joins; + protected ArrayList _selects; - private final GroupBy _groupBy; + private final GroupBy, ?, K> _groupBy; private final List _groupByValues; private final Class _resultType; private final SelectType _selectType; - protected SearchCriteria(final Map attrs, ArrayList conditions, ArrayList selects, SelectType selectType, Class resultType, + HashMap params) { this._attrs = attrs; this._conditions = conditions; this._selects = selects; @@ -132,7 +133,7 @@ public class SearchCriteria { this._groupByValues = null; } - protected SearchCriteria(GenericSearchBuilder sb) { + protected SearchCriteria(SearchBase sb) { this._attrs = sb._attrs; this._conditions = sb._conditions; this._additionals = new ArrayList(); @@ -140,8 +141,8 @@ public class SearchCriteria { this._joins = null; if (sb._joins != null) { _joins = new HashMap>>(sb._joins.size()); - for (Map.Entry>> entry : sb._joins.entrySet()) { - JoinBuilder> value = entry.getValue(); + for (Map.Entry>> entry : sb._joins.entrySet()) { + JoinBuilder> value = entry.getValue(); _joins.put(entry.getKey(), new JoinBuilder>(value.getT().create(),value.getFirstAttribute(), value.getSecondAttribute(), value.getType())); } } @@ -242,8 +243,8 @@ public class SearchCriteria { return _joins.get(joinName).getT(); } - public Pair, List> getGroupBy() { - return _groupBy == null ? null : new Pair, List>(_groupBy, _groupByValues); + public Pair, List> getGroupBy() { + return _groupBy == null ? null : new Pair, List>(_groupBy, _groupByValues); } public void setGroupByValues(Object... values) { diff --git a/framework/db/src/com/cloud/utils/db/SearchCriteria2.java b/framework/db/src/com/cloud/utils/db/SearchCriteria2.java index cccd2204888..1d9ed4bfcb4 100755 --- a/framework/db/src/com/cloud/utils/db/SearchCriteria2.java +++ b/framework/db/src/com/cloud/utils/db/SearchCriteria2.java @@ -23,11 +23,8 @@ import java.util.HashMap; import java.util.List; import java.util.UUID; -import net.sf.cglib.proxy.Factory; - import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria.SelectType; public class SearchCriteria2 extends SearchBase { final HashMap _params = new HashMap(); @@ -69,16 +66,6 @@ public class SearchCriteria2 extends SearchBase { _specifiedAttrs.clear(); } - private void constructCondition(String conditionName, String cond, Attribute attr, Op op) { - assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; - assert op == null || _specifiedAttrs.size() == 1 : "You didn't select the attribute."; - assert op != Op.SC : "Call join"; - - GenericSearchBuilder.Condition condition = new GenericSearchBuilder.Condition(conditionName, cond, attr, op); - _conditions.add(condition); - _specifiedAttrs.clear(); - } - private void setParameters(String conditionName, Object... params) { assert _conditions.contains(new Condition(conditionName)) : "Couldn't find " + conditionName; _params.put(conditionName, params); @@ -91,8 +78,8 @@ public class SearchCriteria2 extends SearchBase { } public List list() { - done(); - SearchCriteria sc1 = createSearchCriteria(); + finalize(); + SearchCriteria sc1 = create(); if (isSelectAll()) { return (List)_dao.search(sc1, null); } else { @@ -108,43 +95,56 @@ public class SearchCriteria2 extends SearchBase { return _entity; } - private SearchCriteria createSearchCriteria() { - return new SearchCriteria(_attrs, _conditions, _selects, _selectType, _resultType, _params); - } - - private void done() { - if (_entity != null) { - Factory factory = (Factory)_entity; - factory.setCallback(0, null); - _entity = null; - } - - if (_selects == null || _selects.size() == 0) { - _selectType = SelectType.Entity; - assert _entityBeanType.equals(_resultType) : "Expecting " + _entityBeanType + " because you didn't specify any selects but instead got " + _resultType; - return; - } - - for (Select select : _selects) { - if (select.field == null) { - assert (_selects.size() == 1) : "You didn't specify any fields to put the result in but you're specifying more than one select so where should I put the selects?"; - _selectType = SelectType.Single; - return; - } - if (select.func != null) { - _selectType = SelectType.Result; - return; - } - } - - _selectType = SelectType.Fields; - } - - public K find() { + public K find() { assert isSelectAll() : "find doesn't support select search"; - done(); - SearchCriteria sc1 = createSearchCriteria(); + finalize(); + SearchCriteria sc1 = create(); return (K)_dao.findOneBy(sc1); } + public Preset and(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + + public Preset where(Object useless, Op op) { + return and(useless, op); + } + + public Preset left(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + + public Preset op(Object useless, Op op) { + return left(useless, op); + } + + public Preset openParen(Object useless, Op op) { + return left(useless, op); + } + + public Preset or(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + + public class Preset { + SearchCriteria2 builder; + Condition condition; + + protected Preset(SearchCriteria2 builder, Condition condition) { + this.builder = builder; + this.condition = condition; + } + + public SearchCriteria2 values(Object... params) { + if (condition.op.getParams() > 0 && condition.op.params != params.length) { + throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op); + } + condition.setPresets(params); + return builder; + } + } + } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/SyncQueueItemDaoImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/SyncQueueItemDaoImpl.java index ccb7f103742..0cd231f6b4b 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/SyncQueueItemDaoImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/dao/SyncQueueItemDaoImpl.java @@ -49,7 +49,7 @@ public class SyncQueueItemDaoImpl extends GenericDaoBase queueIdSearch = createSearchBuilder(Long.class); queueIdSearch.and("contentId", queueIdSearch.entity().getContentId(), Op.EQ); queueIdSearch.and("contentType", queueIdSearch.entity().getContentType(), Op.EQ); - queueIdSearch.selectField(queueIdSearch.entity().getId()); + queueIdSearch.selectFields(queueIdSearch.entity().getId()); queueIdSearch.done(); } diff --git a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index 2a4a06cc958..2ddb1158c8c 100644 --- a/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -898,13 +898,13 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, JoinJobSearch = _joinMapDao.createSearchBuilder(Long.class); JoinJobSearch.and(JoinJobSearch.entity().getJoinJobId(), Op.EQ, "joinJobId"); - JoinJobSearch.selectField(JoinJobSearch.entity().getJobId()); + JoinJobSearch.selectFields(JoinJobSearch.entity().getJobId()); JoinJobSearch.done(); JoinJobTimeSearch = _joinMapDao.createSearchBuilder(Long.class); JoinJobTimeSearch.and(JoinJobTimeSearch.entity().getNextWakeupTime(), Op.LT, "beginTime"); JoinJobTimeSearch.and(JoinJobTimeSearch.entity().getExpiration(), Op.GT, "endTime"); - JoinJobTimeSearch.selectField(JoinJobTimeSearch.entity().getJobId()).done(); + JoinJobTimeSearch.selectFields(JoinJobTimeSearch.entity().getJobId()).done(); JobIdsSearch = _jobDao.createSearchBuilder(); JobIdsSearch.and(JobIdsSearch.entity().getId(), Op.IN, "ids").done(); @@ -913,13 +913,13 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, QueueJobIdsSearch.and(QueueJobIdsSearch.entity().getContentId(), Op.IN, "contentIds").done(); JoinJobIdsSearch = _joinMapDao.createSearchBuilder(Long.class); - JoinJobIdsSearch.selectField(JoinJobIdsSearch.entity().getJobId()); + JoinJobIdsSearch.selectFields(JoinJobIdsSearch.entity().getJobId()); JoinJobIdsSearch.and(JoinJobIdsSearch.entity().getJoinJobId(), Op.EQ, "joinJobId"); JoinJobIdsSearch.and(JoinJobIdsSearch.entity().getJobId(), Op.NIN, "jobIds"); JoinJobIdsSearch.done(); ContentIdsSearch = _queueItemDao.createSearchBuilder(Long.class); - ContentIdsSearch.selectField(ContentIdsSearch.entity().getContentId()).done(); + ContentIdsSearch.selectFields(ContentIdsSearch.entity().getContentId()).done(); AsyncJobExecutionContext.init(this, _joinMapDao); OutcomeImpl.init(this); diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 96ffe35756d..415111d4c91 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -459,7 +459,7 @@ public class StorageManagerImpl extends ManagerBase implements StorageManager, C _serverId = _msServer.getId(); UpHostsInPoolSearch = _storagePoolHostDao.createSearchBuilder(Long.class); - UpHostsInPoolSearch.selectField(UpHostsInPoolSearch.entity().getHostId()); + UpHostsInPoolSearch.selectFields(UpHostsInPoolSearch.entity().getHostId()); SearchBuilder hostSearch = _hostDao.createSearchBuilder(); hostSearch.and("status", hostSearch.entity().getStatus(), Op.EQ); hostSearch.and("resourceState", hostSearch.entity().getResourceState(), Op.EQ); From e2988902c9e7891f0038c579e6951537cdd10a68 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Fri, 27 Sep 2013 15:23:10 -0700 Subject: [PATCH 03/27] Changed SearchCriteria2 to GenericQueryBuilder to reflect the same placement --- .../cloud/agent/manager/AgentManagerImpl.java | 8 +++--- .../manager/ClusteredAgentManagerImpl.java | 10 +++---- .../ClusterBasedAgentLoadBalancerPlanner.java | 8 +++--- .../dao/StorageNetworkIpAddressDaoImpl.java | 2 +- .../dc/dao/StorageNetworkIpRangeDaoImpl.java | 10 +++---- .../network/dao/UserIpv6AddressDaoImpl.java | 2 +- .../com/cloud/user/AccountDetailsDaoImpl.java | 8 +++--- .../datastore/db/PrimaryDataStoreDaoImpl.java | 8 +++--- .../manager/StorageCacheManagerImpl.java | 6 ++-- .../StorageCacheReplacementAlgorithmLRU.java | 10 +++---- .../storage/snapshot/SnapshotObject.java | 6 ++-- .../endpoint/DefaultEndPointSelector.java | 6 ++-- .../db/TemplatePrimaryDataStoreDaoImpl.java | 8 +++--- ...riteria2.java => GenericQueryBuilder.java} | 16 +++++------ .../database/BaremetalDhcpDaoImpl.java | 2 +- .../database/BaremetalPxeDaoImpl.java | 2 +- .../BareMetalPingServiceImpl.java | 6 ++-- .../networkservice/BaremetalDhcpElement.java | 6 ++-- .../BaremetalDhcpManagerImpl.java | 6 ++-- .../BaremetalKickStartServiceImpl.java | 6 ++-- .../networkservice/BaremetalPxeElement.java | 6 ++-- .../BaremetalPxeManagerImpl.java | 6 ++-- .../cloud/ovm/hypervisor/OvmDiscoverer.java | 4 +-- .../com/cloud/ucs/database/UcsManagerDao.java | 2 +- .../com/cloud/ucs/manager/UcsManagerImpl.java | 16 +++++------ .../xen/discoverer/XcpServerDiscoverer.java | 6 ++-- .../element/InternalLoadBalancerElement.java | 6 ++-- .../consoleproxy/ConsoleProxyManagerImpl.java | 6 ++-- .../cloud/ha/AbstractInvestigatorImpl.java | 6 ++-- .../network/StorageNetworkManagerImpl.java | 6 ++-- .../network/element/VirtualRouterElement.java | 6 ++-- .../cloud/resource/ResourceManagerImpl.java | 28 +++++++++---------- .../com/cloud/storage/OCFS2ManagerImpl.java | 6 ++-- .../SecondaryStorageManagerImpl.java | 8 +++--- 34 files changed, 124 insertions(+), 124 deletions(-) rename framework/db/src/com/cloud/utils/db/{SearchCriteria2.java => GenericQueryBuilder.java} (88%) diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 0b04d74e300..4e117723c8e 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -98,8 +98,8 @@ import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; @@ -1448,7 +1448,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl try { List behindAgents = findAgentsBehindOnPing(); for (Long agentId : behindAgents) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getId(), Op.EQ, agentId); HostVO h = sc.find(); if (h != null) { @@ -1470,7 +1470,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl } } - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getResourceState(), Op.IN, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); List hosts = sc.list(); diff --git a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index 3d644734b73..3fcd65669cc 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -88,8 +88,8 @@ import com.cloud.utils.DateUtil; import com.cloud.utils.Profiler; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; @@ -783,7 +783,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public void startRebalanceAgents() { s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); List allManagedAgents = sc.list(); @@ -1369,12 +1369,12 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust profilerAgentLB.start(); //initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold if (EnableLB.value() && !_agentLbHappened) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); List allManagedRoutingAgents = sc.list(); - sc = SearchCriteria2.create(HostVO.class); + sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); List allAgents = sc.list(); double allHostsCount = allAgents.size(); diff --git a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java index 47e2b97c65a..429e82489ea 100755 --- a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java +++ b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java @@ -36,9 +36,9 @@ import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; @Component @Local(value=AgentLoadBalancerPlanner.class) @@ -49,7 +49,7 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements @Override public List getHostsToRebalance(long msId, int avLoad) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId); List allHosts = sc.list(); @@ -59,7 +59,7 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements return null; } - sc = SearchCriteria2.create(HostVO.class); + sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); List directHosts = sc.list(); diff --git a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java index ee1c3db8641..e78533f7821 100755 --- a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpAddressDaoImpl.java @@ -33,7 +33,7 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; diff --git a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java index db85c06962b..04bac512465 100755 --- a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java @@ -31,8 +31,8 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @@ -50,21 +50,21 @@ public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase listByPodId(long podId) { - SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); return sc.list(); } @Override public List listByRangeId(long rangeId) { - SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getId(), Op.EQ, rangeId); return sc.list(); } @Override public List listByDataCenterId(long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); return sc.list(); } diff --git a/engine/schema/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java b/engine/schema/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java index c9f38ec88c4..b3f2416f63f 100644 --- a/engine/schema/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/UserIpv6AddressDaoImpl.java @@ -35,7 +35,7 @@ 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.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; @Component @Local(value=UserIpv6AddressDao.class) diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java index 6a0b2487cd7..1d47fb6282d 100755 --- a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java @@ -30,8 +30,8 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; @Local(value = {AccountDetailsDao.class}) @@ -46,7 +46,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public Map findDetails(long accountId) { - SearchCriteria2 sc = SearchCriteria2.create(AccountDetailVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); List results = sc.list(); Map details = new HashMap(results.size()); @@ -72,7 +72,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public AccountDetailVO findDetail(long accountId, String name) { - SearchCriteria2 sc = SearchCriteria2.create(AccountDetailVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); sc.addAnd(sc.getEntity().getName(), Op.EQ, name); return sc.find(); diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index 074a156a495..ccf9a1f93f1 100644 --- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -39,8 +39,8 @@ 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.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @@ -316,7 +316,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase public List findZoneWideStoragePoolsByTags(long dcId, String[] tags) { List storagePools = null; if (tags == null || tags.length == 0) { - SearchCriteria2 sc = SearchCriteria2.create(StoragePoolVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StoragePoolVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); @@ -421,7 +421,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase @Override public List findZoneWideStoragePoolsByHypervisor(long dataCenterId, HypervisorType hypervisorType) { - SearchCriteria2 sc = SearchCriteria2.create(StoragePoolVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StoragePoolVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java index f14985d08d6..e869714783d 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java @@ -25,8 +25,8 @@ import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import org.apache.cloudstack.engine.subsystem.api.storage.*; @@ -79,7 +79,7 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { } protected List getCacheStores() { - SearchCriteria2 sc = SearchCriteria2.create(ImageStoreVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(ImageStoreVO.class); sc.addAnd(sc.getEntity().getRole(), SearchCriteria.Op.EQ, DataStoreRole.ImageCache); List imageStoreVOs = sc.list(); List stores = new ArrayList(); diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java index 9cd5995e346..c59b0604b93 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java @@ -21,8 +21,8 @@ import com.cloud.configuration.Config; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import org.apache.cloudstack.engine.subsystem.api.storage.*; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; @@ -72,7 +72,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem cal.add(Calendar.DAY_OF_MONTH, -unusedTimeInterval.intValue()); Date bef = cal.getTime(); - SearchCriteria2 sc = SearchCriteria2.create(TemplateDataStoreVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(TemplateDataStoreVO.class); sc.addAnd(sc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); sc.addAnd(sc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); sc.addAnd(sc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); @@ -83,7 +83,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem return templateFactory.getTemplate(template.getTemplateId(), store); } - SearchCriteria2 volSc = SearchCriteria2.create(VolumeDataStoreVO.class); + GenericQueryBuilder volSc = GenericQueryBuilder.create(VolumeDataStoreVO.class); volSc.addAnd(volSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); volSc.addAnd(volSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); volSc.addAnd(volSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); @@ -93,7 +93,7 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem return volumeFactory.getVolume(volume.getVolumeId(), store); } - SearchCriteria2 snapshotSc = SearchCriteria2.create(SnapshotDataStoreVO.class); + GenericQueryBuilder snapshotSc = GenericQueryBuilder.create(SnapshotDataStoreVO.class); snapshotSc.addAnd(snapshotSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); snapshotSc.addAnd(snapshotSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); snapshotSc.addAnd(snapshotSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java index 730cec41489..dcdc9382800 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java @@ -43,8 +43,8 @@ import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -104,7 +104,7 @@ public class SnapshotObject implements SnapshotInfo { @Override public SnapshotInfo getChild() { - SearchCriteria2 sc = SearchCriteria2 + GenericQueryBuilder sc = GenericQueryBuilder .create(SnapshotDataStoreVO.class); sc.addAnd(sc.getEntity().getDataStoreId(), Op.EQ, this.store.getId()); sc.addAnd(sc.getEntity().getRole(), Op.EQ, this.store.getRole()); diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index 1e4101e1d03..118db802060 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -46,7 +46,7 @@ import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @@ -220,7 +220,7 @@ public class DefaultEndPointSelector implements EndPointSelector { } private List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); if (dcId != null) { sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); } @@ -258,7 +258,7 @@ public class DefaultEndPointSelector implements EndPointSelector { endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); } else if (store.getScope().getScopeType() == ScopeType.CLUSTER) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, store.getScope().getScopeId()); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); List hosts = sc.list(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java index 8c43138e695..20bc7095149 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java @@ -30,8 +30,8 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.UpdateBuilder; @Component @@ -50,7 +50,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2 + GenericQueryBuilder sc = GenericQueryBuilder .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); @@ -59,7 +59,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = SearchCriteria2 + GenericQueryBuilder sc = GenericQueryBuilder .create(TemplatePrimaryDataStoreVO.class); sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); diff --git a/framework/db/src/com/cloud/utils/db/SearchCriteria2.java b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java similarity index 88% rename from framework/db/src/com/cloud/utils/db/SearchCriteria2.java rename to framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java index 1d9ed4bfcb4..1dabbf81a48 100755 --- a/framework/db/src/com/cloud/utils/db/SearchCriteria2.java +++ b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java @@ -26,21 +26,21 @@ import java.util.UUID; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; -public class SearchCriteria2 extends SearchBase { +public class GenericQueryBuilder extends SearchBase { final HashMap _params = new HashMap(); - protected SearchCriteria2(Class entityType, Class resultType) { + protected GenericQueryBuilder(Class entityType, Class resultType) { super(entityType, resultType); } @SuppressWarnings("unchecked") - static public SearchCriteria2 create(Class entityType, Class resultType) { + static public GenericQueryBuilder create(Class entityType, Class resultType) { GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); assert dao != null : "Can not find DAO for " + entityType.getName(); - return new SearchCriteria2(entityType, resultType); + return new GenericQueryBuilder(entityType, resultType); } - static public SearchCriteria2 create(Class entityType) { + static public GenericQueryBuilder create(Class entityType) { return create(entityType, entityType); } @@ -130,15 +130,15 @@ public class SearchCriteria2 extends SearchBase { } public class Preset { - SearchCriteria2 builder; + GenericQueryBuilder builder; Condition condition; - protected Preset(SearchCriteria2 builder, Condition condition) { + protected Preset(GenericQueryBuilder builder, Condition condition) { this.builder = builder; this.condition = condition; } - public SearchCriteria2 values(Object... params) { + public GenericQueryBuilder values(Object... params) { if (condition.op.getParams() > 0 && condition.op.params != params.length) { throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op); } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalDhcpDaoImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalDhcpDaoImpl.java index 8123ee0f6b7..b21010b8877 100644 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalDhcpDaoImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalDhcpDaoImpl.java @@ -32,7 +32,7 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; @Component @Local(value=BaremetalDhcpDao.class) diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalPxeDaoImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalPxeDaoImpl.java index acd7f136b6d..6afbc1b36dc 100644 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalPxeDaoImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/database/BaremetalPxeDaoImpl.java @@ -32,7 +32,7 @@ import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; @Component @Local(value = {BaremetalPxeDao.class}) diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java index 4376d403b16..783755d2fde 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java @@ -63,8 +63,8 @@ import com.cloud.resource.ServerResource; import com.cloud.uservm.UserVm; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -84,7 +84,7 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements @Override public boolean prepare(VirtualMachineProfile profile, NicProfile pxeNic, DeployDestination dest, ReservationContext context) { - SearchCriteria2 sc = SearchCriteria2.create(BaremetalPxeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.PING.toString()); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, dest.getPod().getId()); BaremetalPxeVO pxeVo = sc.find(); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java index afc3062643c..5459918b14a 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java @@ -40,8 +40,8 @@ import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.vm.*; import com.cloud.vm.VirtualMachine.Type; @@ -84,7 +84,7 @@ public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProv private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { Pod pod = dest.getPod(); if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) { - SearchCriteria2 sc = SearchCriteria2.create(BaremetalDhcpVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalDhcpVO.class); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, pod.getId()); return sc.find() != null; } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java index 739fafe77c6..9ab714dfe88 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java @@ -68,8 +68,8 @@ import com.cloud.resource.UnableDeleteHostException; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -311,7 +311,7 @@ public class BaremetalDhcpManagerImpl extends ManagerBase implements BaremetalDh return responses; } - SearchCriteria2 sc = SearchCriteria2.create(BaremetalDhcpVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalDhcpVO.class); if (cmd.getDeviceType() != null) { sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, cmd.getDeviceType()); } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java index 090b993d899..b4af709965f 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java @@ -58,8 +58,8 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.uservm.UserVm; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -87,7 +87,7 @@ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase imple @Override public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) { NetworkVO nwVO = _nwDao.findById(nic.getNetworkId()); - SearchCriteria2 sc = SearchCriteria2.create(BaremetalPxeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); BaremetalPxeVO pxeVo = sc.find(); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java index 29c0adcb82d..3e0572ad0e7 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java @@ -47,8 +47,8 @@ import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -91,7 +91,7 @@ public class BaremetalPxeElement extends AdapterBase implements NetworkElement { private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { Pod pod = dest.getPod(); if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) { - SearchCriteria2 sc = SearchCriteria2.create(BaremetalPxeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, pod.getId()); return sc.find() != null; } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java index 5332b63488b..16147562156 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java @@ -63,8 +63,8 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; @@ -220,7 +220,7 @@ public class BaremetalPxeManagerImpl extends ManagerBase implements BaremetalPxe } PhysicalNetworkVO phy = phys.get(0); - SearchCriteria2 sc = SearchCriteria2.create(BaremetalPxeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); //TODO: handle both kickstart and PING //sc.addAnd(sc.getEntity().getPodId(), Op.EQ, vm.getPodIdToDeployIn()); sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, phy.getId()); diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java index 1d8f4f06c56..d8b83109359 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java @@ -49,7 +49,7 @@ import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.ssh.SSHCmdHelper; @@ -90,7 +90,7 @@ public class OvmDiscoverer extends DiscovererBase implements Discoverer, } private boolean checkIfExisted(String guid) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getGuid(), SearchCriteria.Op.EQ, guid); sc.addAnd(sc.getEntity().getHypervisorType(), SearchCriteria.Op.EQ, HypervisorType.Ovm); diff --git a/plugins/hypervisors/ucs/src/com/cloud/ucs/database/UcsManagerDao.java b/plugins/hypervisors/ucs/src/com/cloud/ucs/database/UcsManagerDao.java index f1664a1870a..b341a1b2279 100644 --- a/plugins/hypervisors/ucs/src/com/cloud/ucs/database/UcsManagerDao.java +++ b/plugins/hypervisors/ucs/src/com/cloud/ucs/database/UcsManagerDao.java @@ -27,7 +27,7 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; public interface UcsManagerDao extends GenericDao { } diff --git a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java index fce903f6376..bc22ba6c080 100755 --- a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java +++ b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java @@ -61,8 +61,8 @@ import com.cloud.ucs.structure.UcsProfile; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.xmlobject.XmlObject; @@ -132,7 +132,7 @@ public class UcsManagerImpl implements UcsManager { } private void syncBlades(UcsManagerVO mgr) { - SearchCriteria2 q = SearchCriteria2.create(UcsBladeVO.class); + GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); q.addAnd(q.getEntity().getUcsManagerId(), Op.EQ, mgr.getId()); List pblades = q.list(); if (pblades.isEmpty()) { @@ -210,7 +210,7 @@ public class UcsManagerImpl implements UcsManager { @Override @DB public UcsManagerResponse addUcsManager(AddUcsManagerCmd cmd) { - SearchCriteria2 q = SearchCriteria2.create(UcsManagerVO.class); + GenericQueryBuilder q = GenericQueryBuilder.create(UcsManagerVO.class); q.addAnd(q.getEntity().getUrl(), Op.EQ, cmd.getUrl()); UcsManagerVO mgrvo = q.find(); if (mgrvo != null) { @@ -342,7 +342,7 @@ public class UcsManagerImpl implements UcsManager { @Override public UcsBladeResponse associateProfileToBlade(AssociateUcsProfileToBladeCmd cmd) { - SearchCriteria2 q = SearchCriteria2.create(UcsBladeVO.class); + GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); q.addAnd(q.getEntity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); q.addAnd(q.getEntity().getId(), Op.EQ, cmd.getBladeId()); UcsBladeVO bvo = q.find(); @@ -424,7 +424,7 @@ public class UcsManagerImpl implements UcsManager { return response; } - SearchCriteria2 serv = SearchCriteria2.create(UcsManagerVO.class); + GenericQueryBuilder serv = GenericQueryBuilder.create(UcsManagerVO.class); serv.addAnd(serv.getEntity().getZoneId(), Op.EQ, cmd.getZoneId()); List vos = serv.list(); @@ -454,7 +454,7 @@ public class UcsManagerImpl implements UcsManager { @Override public ListResponse listUcsBlades(ListUcsBladeCmd cmd) { - SearchCriteria2 serv = SearchCriteria2.create(UcsBladeVO.class); + GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); serv.addAnd(serv.getEntity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); List vos = serv.list(); @@ -509,7 +509,7 @@ public class UcsManagerImpl implements UcsManager { @Override public void deleteUcsManager(Long id) { - SearchCriteria2 serv = SearchCriteria2.create(UcsBladeVO.class); + GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); serv.addAnd(serv.getEntity().getUcsManagerId(), Op.EQ, id); List vos = serv.list(); for (UcsBladeVO vo : vos) { diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index 2242e0adefa..202b3405ead 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -70,8 +70,8 @@ import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; import com.xensource.xenapi.Connection; @@ -126,7 +126,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L try { _clusterDao.update(cluster.getId(), cluster); } catch (EntityExistsException e) { - SearchCriteria2 sc = SearchCriteria2.create(ClusterVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(ClusterVO.class); sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); List clusters = sc.list(); ClusterVO clu = clusters.get(0); diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java index 25736fa302e..35b4d52f268 100644 --- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java +++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java @@ -74,8 +74,8 @@ import com.cloud.user.User; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; import com.cloud.vm.DomainRouterVO; @@ -509,7 +509,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public List searchForInternalLoadBalancerElements(Long id, Long ntwkSvsProviderId, Boolean enabled) { - SearchCriteria2 sc = SearchCriteria2.create(VirtualRouterProviderVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(VirtualRouterProviderVO.class); if (id != null) { sc.addAnd(sc.getEntity().getId(), Op.EQ, id); } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index 9d0476aa601..8ad553adcd0 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -118,8 +118,8 @@ import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.events.SubscriptionMgr; import com.cloud.utils.exception.CloudRuntimeException; @@ -1693,7 +1693,7 @@ VirtualMachineGuru, SystemVmLoadScanHandler, ResourceStateAdapter { } protected HostVO findConsoleProxyHostByName(String name) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.ConsoleProxy); sc.addAnd(sc.getEntity().getName(), Op.EQ, name); return sc.find(); diff --git a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java index a0a8c5aee30..c64d2ec9e0d 100755 --- a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java +++ b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java @@ -38,9 +38,9 @@ import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.resource.ResourceManager; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; public abstract class AbstractInvestigatorImpl extends AdapterBase implements Investigator { private static final Logger s_logger = Logger.getLogger(AbstractInvestigatorImpl.class); @@ -68,7 +68,7 @@ public abstract class AbstractInvestigatorImpl extends AdapterBase implements In // Host.status is up and Host.type is routing protected List findHostByPod(long podId, Long excludeHostId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Type.Routing); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index c5944fd21a5..5d6fd62d55f 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -47,8 +47,8 @@ import com.cloud.network.dao.NetworkVO; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -339,7 +339,7 @@ public class StorageNetworkManagerImpl extends ManagerBase implements StorageNet @Override public boolean isStorageIpRangeAvailable(long zoneId) { - SearchCriteria2 sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); List entries = sc.list(); return entries.size() > 0; diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index bfa34bf063e..00d52bffbae 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -81,8 +81,8 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; @@ -969,7 +969,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl Long nspId = cmd.getNspId(); Boolean enabled = cmd.getEnabled(); - SearchCriteria2 sc = SearchCriteria2.create(VirtualRouterProviderVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(VirtualRouterProviderVO.class); if (id != null) { sc.addAnd(sc.getEntity().getId(), Op.EQ, id); } diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index ea3c71ace6b..27f0600176b 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -144,8 +144,8 @@ 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.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -2256,7 +2256,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List findDirectlyConnectedHosts() { /* The resource column is not null for direct connected resource */ - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getResource(), Op.NNULL); sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Disabled); return sc.list(); @@ -2264,7 +2264,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllUpAndEnabledHosts(Type type, Long clusterId, Long podId, long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); if (type != null) { sc.addAnd(sc.getEntity().getType(), Op.EQ, type); } @@ -2288,7 +2288,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List findHostByGuid(long dcId, String guid) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); return sc.list(); @@ -2296,14 +2296,14 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllHostsInCluster(long clusterId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); return sc.list(); } @Override public List listHostsInClusterByStatus(long clusterId, Status status) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, status); return sc.list(); @@ -2311,7 +2311,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllUpAndEnabledHostsInOneZoneByType(Type type, long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, type); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); @@ -2321,7 +2321,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); if (dcId != null) { sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); } @@ -2332,7 +2332,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllHostsInOneZoneByType(Type type, long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, type); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); return sc.list(); @@ -2340,7 +2340,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllHostsInAllZonesByType(Type type) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, type); return sc.list(); } @@ -2370,14 +2370,14 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public HostVO findHostByGuid(String guid) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); return sc.find(); } @Override public HostVO findHostByName(String name) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getName(), Op.EQ, name); return sc.find(); } @@ -2449,7 +2449,7 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType type, long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getHypervisorType(), Op.EQ, type); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); diff --git a/server/src/com/cloud/storage/OCFS2ManagerImpl.java b/server/src/com/cloud/storage/OCFS2ManagerImpl.java index 50c0f7659ff..c258a96684a 100755 --- a/server/src/com/cloud/storage/OCFS2ManagerImpl.java +++ b/server/src/com/cloud/storage/OCFS2ManagerImpl.java @@ -48,8 +48,8 @@ import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.utils.Ternary; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -141,7 +141,7 @@ public class OCFS2ManagerImpl extends ManagerBase implements OCFS2Manager, Resou throw new CloudRuntimeException("Cannot find cluster for ID " + clusterId); } - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cluster.getPodId()); sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index 6a880713994..a6af8119e3f 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -115,8 +115,8 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.SearchCriteria2; -import com.cloud.utils.db.SearchCriteria2; +import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.events.SubscriptionMgr; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -420,7 +420,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar SecStorageFirewallCfgCommand thiscpc = new SecStorageFirewallCfgCommand(true); thiscpc.addPortConfig(thisSecStorageVm.getPublicIpAddress(), copyPort, true, TemplateConstants.DEFAULT_TMPLT_COPY_INTF); - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorageVM); sc.addAnd(sc.getEntity().getStatus(), Op.IN, com.cloud.host.Status.Up, com.cloud.host.Status.Connecting); List ssvms = sc.list(); @@ -1345,7 +1345,7 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar @Override public List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { - SearchCriteria2 sc = SearchCriteria2.create(HostVO.class); + GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); if (dcId != null) { sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); } From e8cac2c5d8b9fa8d1aac2aedc4ad473534f43ad8 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Fri, 27 Sep 2013 16:57:25 -0700 Subject: [PATCH 04/27] Changed SearchCriteria2 to GenericQueryBuilder to reflect the same placement --- .../cloud/network/VirtualRouterProvider.java | 4 +- .../element/VirtualRouterElementService.java | 4 +- .../router/CreateVirtualRouterElementCmd.java | 14 +- .../cloud/agent/manager/AgentManagerImpl.java | 4 +- .../manager/ClusteredAgentManagerImpl.java | 19 +- .../ClusterBasedAgentLoadBalancerPlanner.java | 22 +- .../dc/dao/StorageNetworkIpRangeDaoImpl.java | 6 +- .../network/dao/VirtualRouterProviderDao.java | 10 +- .../dao/VirtualRouterProviderDaoImpl.java | 10 +- .../element/VirtualRouterProviderVO.java | 8 +- .../com/cloud/user/AccountDetailsDaoImpl.java | 6 +- .../datastore/db/PrimaryDataStoreDaoImpl.java | 21 +- .../manager/StorageCacheManagerImpl.java | 61 +-- .../StorageCacheReplacementAlgorithmLRU.java | 66 +-- .../storage/snapshot/SnapshotObject.java | 109 ++--- .../endpoint/DefaultEndPointSelector.java | 16 +- .../db/TemplatePrimaryDataStoreDaoImpl.java | 10 +- .../cloud/utils/db/GenericQueryBuilder.java | 67 +--- .../cloud/utils/db/GenericSearchBuilder.java | 45 +++ .../BareMetalPingServiceImpl.java | 4 +- .../networkservice/BaremetalDhcpElement.java | 35 +- .../BaremetalDhcpManagerImpl.java | 2 +- .../BaremetalKickStartServiceImpl.java | 4 +- .../networkservice/BaremetalPxeElement.java | 2 +- .../BaremetalPxeManagerImpl.java | 2 +- .../cloud/ovm/hypervisor/OvmDiscoverer.java | 378 ++++++++---------- .../com/cloud/ucs/manager/UcsManagerImpl.java | 14 +- .../xen/discoverer/XcpServerDiscoverer.java | 2 +- .../lb/ElasticLoadBalancerManagerImpl.java | 4 +- .../element/InternalLoadBalancerElement.java | 27 +- .../lb/InternalLoadBalancerVMManagerImpl.java | 6 +- .../InternalLbElementServiceTest.java | 8 +- .../InternalLbElementTest.java | 16 +- .../src/com/cloud/api/ApiResponseHelper.java | 6 +- .../consoleproxy/ConsoleProxyManagerImpl.java | 4 +- .../cloud/ha/AbstractInvestigatorImpl.java | 18 +- .../com/cloud/network/NetworkServiceImpl.java | 6 +- .../network/StorageNetworkManagerImpl.java | 2 +- .../network/element/VirtualRouterElement.java | 127 +++--- .../element/VpcVirtualRouterElement.java | 10 +- .../VirtualNetworkApplianceManagerImpl.java | 8 +- ...VpcVirtualNetworkApplianceManagerImpl.java | 8 +- .../cloud/resource/ResourceManagerImpl.java | 85 ++-- .../com/cloud/storage/OCFS2ManagerImpl.java | 8 +- .../SecondaryStorageManagerImpl.java | 18 +- 45 files changed, 642 insertions(+), 664 deletions(-) diff --git a/api/src/com/cloud/network/VirtualRouterProvider.java b/api/src/com/cloud/network/VirtualRouterProvider.java index f67686e6b08..02efb93db5a 100644 --- a/api/src/com/cloud/network/VirtualRouterProvider.java +++ b/api/src/com/cloud/network/VirtualRouterProvider.java @@ -20,14 +20,14 @@ import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; public interface VirtualRouterProvider extends InternalIdentity, Identity { - public enum VirtualRouterProviderType { + public enum Type { VirtualRouter, ElasticLoadBalancerVm, VPCVirtualRouter, InternalLbVm } - public VirtualRouterProviderType getType(); + public Type getType(); public boolean isEnabled(); diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index ea971b89c5d..b0db3d9bce2 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -22,12 +22,12 @@ import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElem import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.utils.component.PluggableService; public interface VirtualRouterElementService extends PluggableService{ VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd); - VirtualRouterProvider addElement(Long nspId, VirtualRouterProviderType providerType); + VirtualRouterProvider addElement(Long nspId, Type providerType); VirtualRouterProvider getCreatedElement(long id); List searchForVirtualRouterElement(ListVirtualRouterElementsCmd cmd); } diff --git a/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java index 66c8ae5cb74..35da69778f3 100644 --- a/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java @@ -36,7 +36,7 @@ import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.element.VirtualRouterElementService; import com.cloud.user.Account; @@ -70,15 +70,15 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { return nspId; } - public VirtualRouterProviderType getProviderType() { + public Type getProviderType() { if (providerType != null) { - if (providerType.equalsIgnoreCase(VirtualRouterProviderType.VirtualRouter.toString())) { - return VirtualRouterProviderType.VirtualRouter; - } else if (providerType.equalsIgnoreCase(VirtualRouterProviderType.VPCVirtualRouter.toString())) { - return VirtualRouterProviderType.VPCVirtualRouter; + if (providerType.equalsIgnoreCase(Type.VirtualRouter.toString())) { + return Type.VirtualRouter; + } else if (providerType.equalsIgnoreCase(Type.VPCVirtualRouter.toString())) { + return Type.VPCVirtualRouter; } else throw new InvalidParameterValueException("Invalid providerType specified"); } - return VirtualRouterProviderType.VirtualRouter; + return Type.VirtualRouter; } ///////////////////////////////////////////////////// diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 4e117723c8e..9c187535794 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -1449,7 +1449,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl List behindAgents = findAgentsBehindOnPing(); for (Long agentId : behindAgents) { GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getId(), Op.EQ, agentId); + sc.and(sc.entity().getId(), Op.EQ, agentId); HostVO h = sc.find(); if (h != null) { ResourceState resourceState = h.getResourceState(); @@ -1471,7 +1471,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl } GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getResourceState(), Op.IN, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); + sc.and(sc.entity().getResourceState(), Op.IN, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); List hosts = sc.list(); for (HostVO host : hosts) { diff --git a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index 3fcd65669cc..76e1d8e33b6 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -87,9 +87,8 @@ import com.cloud.serializer.GsonHelper; import com.cloud.utils.DateUtil; import com.cloud.utils.Profiler; import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.nio.Link; @@ -783,9 +782,9 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust public void startRebalanceAgents() { s_logger.debug("Management server " + _nodeId + " is asking other peers to rebalance their agents"); List allMS = _mshostDao.listBy(ManagementServerHost.State.Up); - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getManagementServerId(), Op.NNULL); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.Routing); List allManagedAgents = sc.list(); int avLoad = 0; @@ -1369,13 +1368,13 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust profilerAgentLB.start(); //initiate agent lb task will be scheduled and executed only once, and only when number of agents loaded exceeds _connectedAgentsThreshold if (EnableLB.value() && !_agentLbHappened) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getManagementServerId(), Op.NNULL); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getManagementServerId(), Op.NNULL); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.Routing); List allManagedRoutingAgents = sc.list(); - sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.Routing); List allAgents = sc.list(); double allHostsCount = allAgents.size(); double managedHostsCount = allManagedRoutingAgents.size(); diff --git a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java index 429e82489ea..1d744b79228 100755 --- a/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java +++ b/engine/orchestration/src/com/cloud/cluster/agentlb/ClusterBasedAgentLoadBalancerPlanner.java @@ -26,7 +26,6 @@ import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -36,9 +35,8 @@ import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; @Component @Local(value=AgentLoadBalancerPlanner.class) @@ -49,9 +47,9 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements @Override public List getHostsToRebalance(long msId, int avLoad) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); - sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.Routing); + sc.and(sc.entity().getManagementServerId(), Op.EQ, msId); List allHosts = sc.list(); if (allHosts.size() <= avLoad) { @@ -59,15 +57,15 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements return null; } - sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getManagementServerId(), Op.EQ, msId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getManagementServerId(), Op.EQ, msId); + sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); List directHosts = sc.list(); if (directHosts.isEmpty()) { s_logger.debug("No direct agents in status " + Status.Up + " exist for the management server " + msId + "; so it doesn't participate in agent rebalancing process"); return null; - } + } Map> hostToClusterMap = new HashMap>(); @@ -91,7 +89,7 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements int hostsLeft = directHosts.size(); List hostsToReturn = new ArrayList(); - s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() + + s_logger.debug("Management server " + msId + " can give away " + hostsToGive + " as it currently owns " + allHosts.size() + " and the average agent load in the system is " + avLoad + "; finalyzing list of hosts to give away..."); for (Long cluster : hostToClusterMap.keySet()) { List hostsInCluster = hostToClusterMap.get(cluster); @@ -105,7 +103,7 @@ public class ClusterBasedAgentLoadBalancerPlanner extends AdapterBase implements continue; } else { break; - } + } } else { s_logger.debug("Taking all " + hostsInCluster.size() + " hosts: " + hostsInCluster + " from cluster id=" + cluster); hostsToReturn.addAll(hostsInCluster); diff --git a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java index 04bac512465..f57acce1080 100755 --- a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java @@ -51,21 +51,21 @@ public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase listByPodId(long podId) { GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); + sc.and(sc.entity().getPodId(), Op.EQ, podId); return sc.list(); } @Override public List listByRangeId(long rangeId) { GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getId(), Op.EQ, rangeId); + sc.and(sc.entity().getId(), Op.EQ, rangeId); return sc.list(); } @Override public List listByDataCenterId(long dcId) { GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); return sc.list(); } diff --git a/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDao.java b/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDao.java index d929293c56d..70d71308904 100644 --- a/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDao.java +++ b/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDao.java @@ -20,12 +20,12 @@ import java.util.List; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.element.VirtualRouterProviderVO; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.utils.db.GenericDao; public interface VirtualRouterProviderDao extends GenericDao { - public VirtualRouterProviderVO findByNspIdAndType(long nspId, VirtualRouterProviderType type); - public List listByEnabledAndType(boolean enabled, VirtualRouterProviderType type); - public VirtualRouterProviderVO findByIdAndEnabledAndType(long id, boolean enabled, VirtualRouterProviderType type); - public List listByType(VirtualRouterProviderType type); + public VirtualRouterProviderVO findByNspIdAndType(long nspId, Type type); + public List listByEnabledAndType(boolean enabled, Type type); + public VirtualRouterProviderVO findByIdAndEnabledAndType(long id, boolean enabled, Type type); + public List listByType(Type type); } diff --git a/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDaoImpl.java b/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDaoImpl.java index dba835f9e1c..1c5d27e265f 100644 --- a/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDaoImpl.java +++ b/engine/schema/src/com/cloud/network/dao/VirtualRouterProviderDaoImpl.java @@ -23,7 +23,7 @@ import javax.ejb.Local; import org.springframework.stereotype.Component; import com.cloud.network.element.VirtualRouterProviderVO; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; @@ -46,7 +46,7 @@ public class VirtualRouterProviderDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("nsp_id", nspId); sc.setParameters("type", type); @@ -54,7 +54,7 @@ public class VirtualRouterProviderDaoImpl extends GenericDaoBase listByEnabledAndType(boolean enabled, VirtualRouterProviderType type) { + public List listByEnabledAndType(boolean enabled, Type type) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("enabled", enabled); sc.setParameters("type", type); @@ -62,7 +62,7 @@ public class VirtualRouterProviderDaoImpl extends GenericDaoBase sc = AllFieldsSearch.create(); sc.setParameters("id", id); sc.setParameters("enabled", enabled); @@ -71,7 +71,7 @@ public class VirtualRouterProviderDaoImpl extends GenericDaoBase listByType(VirtualRouterProviderType type) { + public List listByType(Type type) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("type", type); return listBy(sc); diff --git a/engine/schema/src/com/cloud/network/element/VirtualRouterProviderVO.java b/engine/schema/src/com/cloud/network/element/VirtualRouterProviderVO.java index ff2b6210504..62a25c1bc05 100644 --- a/engine/schema/src/com/cloud/network/element/VirtualRouterProviderVO.java +++ b/engine/schema/src/com/cloud/network/element/VirtualRouterProviderVO.java @@ -42,7 +42,7 @@ public class VirtualRouterProviderVO implements VirtualRouterProvider { @Column(name="type") @Enumerated(EnumType.STRING) - private VirtualRouterProviderType type; + private Type type; @Column(name="enabled") private boolean enabled; @@ -60,7 +60,7 @@ public class VirtualRouterProviderVO implements VirtualRouterProvider { this.uuid = UUID.randomUUID().toString(); } - public VirtualRouterProviderVO(long nspId, VirtualRouterProviderType type) { + public VirtualRouterProviderVO(long nspId, Type type) { this.nspId = nspId; this.type = type; this.uuid = UUID.randomUUID().toString(); @@ -81,7 +81,7 @@ public class VirtualRouterProviderVO implements VirtualRouterProvider { } @Override - public VirtualRouterProviderType getType() { + public Type getType() { return this.type; } @@ -106,7 +106,7 @@ public class VirtualRouterProviderVO implements VirtualRouterProvider { this.id = id; } - public void setType(VirtualRouterProviderType type) { + public void setType(Type type) { this.type = type; } diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java index 1d47fb6282d..81ae6368407 100755 --- a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java @@ -47,7 +47,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public Map findDetails(long accountId) { GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); - sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); + sc.and(sc.entity().getAccountId(), Op.EQ, accountId); List results = sc.list(); Map details = new HashMap(results.size()); for (AccountDetailVO r : results) { @@ -73,8 +73,8 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public AccountDetailVO findDetail(long accountId, String name) { GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); - sc.addAnd(sc.getEntity().getAccountId(), Op.EQ, accountId); - sc.addAnd(sc.getEntity().getName(), Op.EQ, name); + sc.and(sc.entity().getAccountId(), Op.EQ, accountId); + sc.and(sc.entity().getName(), Op.EQ, name); return sc.find(); } diff --git a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index ccf9a1f93f1..54a107b5a92 100644 --- a/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/schema/src/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -35,12 +35,11 @@ import com.cloud.storage.StoragePoolStatus; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.QueryBuilder; 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.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @@ -316,10 +315,10 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase public List findZoneWideStoragePoolsByTags(long dcId, String[] tags) { List storagePools = null; if (tags == null || tags.length == 0) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StoragePoolVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); + QueryBuilder sc = QueryBuilder.create(StoragePoolVO.class); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); + sc.and(sc.entity().getStatus(), Op.EQ,Status.Up); + sc.and(sc.entity().getScope(), Op.EQ,ScopeType.ZONE); return sc.list(); } else { Map details = tagsToDetails(tags); @@ -421,11 +420,11 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase @Override public List findZoneWideStoragePoolsByHypervisor(long dataCenterId, HypervisorType hypervisorType) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StoragePoolVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dataCenterId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getScope(), Op.EQ, ScopeType.ZONE); - sc.addAnd(sc.getEntity().getHypervisor(), Op.EQ, hypervisorType); + QueryBuilder sc = QueryBuilder.create(StoragePoolVO.class); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dataCenterId); + sc.and(sc.entity().getStatus(), Op.EQ,Status.Up); + sc.and(sc.entity().getScope(), Op.EQ,ScopeType.ZONE); + sc.and(sc.entity().getHypervisor(), Op.EQ,hypervisorType); return sc.list(); } } diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java index e869714783d..7f335c53315 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheManagerImpl.java @@ -18,35 +18,46 @@ */ package org.apache.cloudstack.storage.cache.manager; -import com.cloud.configuration.Config; -import com.cloud.storage.DataStoreRole; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.Manager; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.exception.CloudRuntimeException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; -import org.apache.cloudstack.engine.subsystem.api.storage.*; +import javax.inject.Inject; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.engine.subsystem.api.storage.CopyCommandResult; +import org.apache.cloudstack.engine.subsystem.api.storage.DataMotionService; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; +import org.apache.cloudstack.engine.subsystem.api.storage.Scope; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; import org.apache.cloudstack.framework.async.AsyncCallFuture; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.storage.cache.allocator.StorageCacheAllocator; import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager; import org.apache.cloudstack.storage.datastore.db.ImageStoreVO; -import org.apache.log4j.Logger; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; +import com.cloud.configuration.Config; +import com.cloud.storage.DataStoreRole; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.component.Manager; +import com.cloud.utils.concurrency.NamedThreadFactory; +import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.QueryBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.exception.CloudRuntimeException; public class StorageCacheManagerImpl implements StorageCacheManager, Manager { private static final Logger s_logger = Logger.getLogger(StorageCacheManagerImpl.class); @@ -79,8 +90,8 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { } protected List getCacheStores() { - GenericQueryBuilder sc = GenericQueryBuilder.create(ImageStoreVO.class); - sc.addAnd(sc.getEntity().getRole(), SearchCriteria.Op.EQ, DataStoreRole.ImageCache); + QueryBuilder sc = QueryBuilder.create(ImageStoreVO.class); + sc.and(sc.entity().getRole(), SearchCriteria.Op.EQ,DataStoreRole.ImageCache); List imageStoreVOs = sc.list(); List stores = new ArrayList(); for (ImageStoreVO vo : imageStoreVOs) { @@ -232,7 +243,7 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { @Override public DataObject createCacheObject(DataObject data, Scope scope) { - DataStore cacheStore = this.getCacheStorage(scope); + DataStore cacheStore = getCacheStorage(scope); if (cacheStore == null) { @@ -244,7 +255,7 @@ public class StorageCacheManagerImpl implements StorageCacheManager, Manager { @Override public DataObject getCacheObject(DataObject data, Scope scope) { - DataStore cacheStore = this.getCacheStorage(scope); + DataStore cacheStore = getCacheStorage(scope); DataObject objOnCacheStore = cacheStore.create(data); objOnCacheStore.incRefCount(); return objOnCacheStore; diff --git a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java index c59b0604b93..fc96a0da5ea 100644 --- a/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java +++ b/engine/storage/cache/src/org/apache/cloudstack/storage/cache/manager/StorageCacheReplacementAlgorithmLRU.java @@ -17,27 +17,29 @@ * under the License. */ package org.apache.cloudstack.storage.cache.manager; -import com.cloud.configuration.Config; -import com.cloud.utils.DateUtil; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; - -import org.apache.cloudstack.engine.subsystem.api.storage.*; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; -import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; -import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; - -import org.apache.commons.lang.math.NumberUtils; - import java.util.Calendar; import java.util.Date; import javax.annotation.PostConstruct; import javax.inject.Inject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.TemplateDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO; +import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; + +import com.cloud.configuration.Config; +import com.cloud.utils.DateUtil; +import com.cloud.utils.NumbersUtil; +import com.cloud.utils.db.QueryBuilder; +import com.cloud.utils.db.SearchCriteria; + public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacementAlgorithm { @@ -72,33 +74,33 @@ public class StorageCacheReplacementAlgorithmLRU implements StorageCacheReplacem cal.add(Calendar.DAY_OF_MONTH, -unusedTimeInterval.intValue()); Date bef = cal.getTime(); - GenericQueryBuilder sc = GenericQueryBuilder.create(TemplateDataStoreVO.class); - sc.addAnd(sc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); - sc.addAnd(sc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); - sc.addAnd(sc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); - sc.addAnd(sc.getEntity().getDataStoreRole(), SearchCriteria.Op.EQ, store.getRole()); - sc.addAnd(sc.getEntity().getRefCnt(), SearchCriteria.Op.EQ, 0); + QueryBuilder sc = QueryBuilder.create(TemplateDataStoreVO.class); + sc.and(sc.entity().getLastUpdated(), SearchCriteria.Op.LT, bef); + sc.and(sc.entity().getState(), SearchCriteria.Op.EQ,ObjectInDataStoreStateMachine.State.Ready); + sc.and(sc.entity().getDataStoreId(), SearchCriteria.Op.EQ,store.getId()); + sc.and(sc.entity().getDataStoreRole(), SearchCriteria.Op.EQ,store.getRole()); + sc.and(sc.entity().getRefCnt(), SearchCriteria.Op.EQ,0); TemplateDataStoreVO template = sc.find(); if (template != null) { return templateFactory.getTemplate(template.getTemplateId(), store); } - GenericQueryBuilder volSc = GenericQueryBuilder.create(VolumeDataStoreVO.class); - volSc.addAnd(volSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); - volSc.addAnd(volSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); - volSc.addAnd(volSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); - volSc.addAnd(volSc.getEntity().getRefCnt(), SearchCriteria.Op.EQ, 0); + QueryBuilder volSc = QueryBuilder.create(VolumeDataStoreVO.class); + volSc.and(volSc.entity().getLastUpdated(), SearchCriteria.Op.LT, bef); + volSc.and(volSc.entity().getState(), SearchCriteria.Op.EQ,ObjectInDataStoreStateMachine.State.Ready); + volSc.and(volSc.entity().getDataStoreId(), SearchCriteria.Op.EQ,store.getId()); + volSc.and(volSc.entity().getRefCnt(), SearchCriteria.Op.EQ,0); VolumeDataStoreVO volume = volSc.find(); if (volume != null) { return volumeFactory.getVolume(volume.getVolumeId(), store); } - GenericQueryBuilder snapshotSc = GenericQueryBuilder.create(SnapshotDataStoreVO.class); - snapshotSc.addAnd(snapshotSc.getEntity().getLastUpdated(), SearchCriteria.Op.LT, bef); - snapshotSc.addAnd(snapshotSc.getEntity().getState(), SearchCriteria.Op.EQ, ObjectInDataStoreStateMachine.State.Ready); - snapshotSc.addAnd(snapshotSc.getEntity().getDataStoreId(), SearchCriteria.Op.EQ, store.getId()); - snapshotSc.addAnd(snapshotSc.getEntity().getRole(), SearchCriteria.Op.EQ, store.getRole()); - snapshotSc.addAnd(snapshotSc.getEntity().getRefCnt(), SearchCriteria.Op.EQ, 0); + QueryBuilder snapshotSc = QueryBuilder.create(SnapshotDataStoreVO.class); + snapshotSc.and(snapshotSc.entity().getLastUpdated(), SearchCriteria.Op.LT, bef); + snapshotSc.and(snapshotSc.entity().getState(), SearchCriteria.Op.EQ,ObjectInDataStoreStateMachine.State.Ready); + snapshotSc.and(snapshotSc.entity().getDataStoreId(), SearchCriteria.Op.EQ,store.getId()); + snapshotSc.and(snapshotSc.entity().getRole(), SearchCriteria.Op.EQ,store.getRole()); + snapshotSc.and(snapshotSc.entity().getRefCnt(), SearchCriteria.Op.EQ,0); SnapshotDataStoreVO snapshot = snapshotSc.find(); if (snapshot != null) { return snapshotFactory.getSnapshot(snapshot.getSnapshotId(), store); diff --git a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java index dcdc9382800..3f35e1dd5bc 100644 --- a/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java +++ b/engine/storage/snapshot/src/org/apache/cloudstack/storage/snapshot/SnapshotObject.java @@ -22,14 +22,21 @@ import java.util.Date; import javax.inject.Inject; -import org.apache.cloudstack.engine.subsystem.api.storage.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.datastore.ObjectInDataStoreManager; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.cloudstack.storage.to.SnapshotObjectTO; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.to.DataObjectType; @@ -42,9 +49,8 @@ import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -83,19 +89,19 @@ public class SnapshotObject implements SnapshotInfo { } public DataStore getStore() { - return this.store; + return store; } @Override public SnapshotInfo getParent() { - SnapshotDataStoreVO snapStoreVO = this.snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), - this.store.getId(), this.snapshot.getId()); + SnapshotDataStoreVO snapStoreVO = snapshotStoreDao.findByStoreSnapshot(store.getRole(), + store.getId(), snapshot.getId()); Long parentId = null; if (snapStoreVO != null) { parentId = snapStoreVO.getParentSnapshotId(); if (parentId != null && parentId != 0) { - return this.snapshotFactory.getSnapshot(parentId, store); + return snapshotFactory.getSnapshot(parentId, store); } } @@ -104,42 +110,41 @@ public class SnapshotObject implements SnapshotInfo { @Override public SnapshotInfo getChild() { - GenericQueryBuilder sc = GenericQueryBuilder - .create(SnapshotDataStoreVO.class); - sc.addAnd(sc.getEntity().getDataStoreId(), Op.EQ, this.store.getId()); - sc.addAnd(sc.getEntity().getRole(), Op.EQ, this.store.getRole()); - sc.addAnd(sc.getEntity().getState(), Op.NIN, State.Destroying, State.Destroyed, State.Error); - sc.addAnd(sc.getEntity().getParentSnapshotId(), Op.EQ, this.getId()); + QueryBuilder sc = QueryBuilder.create(SnapshotDataStoreVO.class); + sc.and(sc.entity().getDataStoreId(), Op.EQ,store.getId()); + sc.and(sc.entity().getRole(), Op.EQ,store.getRole()); + sc.and(sc.entity().getState(), Op.NIN, State.Destroying, State.Destroyed, State.Error); + sc.and(sc.entity().getParentSnapshotId(), Op.EQ,getId()); SnapshotDataStoreVO vo = sc.find(); if (vo == null) { return null; } - return this.snapshotFactory.getSnapshot(vo.getId(), store); + return snapshotFactory.getSnapshot(vo.getId(), store); } @Override public VolumeInfo getBaseVolume() { - return volFactory.getVolume(this.snapshot.getVolumeId()); + return volFactory.getVolume(snapshot.getVolumeId()); } @Override public long getId() { - return this.snapshot.getId(); + return snapshot.getId(); } @Override public String getUri() { - return this.snapshot.getUuid(); + return snapshot.getUuid(); } @Override public DataStore getDataStore() { - return this.store; + return store; } @Override public Long getSize() { - return this.snapshot.getSize(); + return snapshot.getSize(); } @Override @@ -149,7 +154,7 @@ public class SnapshotObject implements SnapshotInfo { @Override public String getUuid() { - return this.snapshot.getUuid(); + return snapshot.getUuid(); } @Override @@ -168,17 +173,17 @@ public class SnapshotObject implements SnapshotInfo { @Override public long getAccountId() { - return this.snapshot.getAccountId(); + return snapshot.getAccountId(); } @Override public long getVolumeId() { - return this.snapshot.getVolumeId(); + return snapshot.getVolumeId(); } @Override public String getPath() { - DataObjectInStore objectInStore = this.objectInStoreMgr.findObject(this, getDataStore()); + DataObjectInStore objectInStore = objectInStoreMgr.findObject(this, getDataStore()); if (objectInStore != null) { return objectInStore.getInstallPath(); } @@ -187,60 +192,60 @@ public class SnapshotObject implements SnapshotInfo { @Override public String getName() { - return this.snapshot.getName(); + return snapshot.getName(); } @Override public Date getCreated() { - return this.snapshot.getCreated(); + return snapshot.getCreated(); } @Override public Type getRecurringType() { - return this.snapshot.getRecurringType(); + return snapshot.getRecurringType(); } @Override public State getState() { - return this.snapshot.getState(); + return snapshot.getState(); } @Override public HypervisorType getHypervisorType() { - return this.snapshot.getHypervisorType(); + return snapshot.getHypervisorType(); } @Override public boolean isRecursive() { - return this.snapshot.isRecursive(); + return snapshot.isRecursive(); } @Override public short getsnapshotType() { - return this.snapshot.getsnapshotType(); + return snapshot.getsnapshotType(); } @Override public long getDomainId() { - return this.snapshot.getDomainId(); + return snapshot.getDomainId(); } @Override public Long getDataCenterId() { - return this.snapshot.getDataCenterId(); + return snapshot.getDataCenterId(); } public void processEvent(Snapshot.Event event) throws NoTransitionException { - stateMachineMgr.processEvent(this.snapshot, event); + stateMachineMgr.processEvent(snapshot, event); } public SnapshotVO getSnapshotVO() { - return this.snapshot; + return snapshot; } @Override public DataTO getTO() { - DataTO to = this.store.getDriver().getTO(this); + DataTO to = store.getDriver().getTO(this); if (to == null) { return new SnapshotObjectTO(this); } @@ -250,28 +255,28 @@ public class SnapshotObject implements SnapshotInfo { @Override public void processEvent(ObjectInDataStoreStateMachine.Event event, Answer answer) { try { - SnapshotDataStoreVO snapshotStore = this.snapshotStoreDao.findByStoreSnapshot( - this.getDataStore().getRole(), this.getDataStore().getId(), this.getId()); + SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findByStoreSnapshot( + getDataStore().getRole(), getDataStore().getId(), getId()); if (answer instanceof CreateObjectAnswer) { SnapshotObjectTO snapshotTO = (SnapshotObjectTO) ((CreateObjectAnswer) answer).getData(); snapshotStore.setInstallPath(snapshotTO.getPath()); - this.snapshotStoreDao.update(snapshotStore.getId(), snapshotStore); + snapshotStoreDao.update(snapshotStore.getId(), snapshotStore); } else if (answer instanceof CopyCmdAnswer) { SnapshotObjectTO snapshotTO = (SnapshotObjectTO) ((CopyCmdAnswer) answer).getNewData(); snapshotStore.setInstallPath(snapshotTO.getPath()); if (snapshotTO.getParentSnapshotPath() == null) { snapshotStore.setParentSnapshotId(0L); } - this.snapshotStoreDao.update(snapshotStore.getId(), snapshotStore); + snapshotStoreDao.update(snapshotStore.getId(), snapshotStore); // update side-effect of snapshot operation if(snapshotTO.getVolume() != null && snapshotTO.getVolume().getPath() != null) { - VolumeVO vol = this.volumeDao.findByUuid(snapshotTO.getVolume().getUuid()); + VolumeVO vol = volumeDao.findByUuid(snapshotTO.getVolume().getUuid()); if(vol != null) { s_logger.info("Update volume path change due to snapshot operation, volume " + vol.getId() + " path: " + vol.getPath() + "->" + snapshotTO.getVolume().getPath()); vol.setPath(snapshotTO.getVolume().getPath()); - this.volumeDao.update(vol.getId(), vol); + volumeDao.update(vol.getId(), vol); } else { s_logger.error("Cound't find the original volume with uuid: " + snapshotTO.getVolume().getUuid()); } @@ -290,13 +295,13 @@ public class SnapshotObject implements SnapshotInfo { @Override public void incRefCount() { - if (this.store == null) { + if (store == null) { return; } - if (this.store.getRole() == DataStoreRole.Image || this.store.getRole() == DataStoreRole.ImageCache) { + if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) { SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), - this.getId()); + getId()); store.incrRefCnt(); store.setLastUpdated(new Date()); snapshotStoreDao.update(store.getId(), store); @@ -305,12 +310,12 @@ public class SnapshotObject implements SnapshotInfo { @Override public void decRefCount() { - if (this.store == null) { + if (store == null) { return; } - if (this.store.getRole() == DataStoreRole.Image || this.store.getRole() == DataStoreRole.ImageCache) { + if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) { SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), - this.getId()); + getId()); store.decrRefCnt(); store.setLastUpdated(new Date()); snapshotStoreDao.update(store.getId(), store); @@ -319,12 +324,12 @@ public class SnapshotObject implements SnapshotInfo { @Override public Long getRefCount() { - if (this.store == null) { + if (store == null) { return null; } - if (this.store.getRole() == DataStoreRole.Image || this.store.getRole() == DataStoreRole.ImageCache) { + if (store.getRole() == DataStoreRole.Image || store.getRole() == DataStoreRole.ImageCache) { SnapshotDataStoreVO store = snapshotStoreDao.findByStoreSnapshot(this.store.getRole(), this.store.getId(), - this.getId()); + getId()); return store.getRefCnt(); } return null; @@ -332,7 +337,7 @@ public class SnapshotObject implements SnapshotInfo { @Override public ObjectInDataStoreStateMachine.State getStatus() { - return this.objectInStoreMgr.findObject(this, store).getObjectInStoreState(); + return objectInStoreMgr.findObject(this, store).getObjectInStoreState(); } @Override diff --git a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index 118db802060..fdc12bf1cee 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -45,8 +45,8 @@ import com.cloud.host.dao.HostDao; import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; @@ -220,12 +220,12 @@ public class DefaultEndPointSelector implements EndPointSelector { } private List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); if (dcId != null) { - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); } - sc.addAnd(sc.getEntity().getStatus(), Op.IN, com.cloud.host.Status.Up, com.cloud.host.Status.Connecting); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorageVM); + sc.and(sc.entity().getStatus(), Op.IN, Status.Up, Status.Connecting); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.SecondaryStorageVM); return sc.list(); } @@ -258,9 +258,9 @@ public class DefaultEndPointSelector implements EndPointSelector { endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), host.getPublicIpAddress())); } else if (store.getScope().getScopeType() == ScopeType.CLUSTER) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, store.getScope().getScopeId()); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getClusterId(), Op.EQ, store.getScope().getScopeId()); + sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); List hosts = sc.list(); for (HostVO host : hosts) { endPoints.add(RemoteHostEndPoint.getHypervisorHostEndPoint(host.getId(), host.getPrivateIpAddress(), diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java index 20bc7095149..456471bb93c 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java @@ -52,8 +52,8 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = GenericQueryBuilder .create(TemplatePrimaryDataStoreVO.class); - sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); - sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); + sc.and(sc.entity().getTemplateId(), Op.EQ, templateId); + sc.and(sc.entity().getPoolId(), Op.EQ, poolId); return sc.find(); } @@ -61,9 +61,9 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = GenericQueryBuilder .create(TemplatePrimaryDataStoreVO.class); - sc.addAnd(sc.getEntity().getTemplateId(), Op.EQ, templateId); - sc.addAnd(sc.getEntity().getPoolId(), Op.EQ, poolId); - sc.addAnd(sc.getEntity().getState(), Op.EQ, ObjectInDataStoreStateMachine.State.Ready); + sc.and(sc.entity().getTemplateId(), Op.EQ, templateId); + sc.and(sc.entity().getPoolId(), Op.EQ, poolId); + sc.and(sc.entity().getState(), Op.EQ, ObjectInDataStoreStateMachine.State.Ready); return sc.find(); } diff --git a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java index 1dabbf81a48..8581d80dc63 100755 --- a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java @@ -66,23 +66,21 @@ public class GenericQueryBuilder extends SearchBase { _specifiedAttrs.clear(); } - private void setParameters(String conditionName, Object... params) { - assert _conditions.contains(new Condition(conditionName)) : "Couldn't find " + conditionName; - _params.put(conditionName, params); - } - - public void addAnd(Object useless, Op op, Object... values) { + public void and(Object useless, Op op, Object... values) { String uuid = UUID.randomUUID().toString(); - constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op); - setParameters(uuid, values); + Condition condition = constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op); + condition.setPresets(values); } + @SuppressWarnings("unchecked") public List list() { finalize(); - SearchCriteria sc1 = create(); if (isSelectAll()) { + @SuppressWarnings("rawtypes") + SearchCriteria sc1 = create(); return (List)_dao.search(sc1, null); } else { + SearchCriteria sc1 = create(); return _dao.customSearch(sc1, null); } } @@ -91,60 +89,13 @@ public class GenericQueryBuilder extends SearchBase { return _selects == null || _selects.size() == 0; } - public T getEntity() { - return _entity; - } - + @SuppressWarnings("unchecked") public K find() { - assert isSelectAll() : "find doesn't support select search"; finalize(); + @SuppressWarnings("rawtypes") SearchCriteria sc1 = create(); return (K)_dao.findOneBy(sc1); } - public Preset and(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - - public Preset where(Object useless, Op op) { - return and(useless, op); - } - - public Preset left(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - - public Preset op(Object useless, Op op) { - return left(useless, op); - } - - public Preset openParen(Object useless, Op op) { - return left(useless, op); - } - - public Preset or(Object useless, Op op) { - Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op); - return new Preset(this, condition); - } - - public class Preset { - GenericQueryBuilder builder; - Condition condition; - - protected Preset(GenericQueryBuilder builder, Condition condition) { - this.builder = builder; - this.condition = condition; - } - - public GenericQueryBuilder values(Object... params) { - if (condition.op.getParams() > 0 && condition.op.params != params.length) { - throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op); - } - condition.setPresets(params); - return builder; - } - } } diff --git a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java index 16c77f1205e..8e46c30ebf7 100755 --- a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java @@ -19,6 +19,7 @@ package com.cloud.utils.db; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; +import java.util.UUID; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @@ -131,6 +132,11 @@ public class GenericSearchBuilder extends SearchBase { return this; } + public Preset and(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " AND ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + public GenericSearchBuilder and() { constructCondition(null, " AND ", null, null); return this; @@ -153,6 +159,10 @@ public class GenericSearchBuilder extends SearchBase { return and(name, useless, op); } + public Preset where(Object useless, Op op) { + return and(useless, op); + } + public GenericSearchBuilder left(String name, Object useless, Op op) { constructCondition(name, " ( ", _specifiedAttrs.get(0), op); return this; @@ -163,10 +173,19 @@ public class GenericSearchBuilder extends SearchBase { return this; } + public Preset left(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + public GenericSearchBuilder op(Object useless, Op op, String name) { return left(useless, op, name); } + public Preset op(Object useless, Op op) { + return left(useless, op); + } + public GenericSearchBuilder op(String name, Object useless, Op op) { return left(name, useless, op); } @@ -179,6 +198,10 @@ public class GenericSearchBuilder extends SearchBase { return left(name, useless, op); } + public Preset openParen(Object useless, Op op) { + return left(useless, op); + } + public GroupBy, T, K> groupBy(Object... useless) { assert _groupBy == null : "Can't do more than one group bys"; GroupBy, T, K> groupBy = new GroupBy, T, K>(this); @@ -205,6 +228,11 @@ public class GenericSearchBuilder extends SearchBase { return this; } + public Preset or(Object useless, Op op) { + Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op); + return new Preset(this, condition); + } + public GenericSearchBuilder join(String name, GenericSearchBuilder builder, Object useless, Object useless2, JoinBuilder.JoinType joinType) { assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; assert _specifiedAttrs.size() == 1 : "You didn't select the attribute."; @@ -251,4 +279,21 @@ public class GenericSearchBuilder extends SearchBase { super.finalize(); } + public class Preset { + GenericSearchBuilder builder; + Condition condition; + + protected Preset(GenericSearchBuilder builder, Condition condition) { + this.builder = builder; + this.condition = condition; + } + + public GenericSearchBuilder values(Object... params) { + if (condition.op.getParams() > 0 && condition.op.params != params.length) { + throw new RuntimeException("The # of parameters set " + params.length + " does not match # of parameters required by " + condition.op); + } + condition.setPresets(params); + return builder; + } + } } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java index 783755d2fde..c8a178e6a41 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java @@ -85,8 +85,8 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements @Override public boolean prepare(VirtualMachineProfile profile, NicProfile pxeNic, DeployDestination dest, ReservationContext context) { GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); - sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.PING.toString()); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, dest.getPod().getId()); + sc.and(sc.entity().getDeviceType(), Op.EQ, BaremetalPxeType.PING.toString()); + sc.and(sc.entity().getPodId(), Op.EQ, dest.getPod().getId()); BaremetalPxeVO pxeVo = sc.find(); if (pxeVo == null) { throw new CloudRuntimeException("No PING PXE server found in pod: " + dest.getPod().getId() + ", you need to add it before starting VM"); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java index 5459918b14a..6cf94f2db94 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpElement.java @@ -5,19 +5,28 @@ // 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. -// +// // Automatically generated by addcopyright.py at 01/29/2013 package com.cloud.baremetal.networkservice; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.ejb.Local; +import javax.inject.Inject; + +import org.apache.log4j.Logger; + import com.cloud.baremetal.database.BaremetalDhcpVO; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Pod; @@ -39,20 +48,15 @@ import com.cloud.network.element.NetworkElement; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; -import com.cloud.vm.*; +import com.cloud.vm.NicProfile; +import com.cloud.vm.NicVO; +import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine.Type; +import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.NicDao; -import org.apache.log4j.Logger; - -import javax.ejb.Local; -import javax.inject.Inject; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; @Local(value = NetworkElement.class) public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProvider { @@ -84,8 +88,8 @@ public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProv private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { Pod pod = dest.getPod(); if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) { - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalDhcpVO.class); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, pod.getId()); + QueryBuilder sc = QueryBuilder.create(BaremetalDhcpVO.class); + sc.and(sc.entity().getPodId(), Op.EQ,pod.getId()); return sc.find() != null; } @@ -159,6 +163,7 @@ public class BaremetalDhcpElement extends AdapterBase implements DhcpServiceProv return true; } + @Override public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (vm.getHypervisorType() != HypervisorType.BareMetal || !canHandle(dest, network.getTrafficType(), network.getGuestType())) { diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java index 9ab714dfe88..930ca1bf609 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java @@ -313,7 +313,7 @@ public class BaremetalDhcpManagerImpl extends ManagerBase implements BaremetalDh GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalDhcpVO.class); if (cmd.getDeviceType() != null) { - sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, cmd.getDeviceType()); + sc.and(sc.entity().getDeviceType(), Op.EQ, cmd.getDeviceType()); } List vos = sc.list(); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java index b4af709965f..661f39134c7 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java @@ -88,8 +88,8 @@ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase imple public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) { NetworkVO nwVO = _nwDao.findById(nic.getNetworkId()); GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); - sc.addAnd(sc.getEntity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); - sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); + sc.and(sc.entity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); + sc.and(sc.entity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); BaremetalPxeVO pxeVo = sc.find(); if (pxeVo == null) { throw new CloudRuntimeException("No kickstart PXE server found in pod: " + dest.getPod().getId() + ", you need to add it before starting VM"); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java index 3e0572ad0e7..f869fe65461 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java @@ -92,7 +92,7 @@ public class BaremetalPxeElement extends AdapterBase implements NetworkElement { Pod pod = dest.getPod(); if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) { GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, pod.getId()); + sc.and(sc.entity().getPodId(), Op.EQ, pod.getId()); return sc.find() != null; } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java index 16147562156..ae3898bc315 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java @@ -223,7 +223,7 @@ public class BaremetalPxeManagerImpl extends ManagerBase implements BaremetalPxe GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); //TODO: handle both kickstart and PING //sc.addAnd(sc.getEntity().getPodId(), Op.EQ, vm.getPodIdToDeployIn()); - sc.addAnd(sc.getEntity().getPhysicalNetworkId(), Op.EQ, phy.getId()); + sc.and(sc.entity().getPhysicalNetworkId(), Op.EQ, phy.getId()); BaremetalPxeVO pxeVo = sc.find(); if (pxeVo == null) { throw new CloudRuntimeException("No PXE server found in pod: " + vm.getPodIdToDeployIn() + ", you need to add it before starting VM"); diff --git a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java index d8b83109359..eba7ae56ef6 100755 --- a/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java +++ b/plugins/hypervisors/ovm/src/com/cloud/ovm/hypervisor/OvmDiscoverer.java @@ -31,9 +31,9 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; -import com.cloud.configuration.Config; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; +import com.cloud.configuration.Config; import com.cloud.dc.ClusterVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.exception.DiscoveryException; @@ -48,244 +48,214 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.ssh.SSHCmdHelper; @Local(value = Discoverer.class) -public class OvmDiscoverer extends DiscovererBase implements Discoverer, - ResourceStateAdapter { - private static final Logger s_logger = Logger - .getLogger(OvmDiscoverer.class); - protected String _publicNetworkDevice; - protected String _privateNetworkDevice; - protected String _guestNetworkDevice; +public class OvmDiscoverer extends DiscovererBase implements Discoverer, ResourceStateAdapter { + private static final Logger s_logger = Logger.getLogger(OvmDiscoverer.class); + protected String _publicNetworkDevice; + protected String _privateNetworkDevice; + protected String _guestNetworkDevice; - @Inject - ClusterDao _clusterDao; - @Inject - ResourceManager _resourceMgr; + @Inject + ClusterDao _clusterDao; + @Inject + ResourceManager _resourceMgr; - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - super.configure(name, params); - _publicNetworkDevice = _params.get(Config.OvmPublicNetwork.key()); - _privateNetworkDevice = _params.get(Config.OvmPrivateNetwork.key()); - _guestNetworkDevice = _params.get(Config.OvmGuestNetwork.key()); - _resourceMgr.registerResourceStateAdapter(this.getClass() - .getSimpleName(), this); - return true; - } + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + _publicNetworkDevice = _params.get(Config.OvmPublicNetwork.key()); + _privateNetworkDevice = _params.get(Config.OvmPrivateNetwork.key()); + _guestNetworkDevice = _params.get(Config.OvmGuestNetwork.key()); + _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); + return true; + } - protected OvmDiscoverer() { - } + protected OvmDiscoverer() { + } - @Override - public boolean stop() { - _resourceMgr.unregisterResourceStateAdapter(this.getClass() - .getSimpleName()); - return super.stop(); - } + @Override + public boolean stop() { + _resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName()); + return super.stop(); + } - private boolean checkIfExisted(String guid) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getGuid(), SearchCriteria.Op.EQ, guid); - sc.addAnd(sc.getEntity().getHypervisorType(), SearchCriteria.Op.EQ, - HypervisorType.Ovm); - List hosts = sc.list(); - return !hosts.isEmpty(); - } + private boolean checkIfExisted(String guid) { + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getGuid(), SearchCriteria.Op.EQ, guid); + sc.and(sc.entity().getHypervisorType(), SearchCriteria.Op.EQ, HypervisorType.Ovm); + List hosts = sc.list(); + return !hosts.isEmpty(); + } - @Override - public Map> find(long dcId, - Long podId, Long clusterId, URI url, String username, - String password, List hostTags) throws DiscoveryException { - Connection conn = null; + @Override + public Map> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List hostTags) + throws DiscoveryException { + Connection conn = null; - if (!url.getScheme().equals("http")) { - String msg = "urlString is not http so we're not taking care of the discovery for this: " - + url; - s_logger.debug(msg); - return null; - } - if (clusterId == null) { - String msg = "must specify cluster Id when add host"; - s_logger.debug(msg); - throw new CloudRuntimeException(msg); - } + if (!url.getScheme().equals("http")) { + String msg = "urlString is not http so we're not taking care of the discovery for this: " + url; + s_logger.debug(msg); + return null; + } + if (clusterId == null) { + String msg = "must specify cluster Id when add host"; + s_logger.debug(msg); + throw new CloudRuntimeException(msg); + } - if (podId == null) { - String msg = "must specify pod Id when add host"; - s_logger.debug(msg); - throw new CloudRuntimeException(msg); - } + if (podId == null) { + String msg = "must specify pod Id when add host"; + s_logger.debug(msg); + throw new CloudRuntimeException(msg); + } - ClusterVO cluster = _clusterDao.findById(clusterId); - if (cluster == null - || (cluster.getHypervisorType() != HypervisorType.Ovm)) { - if (s_logger.isInfoEnabled()) - s_logger.info("invalid cluster id or cluster is not for Ovm hypervisors"); - return null; - } + ClusterVO cluster = _clusterDao.findById(clusterId); + if (cluster == null || (cluster.getHypervisorType() != HypervisorType.Ovm)) { + if (s_logger.isInfoEnabled()) + s_logger.info("invalid cluster id or cluster is not for Ovm hypervisors"); + return null; + } - String agentUsername = _params.get("agentusername"); - if (agentUsername == null) { - throw new CloudRuntimeException("Agent user name must be specified"); - } + String agentUsername = _params.get("agentusername"); + if (agentUsername == null) { + throw new CloudRuntimeException("Agent user name must be specified"); + } - String agentPassword = _params.get("agentpassword"); - if (agentPassword == null) { - throw new CloudRuntimeException("Agent password must be specified"); - } + String agentPassword = _params.get("agentpassword"); + if (agentPassword == null) { + throw new CloudRuntimeException("Agent password must be specified"); + } - try { - String hostname = url.getHost(); - InetAddress ia = InetAddress.getByName(hostname); - String hostIp = ia.getHostAddress(); - String guid = UUID.nameUUIDFromBytes(hostIp.getBytes()).toString(); + try { + String hostname = url.getHost(); + InetAddress ia = InetAddress.getByName(hostname); + String hostIp = ia.getHostAddress(); + String guid = UUID.nameUUIDFromBytes(hostIp.getBytes()).toString(); - if (checkIfExisted(guid)) { - throw new CloudRuntimeException("The host " + hostIp - + " has been added before"); - } + if (checkIfExisted(guid)) { + throw new CloudRuntimeException("The host " + hostIp + " has been added before"); + } - s_logger.debug("Ovm discover is going to disover host having guid " - + guid); + s_logger.debug("Ovm discover is going to disover host having guid " + guid); - ClusterVO clu = _clusterDao.findById(clusterId); - if (clu.getGuid() == null) { - clu.setGuid(UUID.randomUUID().toString()); - _clusterDao.update(clusterId, clu); - } + ClusterVO clu = _clusterDao.findById(clusterId); + if (clu.getGuid() == null) { + clu.setGuid(UUID.randomUUID().toString()); + _clusterDao.update(clusterId, clu); + } - com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection( - hostIp, 22); - sshConnection.connect(null, 60000, 60000); - sshConnection = SSHCmdHelper.acquireAuthorizedConnection(hostIp, - username, password); - if (sshConnection == null) { - throw new DiscoveryException( - String.format( - "Cannot connect to ovm host(IP=%1$s, username=%2$s, password=%3$s, discover failed", - hostIp, username, password)); - } + com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hostIp, 22); + sshConnection.connect(null, 60000, 60000); + sshConnection = SSHCmdHelper.acquireAuthorizedConnection(hostIp, username, password); + if (sshConnection == null) { + throw new DiscoveryException(String.format("Cannot connect to ovm host(IP=%1$s, username=%2$s, password=%3$s, discover failed", hostIp, username, password)); + } - if (!SSHCmdHelper.sshExecuteCmd(sshConnection, - "[ -f '/etc/ovs-agent/agent.ini' ]")) { - throw new DiscoveryException( - "Can not find /etc/ovs-agent/agent.ini " + hostIp); - } + if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "[ -f '/etc/ovs-agent/agent.ini' ]")) { + throw new DiscoveryException("Can not find /etc/ovs-agent/agent.ini " + hostIp); + } - Map details = new HashMap(); - OvmResourceBase ovmResource = new OvmResourceBase(); - details.put("ip", hostIp); - details.put("username", username); - details.put("password", password); - details.put("zone", Long.toString(dcId)); - details.put("guid", guid); - details.put("pod", Long.toString(podId)); - details.put("cluster", Long.toString(clusterId)); - details.put("agentusername", agentUsername); - details.put("agentpassword", agentPassword); - if (_publicNetworkDevice != null) { - details.put("public.network.device", _publicNetworkDevice); - } - if (_privateNetworkDevice != null) { - details.put("private.network.device", _privateNetworkDevice); - } - if (_guestNetworkDevice != null) { - details.put("guest.network.device", _guestNetworkDevice); - } + Map details = new HashMap(); + OvmResourceBase ovmResource = new OvmResourceBase(); + details.put("ip", hostIp); + details.put("username", username); + details.put("password", password); + details.put("zone", Long.toString(dcId)); + details.put("guid", guid); + details.put("pod", Long.toString(podId)); + details.put("cluster", Long.toString(clusterId)); + details.put("agentusername", agentUsername); + details.put("agentpassword", agentPassword); + if (_publicNetworkDevice != null) { + details.put("public.network.device", _publicNetworkDevice); + } + if (_privateNetworkDevice != null) { + details.put("private.network.device", _privateNetworkDevice); + } + if (_guestNetworkDevice != null) { + details.put("guest.network.device", _guestNetworkDevice); + } - Map params = new HashMap(); - params.putAll(details); - ovmResource.configure("Ovm Server", params); - ovmResource.start(); + Map params = new HashMap(); + params.putAll(details); + ovmResource.configure("Ovm Server", params); + ovmResource.start(); - conn = new Connection(hostIp, "oracle", agentPassword); - /* After resource start, we are able to execute our agent api */ - OvmHost.Details d = OvmHost.getDetails(conn); - details.put("agentVersion", d.agentVersion); - details.put(HostInfo.HOST_OS_KERNEL_VERSION, d.dom0KernelVersion); - details.put(HostInfo.HYPERVISOR_VERSION, d.hypervisorVersion); + conn = new Connection(hostIp, "oracle", agentPassword); + /* After resource start, we are able to execute our agent api */ + OvmHost.Details d = OvmHost.getDetails(conn); + details.put("agentVersion", d.agentVersion); + details.put(HostInfo.HOST_OS_KERNEL_VERSION, d.dom0KernelVersion); + details.put(HostInfo.HYPERVISOR_VERSION, d.hypervisorVersion); - Map> resources = new HashMap>(); - resources.put(ovmResource, details); - return resources; - } catch (XmlRpcException e) { - s_logger.debug("XmlRpc exception, Unable to discover OVM: " + url, - e); - return null; - } catch (UnknownHostException e) { - s_logger.debug( - "Host name resolve failed exception, Unable to discover OVM: " - + url, e); - return null; - } catch (ConfigurationException e) { - s_logger.debug( - "Configure resource failed, Unable to discover OVM: " + url, - e); - return null; - } catch (Exception e) { - s_logger.debug("Unable to discover OVM: " + url, e); - return null; - } - } + Map> resources = new HashMap>(); + resources.put(ovmResource, details); + return resources; + } catch (XmlRpcException e) { + s_logger.debug("XmlRpc exception, Unable to discover OVM: " + url, e); + return null; + } catch (UnknownHostException e) { + s_logger.debug("Host name resolve failed exception, Unable to discover OVM: " + url, e); + return null; + } catch (ConfigurationException e) { + s_logger.debug("Configure resource failed, Unable to discover OVM: " + url, e); + return null; + } catch (Exception e) { + s_logger.debug("Unable to discover OVM: " + url, e); + return null; + } + } - @Override - public void postDiscovery(List hosts, long msId) - throws DiscoveryException { - // TODO Auto-generated method stub + @Override + public void postDiscovery(List hosts, long msId) throws DiscoveryException { + // TODO Auto-generated method stub - } + } - @Override - public boolean matchHypervisor(String hypervisor) { - return HypervisorType.Ovm.toString().equalsIgnoreCase(hypervisor); - } + @Override + public boolean matchHypervisor(String hypervisor) { + return HypervisorType.Ovm.toString().equalsIgnoreCase(hypervisor); + } - @Override - public HypervisorType getHypervisorType() { - return HypervisorType.Ovm; - } + @Override + public HypervisorType getHypervisorType() { + return HypervisorType.Ovm; + } - @Override - public HostVO createHostVOForConnectedAgent(HostVO host, - StartupCommand[] cmd) { - // TODO Auto-generated method stub - return null; - } + @Override + public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) { + // TODO Auto-generated method stub + return null; + } - @Override - public HostVO createHostVOForDirectConnectAgent(HostVO host, - StartupCommand[] startup, ServerResource resource, - Map details, List hostTags) { - StartupCommand firstCmd = startup[0]; - if (!(firstCmd instanceof StartupRoutingCommand)) { - return null; - } + @Override + public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map details, List hostTags) { + StartupCommand firstCmd = startup[0]; + if (!(firstCmd instanceof StartupRoutingCommand)) { + return null; + } - StartupRoutingCommand ssCmd = ((StartupRoutingCommand) firstCmd); - if (ssCmd.getHypervisorType() != HypervisorType.Ovm) { - return null; - } + StartupRoutingCommand ssCmd = ((StartupRoutingCommand)firstCmd); + if (ssCmd.getHypervisorType() != HypervisorType.Ovm) { + return null; + } - return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Ovm, - details, hostTags); - } + return _resourceMgr.fillRoutingHostVO(host, ssCmd, HypervisorType.Ovm, details, hostTags); + } - @Override - public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, - boolean isForceDeleteStorage) throws UnableDeleteHostException { - if (host.getType() != com.cloud.host.Host.Type.Routing - || host.getHypervisorType() != HypervisorType.Ovm) { - return null; - } + @Override + public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { + if (host.getType() != com.cloud.host.Host.Type.Routing || host.getHypervisorType() != HypervisorType.Ovm) { + return null; + } - _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); - return new DeleteHostAnswer(true); - } + _resourceMgr.deleteRoutingHost(host, isForced, isForceDeleteStorage); + return new DeleteHostAnswer(true); + } } diff --git a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java index bc22ba6c080..dec4a79a425 100755 --- a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java +++ b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java @@ -133,7 +133,7 @@ public class UcsManagerImpl implements UcsManager { private void syncBlades(UcsManagerVO mgr) { GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); - q.addAnd(q.getEntity().getUcsManagerId(), Op.EQ, mgr.getId()); + q.and(q.entity().getUcsManagerId(), Op.EQ, mgr.getId()); List pblades = q.list(); if (pblades.isEmpty()) { return; @@ -211,7 +211,7 @@ public class UcsManagerImpl implements UcsManager { @DB public UcsManagerResponse addUcsManager(AddUcsManagerCmd cmd) { GenericQueryBuilder q = GenericQueryBuilder.create(UcsManagerVO.class); - q.addAnd(q.getEntity().getUrl(), Op.EQ, cmd.getUrl()); + q.and(q.entity().getUrl(), Op.EQ, cmd.getUrl()); UcsManagerVO mgrvo = q.find(); if (mgrvo != null) { throw new IllegalArgumentException(String.format("duplicate UCS manager. url[%s] is used by another UCS manager already", cmd.getUrl())); @@ -343,8 +343,8 @@ public class UcsManagerImpl implements UcsManager { @Override public UcsBladeResponse associateProfileToBlade(AssociateUcsProfileToBladeCmd cmd) { GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); - q.addAnd(q.getEntity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); - q.addAnd(q.getEntity().getId(), Op.EQ, cmd.getBladeId()); + q.and(q.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); + q.and(q.entity().getId(), Op.EQ, cmd.getBladeId()); UcsBladeVO bvo = q.find(); if (bvo == null) { throw new IllegalArgumentException(String.format("cannot find UCS blade[id:%s, ucs manager id:%s]", cmd.getBladeId(), cmd.getUcsManagerId())); @@ -425,7 +425,7 @@ public class UcsManagerImpl implements UcsManager { } GenericQueryBuilder serv = GenericQueryBuilder.create(UcsManagerVO.class); - serv.addAnd(serv.getEntity().getZoneId(), Op.EQ, cmd.getZoneId()); + serv.and(serv.entity().getZoneId(), Op.EQ, cmd.getZoneId()); List vos = serv.list(); for (UcsManagerVO vo : vos) { @@ -455,7 +455,7 @@ public class UcsManagerImpl implements UcsManager { @Override public ListResponse listUcsBlades(ListUcsBladeCmd cmd) { GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); - serv.addAnd(serv.getEntity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); + serv.and(serv.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); List vos = serv.list(); List rsps = new ArrayList(vos.size()); @@ -510,7 +510,7 @@ public class UcsManagerImpl implements UcsManager { @Override public void deleteUcsManager(Long id) { GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); - serv.addAnd(serv.getEntity().getUcsManagerId(), Op.EQ, id); + serv.and(serv.entity().getUcsManagerId(), Op.EQ, id); List vos = serv.list(); for (UcsBladeVO vo : vos) { bladeDao.remove(vo.getId()); diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index 202b3405ead..bb357cabd64 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -127,7 +127,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L _clusterDao.update(cluster.getId(), cluster); } catch (EntityExistsException e) { GenericQueryBuilder sc = GenericQueryBuilder.create(ClusterVO.class); - sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); + sc.and(sc.entity().getGuid(), Op.EQ, guid); List clusters = sc.list(); ClusterVO clu = clusters.get(0); List clusterHosts = _resourceMgr.listAllHostsInCluster(clu.getId()); diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index ecd6006edad..6b719eb1476 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -85,7 +85,7 @@ import com.cloud.network.NetworkModel; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.IPAddressVO; @@ -506,7 +506,7 @@ public class ElasticLoadBalancerManagerImpl extends ManagerBase implements Elast if (provider == null) { throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId); } - VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), VirtualRouterProviderType.ElasticLoadBalancerVm); + VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm); if (vrProvider == null) { throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId()); } diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java index 35b4d52f268..7080ca34106 100644 --- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java +++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/element/InternalLoadBalancerElement.java @@ -53,7 +53,7 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.VirtualRouterProviderDao; @@ -73,9 +73,8 @@ import com.cloud.user.AccountManager; import com.cloud.user.User; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.EntityManager; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.Ip; import com.cloud.vm.DomainRouterVO; @@ -270,7 +269,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), - VirtualRouterProviderType.InternalLbVm); + Type.InternalLbVm); if (element == null) { return false; } @@ -282,7 +281,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), - VirtualRouterProviderType.InternalLbVm); + Type.InternalLbVm); if (element == null) { return true; } @@ -467,7 +466,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public VirtualRouterProvider configureInternalLoadBalancerElement(long id, boolean enable) { VirtualRouterProviderVO element = _vrProviderDao.findById(id); - if (element == null || element.getType() != VirtualRouterProviderType.InternalLbVm) { + if (element == null || element.getType() != Type.InternalLbVm) { throw new InvalidParameterValueException("Can't find " + getName() + " element with network service provider id " + id + " to be used as a provider for " + getName()); } @@ -480,7 +479,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public VirtualRouterProvider addInternalLoadBalancerElement(long ntwkSvcProviderId) { - VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(ntwkSvcProviderId, VirtualRouterProviderType.InternalLbVm); + VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(ntwkSvcProviderId, Type.InternalLbVm); if (element != null) { s_logger.debug("There is already an " + getName() + " with service provider id " + ntwkSvcProviderId); return null; @@ -491,7 +490,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala throw new InvalidParameterValueException("Invalid network service provider is specified"); } - element = new VirtualRouterProviderVO(ntwkSvcProviderId, VirtualRouterProviderType.InternalLbVm); + element = new VirtualRouterProviderVO(ntwkSvcProviderId, Type.InternalLbVm); element = _vrProviderDao.persist(element); return element; } @@ -500,7 +499,7 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public VirtualRouterProvider getInternalLoadBalancerElement(long id) { VirtualRouterProvider provider = _vrProviderDao.findById(id); - if (provider == null || provider.getType() != VirtualRouterProviderType.InternalLbVm) { + if (provider == null || provider.getType() != Type.InternalLbVm) { throw new InvalidParameterValueException("Unable to find " + getName() + " by id"); } return provider; @@ -509,19 +508,19 @@ public class InternalLoadBalancerElement extends AdapterBase implements LoadBala @Override public List searchForInternalLoadBalancerElements(Long id, Long ntwkSvsProviderId, Boolean enabled) { - GenericQueryBuilder sc = GenericQueryBuilder.create(VirtualRouterProviderVO.class); + QueryBuilder sc = QueryBuilder.create(VirtualRouterProviderVO.class); if (id != null) { - sc.addAnd(sc.getEntity().getId(), Op.EQ, id); + sc.and(sc.entity().getId(), Op.EQ, id); } if (ntwkSvsProviderId != null) { - sc.addAnd(sc.getEntity().getNspId(), Op.EQ, ntwkSvsProviderId); + sc.and(sc.entity().getNspId(), Op.EQ, ntwkSvsProviderId); } if (enabled != null) { - sc.addAnd(sc.getEntity().isEnabled(), Op.EQ, enabled); + sc.and(sc.entity().isEnabled(), Op.EQ, enabled); } //return only Internal LB elements - sc.addAnd(sc.getEntity().getType(), Op.EQ, VirtualRouterProvider.VirtualRouterProviderType.InternalLbVm); + sc.and(sc.entity().getType(), Op.EQ, VirtualRouterProvider.Type.InternalLbVm); return sc.list(); } diff --git a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java index 587ae993553..5da6e022906 100644 --- a/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java +++ b/plugins/network-elements/internal-loadbalancer/src/org/apache/cloudstack/network/lb/InternalLoadBalancerVMManagerImpl.java @@ -69,7 +69,7 @@ import com.cloud.network.NetworkModel; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.VirtualRouterProviderDao; @@ -310,7 +310,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In VirtualRouterProvider lbProvider = _vrProviderDao.findById(internalLbVm.getElementId()); if (lbProvider == null) { - throw new CloudRuntimeException("Cannot find related element " + VirtualRouterProviderType.InternalLbVm + " of vm: " + internalLbVm.getHostName()); + throw new CloudRuntimeException("Cannot find related element " + Type.InternalLbVm + " of vm: " + internalLbVm.getHostName()); } Provider provider = Network.Provider.getProvider(lbProvider.getType().toString()); @@ -629,7 +629,7 @@ public class InternalLoadBalancerVMManagerImpl extends ManagerBase implements In } protected long getInternalLbProviderId(Network guestNetwork) { - VirtualRouterProviderType type = VirtualRouterProviderType.InternalLbVm; + Type type = Type.InternalLbVm; long physicalNetworkId = _ntwkModel.getPhysicalNetworkId(guestNetwork); PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, type.toString()); diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java index bdc50cafb8c..7a47af9c4c5 100644 --- a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java +++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementServiceTest.java @@ -33,7 +33,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.dao.VirtualRouterProviderDao; @@ -65,15 +65,15 @@ public class InternalLbElementServiceTest { public void setUp() { ComponentContext.initComponentsLifeCycle(); - VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm); - VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.VirtualRouter); + VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, Type.InternalLbVm); + VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, Type.VirtualRouter); Mockito.when(_vrProviderDao.findById(validElId)).thenReturn(validElement); Mockito.when(_vrProviderDao.findById(invalidElId)).thenReturn(invalidElement); Mockito.when(_vrProviderDao.persist(validElement)).thenReturn(validElement); - Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement); + Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, Type.InternalLbVm)).thenReturn(validElement); PhysicalNetworkServiceProviderVO validProvider = new PhysicalNetworkServiceProviderVO(1, "InternalLoadBalancerElement"); PhysicalNetworkServiceProviderVO invalidProvider = new PhysicalNetworkServiceProviderVO(1, "Invalid name!"); diff --git a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java index 7af679649fe..f170fee28e1 100644 --- a/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java +++ b/plugins/network-elements/internal-loadbalancer/test/org/apache/cloudstack/internallbelement/InternalLbElementTest.java @@ -47,7 +47,7 @@ import com.cloud.dc.DataCenterVO; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; @@ -91,18 +91,18 @@ public class InternalLbElementTest { public void setUp() { ComponentContext.initComponentsLifeCycle(); - VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm); + VirtualRouterProviderVO validElement = new VirtualRouterProviderVO(1, Type.InternalLbVm); validElement.setEnabled(true); - VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.VirtualRouter); - VirtualRouterProviderVO notEnabledElement = new VirtualRouterProviderVO(1, VirtualRouterProviderType.InternalLbVm); + VirtualRouterProviderVO invalidElement = new VirtualRouterProviderVO(1, Type.VirtualRouter); + VirtualRouterProviderVO notEnabledElement = new VirtualRouterProviderVO(1, Type.InternalLbVm); - Mockito.when(_vrProviderDao.findByNspIdAndType(validElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement); - Mockito.when(_vrProviderDao.findByNspIdAndType(invalidElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(invalidElement); - Mockito.when(_vrProviderDao.findByNspIdAndType(notEnabledElId, VirtualRouterProviderType.InternalLbVm)).thenReturn(notEnabledElement); + Mockito.when(_vrProviderDao.findByNspIdAndType(validElId, Type.InternalLbVm)).thenReturn(validElement); + Mockito.when(_vrProviderDao.findByNspIdAndType(invalidElId, Type.InternalLbVm)).thenReturn(invalidElement); + Mockito.when(_vrProviderDao.findByNspIdAndType(notEnabledElId, Type.InternalLbVm)).thenReturn(notEnabledElement); Mockito.when(_vrProviderDao.persist(validElement)).thenReturn(validElement); - Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, VirtualRouterProviderType.InternalLbVm)).thenReturn(validElement); + Mockito.when(_vrProviderDao.findByNspIdAndType(validProviderId, Type.InternalLbVm)).thenReturn(validElement); PhysicalNetworkServiceProviderVO validProvider = new PhysicalNetworkServiceProviderVO(1, "InternalLoadBalancerElement"); PhysicalNetworkServiceProviderVO invalidProvider = new PhysicalNetworkServiceProviderVO(1, "Invalid name!"); diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 1ba55bfb56a..f4ca112936a 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -2681,8 +2681,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { //generate only response of the VR/VPCVR provider type - if (!(result.getType() == VirtualRouterProvider.VirtualRouterProviderType.VirtualRouter - || result.getType() == VirtualRouterProvider.VirtualRouterProviderType.VPCVirtualRouter)) { + if (!(result.getType() == VirtualRouterProvider.Type.VirtualRouter + || result.getType() == VirtualRouterProvider.Type.VPCVirtualRouter)) { return null; } VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); @@ -3734,7 +3734,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public InternalLoadBalancerElementResponse createInternalLbElementResponse(VirtualRouterProvider result) { - if (result.getType() != VirtualRouterProvider.VirtualRouterProviderType.InternalLbVm) { + if (result.getType() != VirtualRouterProvider.Type.InternalLbVm) { return null; } InternalLoadBalancerElementResponse response = new InternalLoadBalancerElementResponse(); diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index 8ad553adcd0..b6b9bb5114c 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -1694,8 +1694,8 @@ VirtualMachineGuru, SystemVmLoadScanHandler, ResourceStateAdapter { protected HostVO findConsoleProxyHostByName(String name) { GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.ConsoleProxy); - sc.addAnd(sc.getEntity().getName(), Op.EQ, name); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.ConsoleProxy); + sc.and(sc.entity().getName(), Op.EQ, name); return sc.find(); } diff --git a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java index c64d2ec9e0d..e5513868765 100755 --- a/server/src/com/cloud/ha/AbstractInvestigatorImpl.java +++ b/server/src/com/cloud/ha/AbstractInvestigatorImpl.java @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; - import javax.inject.Inject; import javax.naming.ConfigurationException; @@ -38,16 +37,15 @@ import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.resource.ResourceManager; import com.cloud.utils.component.AdapterBase; -import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; public abstract class AbstractInvestigatorImpl extends AdapterBase implements Investigator { private static final Logger s_logger = Logger.getLogger(AbstractInvestigatorImpl.class); - @Inject private HostDao _hostDao = null; - @Inject private AgentManager _agentMgr = null; - @Inject private ResourceManager _resourceMgr = null; + @Inject private final HostDao _hostDao = null; + @Inject private final AgentManager _agentMgr = null; + @Inject private final ResourceManager _resourceMgr = null; @Override @@ -68,10 +66,10 @@ public abstract class AbstractInvestigatorImpl extends AdapterBase implements In // Host.status is up and Host.type is routing protected List findHostByPod(long podId, Long excludeHostId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Type.Routing); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ, Type.Routing); + sc.and(sc.entity().getPodId(), Op.EQ, podId); + sc.and(sc.entity().getStatus(), Op.EQ, Status.Up); List hosts = sc.list(); List hostIds = new ArrayList(hosts.size()); diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index 4dbf48693f0..598b31c7bfe 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -97,7 +97,7 @@ import com.cloud.network.Network.Service; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetwork.BroadcastDomainRange; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.AccountGuestVlanMapDao; import com.cloud.network.dao.AccountGuestVlanMapVO; @@ -3685,7 +3685,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } VirtualRouterElement element = (VirtualRouterElement)networkElement; - element.addElement(nsp.getId(), VirtualRouterProviderType.VirtualRouter); + element.addElement(nsp.getId(), Type.VirtualRouter); return nsp; } @@ -3701,7 +3701,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { } VpcVirtualRouterElement element = (VpcVirtualRouterElement)networkElement; - element.addElement(nsp.getId(), VirtualRouterProviderType.VPCVirtualRouter); + element.addElement(nsp.getId(), Type.VPCVirtualRouter); return nsp; } diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 5d6fd62d55f..2c6414e1097 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -340,7 +340,7 @@ public class StorageNetworkManagerImpl extends ManagerBase implements StorageNet @Override public boolean isStorageIpRangeAvailable(long zoneId) { GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId); + sc.and(sc.entity().getDataCenterId(), Op.EQ, zoneId); List entries = sc.list(); return entries.size() > 0; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 00d52bffbae..0cd3bcf6db0 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -5,7 +5,7 @@ // 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, @@ -25,13 +25,15 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.log4j.Logger; + +import com.google.gson.Gson; + import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; import org.apache.cloudstack.api.command.admin.router.CreateVirtualRouterElementCmd; import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.log4j.Logger; - import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.configuration.ConfigurationManager; import com.cloud.dc.DataCenter; @@ -55,7 +57,7 @@ import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.VpnUser; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.LoadBalancerDao; @@ -77,12 +79,10 @@ import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.user.AccountManager; -import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; @@ -91,19 +91,16 @@ import com.cloud.vm.UserVmManager; import com.cloud.vm.UserVmVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; -import com.google.gson.Gson; - -@Local(value = {NetworkElement.class, FirewallServiceProvider.class, - DhcpServiceProvider.class, UserDataServiceProvider.class, +@Local(value = {NetworkElement.class, FirewallServiceProvider.class, + DhcpServiceProvider.class, UserDataServiceProvider.class, StaticNatServiceProvider.class, LoadBalancingServiceProvider.class, PortForwardingServiceProvider.class, IpDeployer.class, RemoteAccessVPNServiceProvider.class, NetworkMigrationResponder.class} ) -public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, +public class VirtualRouterElement extends AdapterBase implements VirtualRouterElementService, DhcpServiceProvider, UserDataServiceProvider, SourceNatServiceProvider, StaticNatServiceProvider, FirewallServiceProvider, LoadBalancingServiceProvider, PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, NetworkMigrationResponder { @@ -166,7 +163,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } } else { if (!_networkMgr.isProviderSupportServiceInNetwork(network.getId(), service, getProvider())) { - s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + s_logger.trace("Element " + getProvider().getName() + " doesn't support service " + service.getName() + " in the network " + network); return false; } @@ -187,19 +184,19 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl Map params = new HashMap(1); params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true); - List routers = _routerMgr.deployVirtualRouterInGuestNetwork(network, dest, - _accountMgr.getAccount(network.getAccountId()), params, + List routers = _routerMgr.deployVirtualRouterInGuestNetwork(network, dest, + _accountMgr.getAccount(network.getAccountId()), params, offering.getRedundantRouter()); if ((routers == null) || (routers.size() == 0)) { throw new ResourceUnavailableException("Can't find at least one running router!", DataCenter.class, network.getDataCenterId()); } - return true; + return true; } @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, + public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (vm.getType() != VirtualMachine.Type.User || vm.getHypervisorType() == HypervisorType.BareMetal) { @@ -219,15 +216,15 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; - List routers = _routerMgr.deployVirtualRouterInGuestNetwork(network, dest, + VirtualMachineProfile uservm = vm; + List routers = _routerMgr.deployVirtualRouterInGuestNetwork(network, dest, _accountMgr.getAccount(network.getAccountId()), uservm.getParameters(), offering.getRedundantRouter()); if ((routers == null) || (routers.size() == 0)) { throw new ResourceUnavailableException("Can't find at least one running router!", DataCenter.class, network.getDataCenterId()); } - return true; + return true; } @Override @@ -306,11 +303,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl expire = value; } if ((expire != null) && !containsOnlyNumbers(expire, timeEndChar)) { - throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + + throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + " Cause: expire is not in timeformat: " + expire); } if ((tablesize != null) && !containsOnlyNumbers(tablesize, "kmg")) { - throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + + throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + " Cause: tablesize is not in size format: " + tablesize); } @@ -337,11 +334,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } if ((length != null) && (!containsOnlyNumbers(length, null))) { - throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + + throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + " Cause: length is not a number: " + length); } if ((holdTime != null) && (!containsOnlyNumbers(holdTime, timeEndChar) && !containsOnlyNumbers(holdTime, null))) { - throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + + throw new InvalidParameterValueException("Failed LB in validation rule id: " + rule.getId() + " Cause: holdtime is not in timeformat: " + holdTime); } } @@ -400,7 +397,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } return _routerMgr.applyVpnUsers(network, users, routers); } else { - s_logger.debug("Element " + this.getName() + " doesn't handle applyVpnUsers command"); + s_logger.debug("Element " + getName() + " doesn't handle applyVpnUsers command"); return null; } } @@ -416,7 +413,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } return _routerMgr.startRemoteAccessVpn(network, vpn, routers); } else { - s_logger.debug("Element " + this.getName() + " doesn't handle createVpn command"); + s_logger.debug("Element " + getName() + " doesn't handle createVpn command"); return false; } } @@ -432,13 +429,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } return _routerMgr.deleteRemoteAccessVpn(network, vpn, routers); } else { - s_logger.debug("Element " + this.getName() + " doesn't handle removeVpn command"); + s_logger.debug("Element " + getName() + " doesn't handle removeVpn command"); return false; } } @Override - public boolean applyIps(Network network, List ipAddress, Set services) + public boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException { boolean canHandle = true; for (Service service : services) { @@ -636,7 +633,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) + public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); if (routers == null || routers.isEmpty()) { @@ -672,7 +669,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) + public boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { if (!canHandle(network, null)) { return false; @@ -684,7 +681,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; return _routerMgr.savePasswordToRouter(network, nic, uservm, routers); } @@ -702,7 +699,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; return _routerMgr.saveSSHPublicKeyToRouter(network, nic, uservm, routers, SSHPublicKey); } @@ -720,7 +717,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; return _routerMgr.saveUserDataToRouter(network, nic, uservm, routers); } @@ -737,7 +734,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl @Override public VirtualRouterProvider configure(ConfigureVirtualRouterElementCmd cmd) { VirtualRouterProviderVO element = _vrProviderDao.findById(cmd.getId()); - if (element == null || !(element.getType() == VirtualRouterProviderType.VirtualRouter || element.getType() == VirtualRouterProviderType.VPCVirtualRouter)) { + if (element == null || !(element.getType() == Type.VirtualRouter || element.getType() == Type.VPCVirtualRouter)) { s_logger.debug("Can't find Virtual Router element with network service provider id " + cmd.getId()); return null; } @@ -749,10 +746,10 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public VirtualRouterProvider addElement(Long nspId, VirtualRouterProviderType providerType) { - if (!(providerType == VirtualRouterProviderType.VirtualRouter || providerType == VirtualRouterProviderType.VPCVirtualRouter)) { - throw new InvalidParameterValueException("Element " + this.getName() + " supports only providerTypes: " + - VirtualRouterProviderType.VirtualRouter.toString() + " and " + VirtualRouterProviderType.VPCVirtualRouter); + public VirtualRouterProvider addElement(Long nspId, Type providerType) { + if (!(providerType == Type.VirtualRouter || providerType == Type.VPCVirtualRouter)) { + throw new InvalidParameterValueException("Element " + getName() + " supports only providerTypes: " + + Type.VirtualRouter.toString() + " and " + Type.VPCVirtualRouter); } VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(nspId, providerType); if (element != null) { @@ -786,7 +783,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl @Override public boolean isReady(PhysicalNetworkServiceProvider provider) { - VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), + VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), getVirtualRouterProvider()); if (element == null) { return false; @@ -795,10 +792,10 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) + public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), + VirtualRouterProviderVO element = _vrProviderDao.findByNspIdAndType(provider.getId(), getVirtualRouterProvider()); if (element == null) { return true; @@ -821,14 +818,14 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } public Long getIdByNspId(Long nspId) { - VirtualRouterProviderVO vr = _vrProviderDao.findByNspIdAndType(nspId, VirtualRouterProviderType.VirtualRouter); + VirtualRouterProviderVO vr = _vrProviderDao.findByNspIdAndType(nspId, Type.VirtualRouter); return vr.getId(); } @Override public VirtualRouterProvider getCreatedElement(long id) { VirtualRouterProvider provider = _vrProviderDao.findById(id); - if (!(provider.getType() == VirtualRouterProviderType.VirtualRouter || provider.getType() == VirtualRouterProviderType.VPCVirtualRouter)) { + if (!(provider.getType() == Type.VirtualRouter || provider.getType() == Type.VPCVirtualRouter)) { throw new InvalidParameterValueException("Unable to find provider by id"); } return provider; @@ -849,7 +846,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return false; } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; List routers = getRouters(network, dest); @@ -880,7 +877,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile vm, + public boolean addDhcpEntry(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { if (canHandle(network, Service.Dhcp)) { @@ -889,7 +886,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; List routers = getRouters(network, dest); @@ -917,7 +914,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @SuppressWarnings("unchecked") - VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + VirtualMachineProfile uservm = vm; List routers = getRouters(network, dest); @@ -935,7 +932,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl if (_networkMgr.isProviderSupportServiceInNetwork(network.getId(), Service.SourceNat, getProvider())) { publicNetwork = true; } - boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic + boolean isPodBased = (dest.getDataCenter().getNetworkType() == NetworkType.Basic || _networkMgr.isSecurityGroupSupportedInNetwork(network)) && network.getTrafficType() == TrafficType.Guest; @@ -969,19 +966,19 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl Long nspId = cmd.getNspId(); Boolean enabled = cmd.getEnabled(); - GenericQueryBuilder sc = GenericQueryBuilder.create(VirtualRouterProviderVO.class); + QueryBuilder sc = QueryBuilder.create(VirtualRouterProviderVO.class); if (id != null) { - sc.addAnd(sc.getEntity().getId(), Op.EQ, id); + sc.and(sc.entity().getId(), Op.EQ, id); } if (nspId != null) { - sc.addAnd(sc.getEntity().getNspId(), Op.EQ, nspId); + sc.and(sc.entity().getNspId(), Op.EQ, nspId); } if (enabled != null) { - sc.addAnd(sc.getEntity().isEnabled(), Op.EQ, enabled); + sc.and(sc.entity().isEnabled(), Op.EQ, enabled); } //return only VR and VPC VR - sc.addAnd(sc.getEntity().getType(), Op.IN, VirtualRouterProvider.VirtualRouterProviderType.VPCVirtualRouter, VirtualRouterProvider.VirtualRouterProviderType.VirtualRouter); + sc.and(sc.entity().getType(), Op.IN, VirtualRouterProvider.Type.VPCVirtualRouter, VirtualRouterProvider.Type.VirtualRouter); return sc.list(); } @@ -989,7 +986,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl @Override public boolean verifyServicesCombination(Set services) { if (!services.contains(Service.SourceNat)) { - if (services.contains(Service.StaticNat) || services.contains(Service.Firewall) || services.contains(Service.Lb) || + if (services.contains(Service.StaticNat) || services.contains(Service.Firewall) || services.contains(Service.Lb) || services.contains(Service.PortForwarding) || services.contains(Service.Vpn)) { String servicesList = "["; for (Service service : services) { @@ -1008,8 +1005,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return this; } - protected VirtualRouterProviderType getVirtualRouterProvider() { - return VirtualRouterProviderType.VirtualRouter; + protected VirtualRouterProvider.Type getVirtualRouterProvider() { + return VirtualRouterProvider.Type.VirtualRouter; } @Override @@ -1019,13 +1016,13 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl return null; } private boolean canHandleLbRules(List rules) { - Map lbCaps = this.getCapabilities().get(Service.Lb); + Map lbCaps = getCapabilities().get(Service.Lb); if (!lbCaps.isEmpty()) { String schemeCaps = lbCaps.get(Capability.LbSchemes); if (schemeCaps != null) { for (LoadBalancingRule rule : rules) { if (!schemeCaps.contains(rule.getScheme().toString())) { - s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName()); + s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + getName()); return false; } } @@ -1041,11 +1038,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) { return true; } - if (vm.getType() == Type.DomainRouter) { + if (vm.getType() == VirtualMachine.Type.DomainRouter) { assert vm instanceof DomainRouterVO; DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine(); _routerMgr.setupDhcpForPvlan(false, router, router.getHostId(), nic); - } else if (vm.getType() == Type.User){ + } else if (vm.getType() == VirtualMachine.Type.User) { assert vm instanceof UserVmVO; UserVmVO userVm = (UserVmVO)vm.getVirtualMachine(); _userVmMgr.setupVmForPvlan(false, userVm.getHostId(), nic); @@ -1060,11 +1057,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) { return; } - if (vm.getType() == Type.DomainRouter) { + if (vm.getType() == VirtualMachine.Type.DomainRouter) { assert vm instanceof DomainRouterVO; DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine(); _routerMgr.setupDhcpForPvlan(true, router, router.getHostId(), nic); - } else if (vm.getType() == Type.User){ + } else if (vm.getType() == VirtualMachine.Type.User) { assert vm instanceof UserVmVO; UserVmVO userVm = (UserVmVO)vm.getVirtualMachine(); _userVmMgr.setupVmForPvlan(true, userVm.getHostId(), nic); @@ -1078,11 +1075,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) { return; } - if (vm.getType() == Type.DomainRouter) { + if (vm.getType() == VirtualMachine.Type.DomainRouter) { assert vm instanceof DomainRouterVO; DomainRouterVO router = (DomainRouterVO)vm.getVirtualMachine(); _routerMgr.setupDhcpForPvlan(true, router, router.getHostId(), nic); - } else if (vm.getType() == Type.User){ + } else if (vm.getType() == VirtualMachine.Type.User) { assert vm instanceof UserVmVO; UserVmVO userVm = (UserVmVO)vm.getVirtualMachine(); _userVmMgr.setupVmForPvlan(true, userVm.getHostId(), nic); diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index c512dda0058..b8a8246f76d 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -41,7 +41,7 @@ import com.cloud.network.NetworkModel; import com.cloud.network.PublicIpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.Site2SiteVpnGatewayDao; @@ -63,7 +63,7 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine.Type; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; @Local(value = {NetworkElement.class, FirewallServiceProvider.class, @@ -210,7 +210,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc return false; } - if (vm.getType() == Type.User) { + if (vm.getType() == VirtualMachine.Type.User) { Map params = new HashMap(1); params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true); List routers = _vpcRouterMgr.deployVirtualRouterInVpc(vpc, dest, @@ -434,8 +434,8 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc } @Override - protected VirtualRouterProviderType getVirtualRouterProvider() { - return VirtualRouterProviderType.VPCVirtualRouter; + protected Type getVirtualRouterProvider() { + return Type.VPCVirtualRouter; } @Override diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 7c026a4cb80..043c376f558 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -155,7 +155,7 @@ import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.SshKeysDistriMonitor; import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.VpnUser; import com.cloud.network.VpnUserVO; import com.cloud.network.addr.PublicIp; @@ -202,7 +202,7 @@ import com.cloud.server.ConfigurationServer; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.Volume.Type; +import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.VMTemplateDao; @@ -1506,7 +1506,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V } // Check if providers are supported in the physical networks - VirtualRouterProviderType type = VirtualRouterProviderType.VirtualRouter; + Type type = Type.VirtualRouter; Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork); PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, type.toString()); if (provider == null) { @@ -1930,7 +1930,7 @@ public class VirtualNetworkApplianceManagerImpl extends ManagerBase implements V avoids[1] = new ExcludeList(); avoids[1].addCluster(_hostDao.findById(routerToBeAvoid.getHostId()).getClusterId()); avoids[2] = new ExcludeList(); - List volumes = _volumeDao.findByInstanceAndType(routerToBeAvoid.getId(), Type.ROOT); + List volumes = _volumeDao.findByInstanceAndType(routerToBeAvoid.getId(), Volume.Type.ROOT); if (volumes != null && volumes.size() != 0) { avoids[2].addPool(volumes.get(0).getPoolId()); } diff --git a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index ea2d7c42884..12d90ef070c 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -72,7 +72,7 @@ import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PublicIpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; +import com.cloud.network.VirtualRouterProvider.Type; import com.cloud.network.VpcVirtualNetworkApplianceService; import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.FirewallRulesDao; @@ -203,13 +203,13 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian for (PhysicalNetwork pNtwk : pNtwks) { PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(pNtwk.getId(), - VirtualRouterProviderType.VPCVirtualRouter.toString()); + Type.VPCVirtualRouter.toString()); if (provider == null) { throw new CloudRuntimeException("Cannot find service provider " + - VirtualRouterProviderType.VPCVirtualRouter.toString() + " in physical network " + pNtwk.getId()); + Type.VPCVirtualRouter.toString() + " in physical network " + pNtwk.getId()); } vpcVrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), - VirtualRouterProviderType.VPCVirtualRouter); + Type.VPCVirtualRouter); if (vpcVrProvider != null) { break; } diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index 27f0600176b..7a9343cff41 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -140,12 +140,11 @@ import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.QueryBuilder; 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.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.NoTransitionException; @@ -2256,27 +2255,27 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List findDirectlyConnectedHosts() { /* The resource column is not null for direct connected resource */ - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getResource(), Op.NNULL); - sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Disabled); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getResource(), Op.NNULL); + sc.and(sc.entity().getResourceState(), Op.NIN, ResourceState.Disabled); return sc.list(); } @Override public List listAllUpAndEnabledHosts(Type type, Long clusterId, Long podId, long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); if (type != null) { - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + sc.and(sc.entity().getType(), Op.EQ,type); } if (clusterId != null) { - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + sc.and(sc.entity().getClusterId(), Op.EQ,clusterId); } if (podId != null) { - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, podId); + sc.and(sc.entity().getPodId(), Op.EQ,podId); } - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); + sc.and(sc.entity().getStatus(), Op.EQ,Status.Up); + sc.and(sc.entity().getResourceState(), Op.EQ,ResourceState.Enabled); return sc.list(); } @@ -2288,60 +2287,60 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List findHostByGuid(long dcId, String guid) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); + sc.and(sc.entity().getGuid(), Op.EQ,guid); return sc.list(); } @Override public List listAllHostsInCluster(long clusterId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getClusterId(), Op.EQ,clusterId); return sc.list(); } @Override public List listHostsInClusterByStatus(long clusterId, Status status) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, status); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getClusterId(), Op.EQ,clusterId); + sc.and(sc.entity().getStatus(), Op.EQ,status); return sc.list(); } @Override public List listAllUpAndEnabledHostsInOneZoneByType(Type type, long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ,type); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); + sc.and(sc.entity().getStatus(), Op.EQ,Status.Up); + sc.and(sc.entity().getResourceState(), Op.EQ,ResourceState.Enabled); return sc.list(); } @Override public List listAllNotInMaintenanceHostsInOneZone(Type type, Long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); if (dcId != null) { - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); } - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance, ResourceState.PrepareForMaintenance, ResourceState.Error); + sc.and(sc.entity().getType(), Op.EQ,type); + sc.and(sc.entity().getResourceState(), Op.NIN, ResourceState.Maintenance, ResourceState.ErrorInMaintenance, ResourceState.PrepareForMaintenance, ResourceState.Error); return sc.list(); } @Override public List listAllHostsInOneZoneByType(Type type, long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ,type); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); return sc.list(); } @Override public List listAllHostsInAllZonesByType(Type type) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, type); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ,type); return sc.list(); } @@ -2370,15 +2369,15 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public HostVO findHostByGuid(String guid) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getGuid(), Op.EQ, guid); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getGuid(), Op.EQ,guid); return sc.find(); } @Override public HostVO findHostByName(String name) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getName(), Op.EQ, name); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getName(), Op.EQ,name); return sc.find(); } @@ -2449,11 +2448,11 @@ public class ResourceManagerImpl extends ManagerBase implements ResourceManager, @Override public List listAllUpAndEnabledHostsInOneZoneByHypervisor(HypervisorType type, long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getHypervisorType(), Op.EQ, type); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); - sc.addAnd(sc.getEntity().getStatus(), Op.EQ, Status.Up); - sc.addAnd(sc.getEntity().getResourceState(), Op.EQ, ResourceState.Enabled); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getHypervisorType(), Op.EQ,type); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); + sc.and(sc.entity().getStatus(), Op.EQ,Status.Up); + sc.and(sc.entity().getResourceState(), Op.EQ,ResourceState.Enabled); return sc.list(); } diff --git a/server/src/com/cloud/storage/OCFS2ManagerImpl.java b/server/src/com/cloud/storage/OCFS2ManagerImpl.java index c258a96684a..e38ca5bae2f 100755 --- a/server/src/com/cloud/storage/OCFS2ManagerImpl.java +++ b/server/src/com/cloud/storage/OCFS2ManagerImpl.java @@ -142,10 +142,10 @@ public class OCFS2ManagerImpl extends ManagerBase implements OCFS2Manager, Resou } GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getClusterId(), Op.EQ, clusterId); - sc.addAnd(sc.getEntity().getPodId(), Op.EQ, cluster.getPodId()); - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.Routing); + sc.and(sc.entity().getClusterId(), Op.EQ, clusterId); + sc.and(sc.entity().getPodId(), Op.EQ, cluster.getPodId()); + sc.and(sc.entity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); + sc.and(sc.entity().getType(), Op.EQ, Host.Type.Routing); List hosts = sc.list(); if (hosts.isEmpty()) { s_logger.debug("There is no host in cluster " + clusterId + ", no need to prepare OCFS2 nodes"); diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index a6af8119e3f..3a070349ace 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -75,6 +75,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.StorageUnavailableException; import com.cloud.host.Host; import com.cloud.host.HostVO; +import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.info.RunningHostCountInfo; @@ -114,9 +115,8 @@ import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.events.SubscriptionMgr; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -420,9 +420,9 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar SecStorageFirewallCfgCommand thiscpc = new SecStorageFirewallCfgCommand(true); thiscpc.addPortConfig(thisSecStorageVm.getPublicIpAddress(), copyPort, true, TemplateConstants.DEFAULT_TMPLT_COPY_INTF); - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorageVM); - sc.addAnd(sc.getEntity().getStatus(), Op.IN, com.cloud.host.Status.Up, com.cloud.host.Status.Connecting); + QueryBuilder sc = QueryBuilder.create(HostVO.class); + sc.and(sc.entity().getType(), Op.EQ,Host.Type.SecondaryStorageVM); + sc.and(sc.entity().getStatus(), Op.IN, Status.Up, Status.Connecting); List ssvms = sc.list(); for (HostVO ssvm : ssvms) { if (ssvm.getId() == ssAHostId) { @@ -1345,12 +1345,12 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar @Override public List listUpAndConnectingSecondaryStorageVmHost(Long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); if (dcId != null) { - sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, dcId); + sc.and(sc.entity().getDataCenterId(), Op.EQ,dcId); } - sc.addAnd(sc.getEntity().getState(), Op.IN, com.cloud.host.Status.Up, com.cloud.host.Status.Connecting); - sc.addAnd(sc.getEntity().getType(), Op.EQ, Host.Type.SecondaryStorageVM); + sc.and(sc.entity().getState(), Op.IN, Status.Up, Status.Connecting); + sc.and(sc.entity().getType(), Op.EQ,Host.Type.SecondaryStorageVM); return sc.list(); } From 38e69fb9f99d0a544b7ef0036db16b6d90a731cf Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Fri, 27 Sep 2013 17:12:37 -0700 Subject: [PATCH 05/27] Changed SearchCriteria2 to GenericQueryBuilder to reflect the same placement --- .../cloud/utils/db/GenericQueryBuilder.java | 47 +++++++++++++++++-- .../cloud/utils/db/GenericSearchBuilder.java | 47 ++++--------------- 2 files changed, 53 insertions(+), 41 deletions(-) diff --git a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java index 8581d80dc63..570a10e1bca 100755 --- a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java @@ -44,6 +44,11 @@ public class GenericQueryBuilder extends SearchBase { return create(entityType, entityType); } + public GenericQueryBuilder or() { + constructCondition(null, " OR ", null, null); + return this; + } + public void selectField(Object... useless) { assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes"; @@ -66,10 +71,48 @@ public class GenericQueryBuilder extends SearchBase { _specifiedAttrs.clear(); } - public void and(Object useless, Op op, Object... values) { + public GenericQueryBuilder and(Object useless, Op op, Object... values) { String uuid = UUID.randomUUID().toString(); Condition condition = constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op); condition.setPresets(values); + return this; + } + + public GenericQueryBuilder or(Object useless, Op op, Object... values) { + String uuid = UUID.randomUUID().toString(); + Condition condition = constructCondition(uuid, " OR ", _specifiedAttrs.get(0), op); + condition.setPresets(values); + return this; + } + + protected GenericQueryBuilder left(Object useless, Op op, Object... values) { + String uuid = UUID.randomUUID().toString(); + Condition condition = constructCondition(uuid, " ( ", _specifiedAttrs.get(0), op); + condition.setPresets(values); + return this; + } + + public GenericQueryBuilder and() { + constructCondition(null, " AND ", null, null); + return this; + } + + public GenericQueryBuilder where() { + return and(); + } + + public GenericQueryBuilder op(Object useless, Op op, Object... values) { + return left(useless, op, values); + } + + protected GenericQueryBuilder right() { + Condition condition = new Condition("rp", " ) ", null, Op.RP); + _conditions.add(condition); + return this; + } + + public GenericQueryBuilder cp() { + return right(); } @SuppressWarnings("unchecked") @@ -96,6 +139,4 @@ public class GenericQueryBuilder extends SearchBase { SearchCriteria sc1 = create(); return (K)_dao.findOneBy(sc1); } - - } diff --git a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java index 8e46c30ebf7..e17163507ea 100755 --- a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java @@ -127,6 +127,11 @@ public class GenericSearchBuilder extends SearchBase { return this; } + public GenericSearchBuilder and() { + constructCondition(null, " AND ", null, null); + return this; + } + public GenericSearchBuilder and(Object useless, Op op, String name) { constructCondition(name, " AND ", _specifiedAttrs.get(0), op); return this; @@ -137,24 +142,11 @@ public class GenericSearchBuilder extends SearchBase { return new Preset(this, condition); } - public GenericSearchBuilder and() { - constructCondition(null, " AND ", null, null); - return this; - } - - public GenericSearchBuilder where() { - return and(); - } - public GenericSearchBuilder or() { constructCondition(null, " OR ", null, null); return this; } - public GenericSearchBuilder where(String name, Object useless, Op op) { - return and(name, useless, op); - } - public GenericSearchBuilder where(Object useless, Op op, String name) { return and(name, useless, op); } @@ -163,17 +155,12 @@ public class GenericSearchBuilder extends SearchBase { return and(useless, op); } - public GenericSearchBuilder left(String name, Object useless, Op op) { - constructCondition(name, " ( ", _specifiedAttrs.get(0), op); - return this; - } - - public GenericSearchBuilder left(Object useless, Op op, String name) { + protected GenericSearchBuilder left(Object useless, Op op, String name) { constructCondition(name, " ( ", _specifiedAttrs.get(0), op); return this; } - public Preset left(Object useless, Op op) { + protected Preset left(Object useless, Op op) { Condition condition = constructCondition(UUID.randomUUID().toString(), " ( ", _specifiedAttrs.get(0), op); return new Preset(this, condition); } @@ -187,21 +174,9 @@ public class GenericSearchBuilder extends SearchBase { } public GenericSearchBuilder op(String name, Object useless, Op op) { - return left(name, useless, op); + return left(useless, op, name); } - public GenericSearchBuilder openParen(Object useless, Op op, String name) { - return left(name, useless, op); - } - - public GenericSearchBuilder openParen(String name, Object useless, Op op) { - return left(name, useless, op); - } - - public Preset openParen(Object useless, Op op) { - return left(useless, op); - } - public GroupBy, T, K> groupBy(Object... useless) { assert _groupBy == null : "Can't do more than one group bys"; GroupBy, T, K> groupBy = new GroupBy, T, K>(this); @@ -258,7 +233,7 @@ public class GenericSearchBuilder extends SearchBase { return sc; } - public GenericSearchBuilder right() { + protected GenericSearchBuilder right() { Condition condition = new Condition("rp", " ) ", null, Op.RP); _conditions.add(condition); return this; @@ -268,10 +243,6 @@ public class GenericSearchBuilder extends SearchBase { return right(); } - public GenericSearchBuilder closeParen() { - return right(); - } - /** * Marks the SearchBuilder as completed in building the search conditions. */ From 5fd47cc87382681b40cc2ec42265ac96064959fc Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Fri, 27 Sep 2013 17:13:11 -0700 Subject: [PATCH 06/27] Added QueryBuilder --- .../src/com/cloud/utils/db/QueryBuilder.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 framework/db/src/com/cloud/utils/db/QueryBuilder.java diff --git a/framework/db/src/com/cloud/utils/db/QueryBuilder.java b/framework/db/src/com/cloud/utils/db/QueryBuilder.java new file mode 100644 index 00000000000..5a5ff33ce35 --- /dev/null +++ b/framework/db/src/com/cloud/utils/db/QueryBuilder.java @@ -0,0 +1,29 @@ +// 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.utils.db; + +public class QueryBuilder extends GenericQueryBuilder { + + public static QueryBuilder create(Class entityType) { + return new QueryBuilder(entityType); + } + + protected QueryBuilder(Class entityType) { + super(entityType, entityType); + } + +} From b60eef3e822b3f176e449b150594ae7a76bc306f Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Sat, 28 Sep 2013 07:52:50 -0700 Subject: [PATCH 07/27] Added comments and finished off the work --- .../cloud/agent/manager/AgentManagerImpl.java | 7 +- .../dc/dao/StorageNetworkIpRangeDaoImpl.java | 13 +- .../cloud/event/dao/UsageEventDaoImpl.java | 2 +- .../src/com/cloud/host/dao/HostDaoImpl.java | 255 ++++++++++-------- .../com/cloud/user/AccountDetailsDaoImpl.java | 7 +- .../db/TemplatePrimaryDataStoreDaoImpl.java | 18 +- .../cloud/utils/db/GenericQueryBuilder.java | 74 +---- .../cloud/utils/db/GenericSearchBuilder.java | 226 +++++----------- .../db/src/com/cloud/utils/db/GroupBy.java | 2 +- .../db/src/com/cloud/utils/db/SearchBase.java | 213 ++++++++++++++- .../com/cloud/utils/db/SearchCriteria.java | 83 ++---- .../BareMetalPingServiceImpl.java | 7 +- .../BaremetalDhcpManagerImpl.java | 18 +- .../BaremetalKickStartServiceImpl.java | 6 +- .../networkservice/BaremetalPxeElement.java | 12 +- .../BaremetalPxeManagerImpl.java | 8 +- .../com/cloud/ucs/manager/UcsManagerImpl.java | 20 +- .../xen/discoverer/XcpServerDiscoverer.java | 52 ++-- .../query/dao/DiskOfferingJoinDaoImpl.java | 25 +- .../consoleproxy/ConsoleProxyManagerImpl.java | 5 +- .../network/StorageNetworkManagerImpl.java | 12 +- .../com/cloud/storage/OCFS2ManagerImpl.java | 10 +- 22 files changed, 555 insertions(+), 520 deletions(-) diff --git a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java index 9c187535794..51f6d72109e 100755 --- a/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/engine/orchestration/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -97,9 +97,8 @@ import com.cloud.utils.component.ManagerBase; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.EntityManager; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; @@ -1448,7 +1447,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl try { List behindAgents = findAgentsBehindOnPing(); for (Long agentId : behindAgents) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getId(), Op.EQ, agentId); HostVO h = sc.find(); if (h != null) { @@ -1470,7 +1469,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl } } - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getResourceState(), Op.IN, ResourceState.PrepareForMaintenance, ResourceState.ErrorInMaintenance); List hosts = sc.list(); diff --git a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java index f57acce1080..e1605d56334 100755 --- a/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java +++ b/engine/schema/src/com/cloud/dc/dao/StorageNetworkIpRangeDaoImpl.java @@ -17,22 +17,17 @@ package com.cloud.dc.dao; import java.util.List; -import java.util.Map; import javax.ejb.Local; -import javax.naming.ConfigurationException; import org.springframework.stereotype.Component; import com.cloud.dc.StorageNetworkIpRangeVO; import com.cloud.utils.db.DB; -import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; -import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; @@ -50,21 +45,21 @@ public class StorageNetworkIpRangeDaoImpl extends GenericDaoBase listByPodId(long podId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); + QueryBuilder sc = QueryBuilder.create(StorageNetworkIpRangeVO.class); sc.and(sc.entity().getPodId(), Op.EQ, podId); return sc.list(); } @Override public List listByRangeId(long rangeId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); + QueryBuilder sc = QueryBuilder.create(StorageNetworkIpRangeVO.class); sc.and(sc.entity().getId(), Op.EQ, rangeId); return sc.list(); } @Override public List listByDataCenterId(long dcId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); + QueryBuilder sc = QueryBuilder.create(StorageNetworkIpRangeVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, dcId); return sc.list(); } diff --git a/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java b/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java index cda02efe6bf..4f05bbe8fcd 100644 --- a/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java +++ b/engine/schema/src/com/cloud/event/dao/UsageEventDaoImpl.java @@ -66,7 +66,7 @@ public class UsageEventDaoImpl extends GenericDaoBase implem IpeventsSearch.and("networktype", IpeventsSearch.entity().getResourceType(), SearchCriteria.Op.EQ); IpeventsSearch.and().op("assignEvent", IpeventsSearch.entity().getType(), SearchCriteria.Op.EQ); IpeventsSearch.or("releaseEvent", IpeventsSearch.entity().getType(), SearchCriteria.Op.EQ); - IpeventsSearch.closeParen(); + IpeventsSearch.cp(); IpeventsSearch.done(); } diff --git a/engine/schema/src/com/cloud/host/dao/HostDaoImpl.java b/engine/schema/src/com/cloud/host/dao/HostDaoImpl.java index d0d3a5c394b..47168102a56 100755 --- a/engine/schema/src/com/cloud/host/dao/HostDaoImpl.java +++ b/engine/schema/src/com/cloud/host/dao/HostDaoImpl.java @@ -64,7 +64,7 @@ import com.cloud.utils.db.UpdateBuilder; import com.cloud.utils.exception.CloudRuntimeException; @Component -@Local(value = { HostDao.class }) +@Local(value = {HostDao.class}) @DB(txn = false) @TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1) public class HostDaoImpl extends GenericDaoBase implements HostDao { //FIXME: , ExternalIdDao { @@ -123,13 +123,17 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao protected Attribute _msIdAttr; protected Attribute _pingTimeAttr; - @Inject protected HostDetailsDao _detailsDao; - @Inject protected HostTagsDao _hostTagsDao; - @Inject protected HostTransferMapDao _hostTransferDao; - @Inject protected ClusterDao _clusterDao; + @Inject + protected HostDetailsDao _detailsDao; + @Inject + protected HostTagsDao _hostTagsDao; + @Inject + protected HostTransferMapDao _hostTransferDao; + @Inject + protected ClusterDao _clusterDao; public HostDaoImpl() { - super(); + super(); } @PostConstruct @@ -271,18 +275,19 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao * SearchCriteria.Op.LTEQ); UnmanagedDirectConnectSearch.cp(); UnmanagedDirectConnectSearch.cp(); */ try { - HostTransferSearch = _hostTransferDao.createSearchBuilder(); + HostTransferSearch = _hostTransferDao.createSearchBuilder(); } catch (Throwable e) { - s_logger.debug("error", e); + s_logger.debug("error", e); } HostTransferSearch.and("id", HostTransferSearch.entity().getId(), SearchCriteria.Op.NULL); - UnmanagedDirectConnectSearch.join("hostTransferSearch", HostTransferSearch, HostTransferSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getId(), JoinType.LEFTOUTER); + UnmanagedDirectConnectSearch.join("hostTransferSearch", HostTransferSearch, HostTransferSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getId(), + JoinType.LEFTOUTER); ClusterManagedSearch = _clusterDao.createSearchBuilder(); ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ); - UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getClusterId(), JoinType.INNER); + UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), + UnmanagedDirectConnectSearch.entity().getClusterId(), JoinType.INNER); UnmanagedDirectConnectSearch.done(); - DirectConnectSearch = createSearchBuilder(); DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL); DirectConnectSearch.and("id", DirectConnectSearch.entity().getId(), SearchCriteria.Op.EQ); @@ -386,7 +391,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao public long countBy(long clusterId, ResourceState... states) { SearchCriteria sc = MaintenanceCountSearch.create(); - sc.setParameters("resourceState", (Object[]) states); + sc.setParameters("resourceState", (Object[])states); sc.setParameters("cluster", clusterId); List hosts = listBy(sc); @@ -482,7 +487,8 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return ownCluster; } - @Override @DB + @Override + @DB public List findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) { Transaction txn = Transaction.currentTxn(); @@ -580,24 +586,26 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return assignedHosts; } - @Override @DB + @Override + @DB public List findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) { - Transaction txn = Transaction.currentTxn(); + Transaction txn = Transaction.currentTxn(); - txn.start(); - SearchCriteria sc = UnmanagedApplianceSearch.create(); - sc.setParameters("lastPinged", lastPingSecondsAfter); - sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.BaremetalDhcp, Type.BaremetalPxe, Type.TrafficMonitor, Type.L2Networking); - List hosts = lockRows(sc, null, true); + txn.start(); + SearchCriteria sc = UnmanagedApplianceSearch.create(); + sc.setParameters("lastPinged", lastPingSecondsAfter); + sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.BaremetalDhcp, Type.BaremetalPxe, Type.TrafficMonitor, + Type.L2Networking); + List hosts = lockRows(sc, null, true); - for (HostVO host : hosts) { - host.setManagementServerId(managementServerId); - update(host.getId(), host); - } + for (HostVO host : hosts) { + host.setManagementServerId(managementServerId); + update(host.getId(), host); + } - txn.commit(); + txn.commit(); - return hosts; + return hosts; } @Override @@ -657,7 +665,6 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return listBy(sc); } - @Override public List listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) { SearchBuilder hostTagSearch = null; @@ -726,7 +733,7 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao List result = new ArrayList(); ResultSet rs = null; try { - String sql = "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;" ; + String sql = "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;"; pstmt = txn.prepareStatement(sql); pstmt.setLong(1, timeout); rs = pstmt.executeQuery(); @@ -818,9 +825,9 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao @DB public List getRunningHostCounts(Date cutTime) { String sql = "select * from (" + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid " - + "where h.status='Up' and h.type='SecondaryStorage' and m.last_update > ? " + "group by h.data_center_id, h.type " + "UNION ALL " - + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid " - + "where h.status='Up' and h.type='Routing' and m.last_update > ? " + "group by h.data_center_id, h.type) as t " + "ORDER by t.data_center_id, t.type"; + + "where h.status='Up' and h.type='SecondaryStorage' and m.last_update > ? " + "group by h.data_center_id, h.type " + "UNION ALL " + + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid " + + "where h.status='Up' and h.type='Routing' and m.last_update > ? " + "group by h.data_center_id, h.type) as t " + "ORDER by t.data_center_id, t.type"; ArrayList l = new ArrayList(); @@ -870,90 +877,100 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao return customSearch(sc, null).get(0); } + @Override + public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) { + HostVO host = findById(vo.getId()); + if (host == null) { + if (event == Event.Remove && newStatus == Status.Removed) { + host = findByIdIncludingRemoved(vo.getId()); + } + } - @Override - public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) { - HostVO host = findById(vo.getId()); - if(host == null){ - if(event == Event.Remove && newStatus == Status.Removed){ - host = findByIdIncludingRemoved(vo.getId()); - } - } - - if(host == null){ + if (host == null) { return false; - } - long oldPingTime = host.getLastPinged(); + } + long oldPingTime = host.getLastPinged(); - SearchBuilder sb = createSearchBuilder(); - sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ); - if (newStatus.checkManagementServer()) { - sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ); - sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL); - sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ); - sb.closeParen(); - } - sb.done(); + SearchBuilder sb = createSearchBuilder(); + sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ); + if (newStatus.checkManagementServer()) { + sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ); + sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL); + sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ); + sb.cp(); + } + sb.done(); - SearchCriteria sc = sb.create(); + SearchCriteria sc = sb.create(); - sc.setParameters("status", oldStatus); - sc.setParameters("id", host.getId()); - sc.setParameters("update", host.getUpdated()); - long oldUpdateCount = host.getUpdated(); - if (newStatus.checkManagementServer()) { - sc.setParameters("ping", oldPingTime); - sc.setParameters("msid", host.getManagementServerId()); - } + sc.setParameters("status", oldStatus); + sc.setParameters("id", host.getId()); + sc.setParameters("update", host.getUpdated()); + long oldUpdateCount = host.getUpdated(); + if (newStatus.checkManagementServer()) { + sc.setParameters("ping", oldPingTime); + sc.setParameters("msid", host.getManagementServerId()); + } - long newUpdateCount = host.incrUpdated(); - UpdateBuilder ub = getUpdateBuilder(host); - ub.set(host, _statusAttr, newStatus); - if (newStatus.updateManagementServer()) { - if (newStatus.lostConnection()) { - ub.set(host, _msIdAttr, null); - } else { - ub.set(host, _msIdAttr, host.getManagementServerId()); - } - if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) { - ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10); - } - } - if (event.equals(Event.ManagementServerDown)) { - ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60))); - } - int result = update(ub, sc, null); - assert result <= 1 : "How can this update " + result + " rows? "; + long newUpdateCount = host.incrUpdated(); + UpdateBuilder ub = getUpdateBuilder(host); + ub.set(host, _statusAttr, newStatus); + if (newStatus.updateManagementServer()) { + if (newStatus.lostConnection()) { + ub.set(host, _msIdAttr, null); + } else { + ub.set(host, _msIdAttr, host.getManagementServerId()); + } + if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) { + ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10); + } + } + if (event.equals(Event.ManagementServerDown)) { + ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60))); + } + int result = update(ub, sc, null); + assert result <= 1 : "How can this update " + result + " rows? "; - if (status_logger.isDebugEnabled() && result == 0) { - HostVO ho = findById(host.getId()); - assert ho != null : "How how how? : " + host.getId(); + if (status_logger.isDebugEnabled() && result == 0) { + HostVO ho = findById(host.getId()); + assert ho != null : "How how how? : " + host.getId(); - StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString()); - str.append(". Name=").append(host.getName()); - str.append("; New=[status=").append(newStatus.toString()).append(":msid=") - .append(newStatus.lostConnection() ? "null" : host.getManagementServerId()).append(":lastpinged=").append(host.getLastPinged()).append("]"); - str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=") - .append(oldPingTime).append("]"); - str.append("; DB=[status=").append(vo.getStatus().toString()).append(":msid=").append(vo.getManagementServerId()).append(":lastpinged=") - .append(vo.getLastPinged()).append(":old update count=").append(oldUpdateCount).append("]"); - status_logger.debug(str.toString()); - } else { - StringBuilder msg = new StringBuilder("Agent status update: ["); - msg.append("id = " + host.getId()); - msg.append("; name = " + host.getName()); - msg.append("; old status = " + oldStatus); - msg.append("; event = " + event); - msg.append("; new status = " + newStatus); - msg.append("; old update count = " + oldUpdateCount); - msg.append("; new update count = " + newUpdateCount + "]"); - status_logger.debug(msg.toString()); - } + StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString()); + str.append(". Name=").append(host.getName()); + str.append("; New=[status=") + .append(newStatus.toString()) + .append(":msid=") + .append(newStatus.lostConnection() ? "null" : host.getManagementServerId()) + .append(":lastpinged=") + .append(host.getLastPinged()) + .append("]"); + str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=").append(oldPingTime).append("]"); + str.append("; DB=[status=") + .append(vo.getStatus().toString()) + .append(":msid=") + .append(vo.getManagementServerId()) + .append(":lastpinged=") + .append(vo.getLastPinged()) + .append(":old update count=") + .append(oldUpdateCount) + .append("]"); + status_logger.debug(str.toString()); + } else { + StringBuilder msg = new StringBuilder("Agent status update: ["); + msg.append("id = " + host.getId()); + msg.append("; name = " + host.getName()); + msg.append("; old status = " + oldStatus); + msg.append("; event = " + event); + msg.append("; new status = " + newStatus); + msg.append("; old update count = " + oldUpdateCount); + msg.append("; new update count = " + newUpdateCount + "]"); + status_logger.debug(msg.toString()); + } - return result > 0; - } + return result > 0; + } @Override public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) { @@ -978,20 +995,20 @@ public class HostDaoImpl extends GenericDaoBase implements HostDao assert ho != null : "How how how? : " + host.getId(); StringBuilder str = new StringBuilder("Unable to update resource state: ["); - str.append("m = " + host.getId()); - str.append("; name = " + host.getName()); - str.append("; old state = " + oldState); - str.append("; event = " + event); - str.append("; new state = " + newState + "]"); - state_logger.debug(str.toString()); + str.append("m = " + host.getId()); + str.append("; name = " + host.getName()); + str.append("; old state = " + oldState); + str.append("; event = " + event); + str.append("; new state = " + newState + "]"); + state_logger.debug(str.toString()); } else { - StringBuilder msg = new StringBuilder("Resource state update: ["); - msg.append("id = " + host.getId()); - msg.append("; name = " + host.getName()); - msg.append("; old state = " + oldState); - msg.append("; event = " + event); - msg.append("; new state = " + newState + "]"); - state_logger.debug(msg.toString()); + StringBuilder msg = new StringBuilder("Resource state update: ["); + msg.append("id = " + host.getId()); + msg.append("; name = " + host.getName()); + msg.append("; old state = " + oldState); + msg.append("; event = " + event); + msg.append("; new state = " + newState + "]"); + state_logger.debug(msg.toString()); } return result > 0; diff --git a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java index 81ae6368407..30bbe73a568 100755 --- a/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java +++ b/engine/schema/src/com/cloud/user/AccountDetailsDaoImpl.java @@ -27,11 +27,10 @@ import org.apache.cloudstack.framework.config.ConfigKey.Scope; import org.apache.cloudstack.framework.config.ScopedConfigStorage; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; @Local(value = {AccountDetailsDao.class}) @@ -46,7 +45,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public Map findDetails(long accountId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); + QueryBuilder sc = QueryBuilder.create(AccountDetailVO.class); sc.and(sc.entity().getAccountId(), Op.EQ, accountId); List results = sc.list(); Map details = new HashMap(results.size()); @@ -72,7 +71,7 @@ public class AccountDetailsDaoImpl extends GenericDaoBase @Override public AccountDetailVO findDetail(long accountId, String name) { - GenericQueryBuilder sc = GenericQueryBuilder.create(AccountDetailVO.class); + QueryBuilder sc = QueryBuilder.create(AccountDetailVO.class); sc.and(sc.entity().getAccountId(), Op.EQ, accountId); sc.and(sc.entity().getName(), Op.EQ, name); return sc.find(); diff --git a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java index 456471bb93c..50ab9e6c42b 100644 --- a/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java +++ b/engine/storage/src/org/apache/cloudstack/storage/volume/db/TemplatePrimaryDataStoreDaoImpl.java @@ -20,18 +20,18 @@ package org.apache.cloudstack.storage.volume.db; import java.util.Date; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; -import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State; + import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; +import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.UpdateBuilder; @Component @@ -50,8 +50,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = GenericQueryBuilder - .create(TemplatePrimaryDataStoreVO.class); + QueryBuilder sc = QueryBuilder.create(TemplatePrimaryDataStoreVO.class); sc.and(sc.entity().getTemplateId(), Op.EQ, templateId); sc.and(sc.entity().getPoolId(), Op.EQ, poolId); return sc.find(); @@ -59,8 +58,7 @@ public class TemplatePrimaryDataStoreDaoImpl extends GenericDaoBase sc = GenericQueryBuilder - .create(TemplatePrimaryDataStoreVO.class); + QueryBuilder sc = QueryBuilder.create(TemplatePrimaryDataStoreVO.class); sc.and(sc.entity().getTemplateId(), Op.EQ, templateId); sc.and(sc.entity().getPoolId(), Op.EQ, poolId); sc.and(sc.entity().getState(), Op.EQ, ObjectInDataStoreStateMachine.State.Ready); diff --git a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java index 570a10e1bca..885bebb2ab3 100755 --- a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java @@ -17,16 +17,13 @@ package com.cloud.utils.db; import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; -import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.db.SearchCriteria.Op; -public class GenericQueryBuilder extends SearchBase { +public class GenericQueryBuilder extends SearchBase, T, K> { final HashMap _params = new HashMap(); protected GenericQueryBuilder(Class entityType, Class resultType) { @@ -40,81 +37,31 @@ public class GenericQueryBuilder extends SearchBase { return new GenericQueryBuilder(entityType, resultType); } - static public GenericQueryBuilder create(Class entityType) { - return create(entityType, entityType); - } - - public GenericQueryBuilder or() { - constructCondition(null, " OR ", null, null); - return this; - } - - public void selectField(Object... useless) { - assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; - assert _specifiedAttrs.size() > 0 : "You didn't specify any attributes"; - - if (_selects == null) { - _selects = new ArrayList(); - } - - for (Attribute attr : _specifiedAttrs) { - Field field = null; - try { - field = _resultType.getDeclaredField(attr.field.getName()); - field.setAccessible(true); - } catch (SecurityException e) { - } catch (NoSuchFieldException e) { - } - _selects.add(new Select(Func.NATIVE, attr, field, null)); - } - - _specifiedAttrs.clear(); - - return this; - } - - /** - * Specifies the field to select. - * - * @param fieldName The field name of the result object to put the value of the field selected. This can be null if you're selecting only one field and the result is not a complex object. - * @param func function to place. - * @param useless column to select. Call this with this.entity() method. - * @param params parameters to the function. - * @return a SearchBuilder to build more search parts. - */ - public GenericSearchBuilder select(String fieldName, Func func, Object useless, Object... params) { - if (_entity == null) { - throw new RuntimeException("SearchBuilder cannot be modified once it has been setup"); - } - if (_specifiedAttrs.size() > 1) { - throw new RuntimeException("You can't specify more than one field to search on"); - } - if (func.getCount() != -1 && (func.getCount() != (params.length + 1))) { - throw new RuntimeException("The number of parameters does not match the function param count for " + func); - } - - if (_selects == null) { - _selects = new ArrayList _selects; - protected GroupBy, T, K> _groupBy = null; + protected GroupBy _groupBy = null; protected SelectType _selectType; T _entity; @@ -52,6 +65,134 @@ public abstract class SearchBase { _specifiedAttrs = new ArrayList(); } + /** + * Specifies how the search query should be grouped + * + * @param fields fields of the entity object that should be grouped on. The order is important. + * @return GroupBy object to perform more operations on. + * @see GroupBy + */ + @SuppressWarnings("unchecked") + public GroupBy groupBy(Object... fields) { + assert _groupBy == null : "Can't do more than one group bys"; + _groupBy = new GroupBy((J)this); + return _groupBy; + } + + /** + * Specifies what to select in the search. + * + * @param fieldName The field name of the result object to put the value of the field selected. This can be null if you're selecting only one field and the result is not a complex object. + * @param func function to place. + * @param field column to select. Call this with this.entity() method. + * @param params parameters to the function. + * @return itself to build more search parts. + */ + @SuppressWarnings("unchecked") + public J select(String fieldName, Func func, Object field, Object... params) { + if (_entity == null) { + throw new RuntimeException("SearchBuilder cannot be modified once it has been setup"); + } + if (_specifiedAttrs.size() > 1) { + throw new RuntimeException("You can't specify more than one field to search on"); + } + if (func.getCount() != -1 && (func.getCount() != (params.length + 1))) { + throw new RuntimeException("The number of parameters does not match the function param count for " + func); + } + + if (_selects == null) { + _selects = new ArrayList(); + } + + for (Attribute attr : _specifiedAttrs) { + Field field = null; + try { + field = _resultType.getDeclaredField(attr.field.getName()); + field.setAccessible(true); + } catch (SecurityException e) { + } catch (NoSuchFieldException e) { + } + _selects.add(new Select(Func.NATIVE, attr, field, null)); + } + + _specifiedAttrs.clear(); + + return (J)this; + } + + /** + * joins this search with another search + * + * @param name name given to the other search. used for setJoinParameters. + * @param builder The other search + * @param joinField1 field of the first table used to perform the join + * @param joinField2 field of the second table used to perform the join + * @param joinType type of join + * @return itself + */ + @SuppressWarnings("unchecked") + public J join(String name, SearchBase builder, Object joinField1, Object joinField2, JoinBuilder.JoinType joinType) { + assert _entity != null : "SearchBuilder cannot be modified once it has been setup"; + assert _specifiedAttrs.size() == 1 : "You didn't select the attribute."; + assert builder._entity != null : "SearchBuilder cannot be modified once it has been setup"; + assert builder._specifiedAttrs.size() == 1 : "You didn't select the attribute."; + assert builder != this : "You can't add yourself, can you? Really think about it!"; + + JoinBuilder> t = new JoinBuilder>(builder, _specifiedAttrs.get(0), builder._specifiedAttrs.get(0), joinType); + if (_joins == null) { + _joins = new HashMap>>(); + } + _joins.put(name, t); + + builder._specifiedAttrs.clear(); + _specifiedAttrs.clear(); + return (J)this; + } + public SelectType getSelectType() { return _selectType; } @@ -62,6 +203,10 @@ public abstract class SearchBase { _specifiedAttrs.add(attr); } + /** + * @return entity object. This allows the caller to use the entity return + * to specify the field to be selected in many of the search parameters. + */ public T entity() { return _entity; } @@ -100,11 +245,69 @@ public abstract class SearchBase { return new SearchCriteria(this); } + /** + * Adds an OR condition to the search. Normally you should use this to + * perform an 'OR' with a big conditional in parenthesis. For example, + * + * search.or().op(entity.getId(), Op.Eq, "abc").cp() + * + * The above fragment produces something similar to + * + * "OR (id = $abc) where abc is the token to be replaced by a value later. + * + * @return this + */ + @SuppressWarnings("unchecked") + public J or() { + constructCondition(null, " OR ", null, null); + return (J)this; + } + + /** + * Adds an AND condition to the search. Normally you should use this to + * perform an 'AND' with a big conditional in parenthesis. For example, + * + * search.and().op(entity.getId(), Op.Eq, "abc").cp() + * + * The above fragment produces something similar to + * + * "AND (id = $abc) where abc is the token to be replaced by a value later. + * + * @return this + */ + @SuppressWarnings("unchecked") + public J and() { + constructCondition(null, " AND ", null, null); + return (J)this; + } + + /** + * Closes a parenthesis that's started by op() + * @return this + */ + @SuppressWarnings("unchecked") + public J cp() { + Condition condition = new Condition(null, " ) ", null, Op.RP); + _conditions.add(condition); + return (J)this; + } + + /** + * Writes an open parenthesis into the search + * @return this + */ + @SuppressWarnings("unchecked") + public J op() { + Condition condition = new Condition(null, " ( ", null, Op.RP); + _conditions.add(condition); + return (J)this; + } + /** * Marks the SearchBuilder as completed in building the search conditions. */ @Override - public synchronized void finalize() { + protected synchronized void finalize() { if (_entity != null) { Factory factory = (Factory)_entity; factory.setCallback(0, null); @@ -112,7 +315,7 @@ public abstract class SearchBase { } if (_joins != null) { - for (JoinBuilder> join : _joins.values()) { + for (JoinBuilder> join : _joins.values()) { join.getT().finalize(); } } diff --git a/framework/db/src/com/cloud/utils/db/SearchCriteria.java b/framework/db/src/com/cloud/utils/db/SearchCriteria.java index a1f6408744c..3b20686fe3f 100755 --- a/framework/db/src/com/cloud/utils/db/SearchCriteria.java +++ b/framework/db/src/com/cloud/utils/db/SearchCriteria.java @@ -56,6 +56,7 @@ public class SearchCriteria { private final String op; int params; + Op(String op, int params) { this.op = op; this.params = params; @@ -113,27 +114,12 @@ public class SearchCriteria { private int _counter; private HashMap>> _joins; private final ArrayList selects, SelectType selectType, Class resultType, - HashMap params) { - this._attrs = attrs; - this._conditions = conditions; - this._selects = selects; - this._selectType = selectType; - this._resultType = resultType; - this._params = params; - this._additionals = new ArrayList(); - this._counter = 0; - this._joins = null; - this._groupBy = null; - this._groupByValues = null; - } - - protected SearchCriteria(SearchBase sb) { + protected SearchCriteria(SearchBase sb) { this._attrs = sb._attrs; this._conditions = sb._conditions; this._additionals = new ArrayList(); @@ -141,9 +127,9 @@ public class SearchCriteria { this._joins = null; if (sb._joins != null) { _joins = new HashMap>>(sb._joins.size()); - for (Map.Entry>> entry : sb._joins.entrySet()) { - JoinBuilder> value = entry.getValue(); - _joins.put(entry.getKey(), new JoinBuilder>(value.getT().create(),value.getFirstAttribute(), value.getSecondAttribute(), value.getType())); + for (Map.Entry>> entry : sb._joins.entrySet()) { + JoinBuilder> value = entry.getValue(); + _joins.put(entry.getKey(), new JoinBuilder>(value.getT().create(), value.getFirstAttribute(), value.getSecondAttribute(), value.getType())); } } _selects = sb._selects; @@ -157,6 +143,10 @@ public class SearchCriteria { _selectType = sb._selectType; } + protected void setParameters(HashMap parameters) { + _params = parameters; + } + public SelectType getSelectType() { return _selectType; } @@ -202,22 +192,22 @@ public class SearchCriteria { } protected JoinBuilder> findJoin(Map>> jbmap, String joinName) { - JoinBuilder> jb = jbmap.get(joinName); - if (jb != null) { - return jb; - } - - for (JoinBuilder> j2 : jbmap.values()) { - SearchCriteria sc = j2.getT(); - if(sc._joins != null) - jb = findJoin(sc._joins, joinName); - if (jb != null) { - return jb; - } - } - - assert (false) : "Unable to find a join by the name " + joinName; - return null; + JoinBuilder> jb = jbmap.get(joinName); + if (jb != null) { + return jb; + } + + for (JoinBuilder> j2 : jbmap.values()) { + SearchCriteria sc = j2.getT(); + if (sc._joins != null) + jb = findJoin(sc._joins, joinName); + if (jb != null) { + return jb; + } + } + + assert (false) : "Unable to find a join by the name " + joinName; + return null; } public void setJoinParameters(String joinName, String conditionName, Object... params) { @@ -227,18 +217,6 @@ public class SearchCriteria { } - public void addJoinAnd(String joinName, String field, Op op, Object... values) { - JoinBuilder> join = _joins.get(joinName); - assert (join != null) : "Incorrect join name specified: " + joinName; - join.getT().addAnd(field, op, values); - } - - public void addJoinOr(String joinName, String field, Op op, Object... values) { - JoinBuilder> join = _joins.get(joinName); - assert (join != null) : "Incorrect join name specified: " + joinName; - join.getT().addOr(field, op, values); - } - public SearchCriteria getJoin(String joinName) { return _joins.get(joinName).getT(); } @@ -257,30 +235,27 @@ public class SearchCriteria { return _resultType; } + @Deprecated public void addAnd(String field, Op op, Object... values) { String name = Integer.toString(_counter++); addCondition(name, " AND ", field, op); setParameters(name, values); } + @Deprecated public void addAnd(Attribute attr, Op op, Object... values) { String name = Integer.toString(_counter++); addCondition(name, " AND ", attr, op); setParameters(name, values); } + @Deprecated public void addOr(String field, Op op, Object... values) { String name = Integer.toString(_counter++); addCondition(name, " OR ", field, op); setParameters(name, values); } - public void addOr(Attribute attr, Op op, Object... values) { - String name = Integer.toString(_counter++); - addCondition(name, " OR ", attr, op); - setParameters(name, values); - } - protected void addCondition(String conditionName, String cond, String fieldName, Op op) { Attribute attr = _attrs.get(fieldName); assert attr != null : "Unable to find field: " + fieldName; diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java index c8a178e6a41..314c9577279 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BareMetalPingServiceImpl.java @@ -23,7 +23,6 @@ package com.cloud.baremetal.networkservice; import java.net.URI; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -36,7 +35,6 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.AddBaremetalPxeCmd; import org.apache.cloudstack.api.AddBaremetalPxePingServerCmd; import org.apache.cloudstack.api.ListBaremetalPxeServersCmd; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; @@ -62,9 +60,8 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ServerResource; import com.cloud.uservm.UserVm; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -84,7 +81,7 @@ public class BareMetalPingServiceImpl extends BareMetalPxeServiceBase implements @Override public boolean prepare(VirtualMachineProfile profile, NicProfile pxeNic, DeployDestination dest, ReservationContext context) { - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); + QueryBuilder sc = QueryBuilder.create(BaremetalPxeVO.class); sc.and(sc.entity().getDeviceType(), Op.EQ, BaremetalPxeType.PING.toString()); sc.and(sc.entity().getPodId(), Op.EQ, dest.getPod().getId()); BaremetalPxeVO pxeVo = sc.find(); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java index 930ca1bf609..9e1fd65a239 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalDhcpManagerImpl.java @@ -5,20 +5,20 @@ // 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. -// +// // Automatically generated by addcopyright.py at 01/29/2013 // Apache License, Version 2.0 (the "License"); you may not use this // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// +// // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.baremetal.networkservice; @@ -32,9 +32,10 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; + import org.apache.cloudstack.api.AddBaremetalDhcpCmd; import org.apache.cloudstack.api.ListBaremetalDhcpCmd; -import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -45,7 +46,6 @@ import com.cloud.baremetal.database.BaremetalDhcpDao; import com.cloud.baremetal.database.BaremetalDhcpVO; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenterVO; -import com.cloud.dc.HostPodVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.deploy.DeployDestination; @@ -67,14 +67,12 @@ import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.NicDao; import com.cloud.vm.dao.UserVmDao; @@ -311,7 +309,7 @@ public class BaremetalDhcpManagerImpl extends ManagerBase implements BaremetalDh return responses; } - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalDhcpVO.class); + QueryBuilder sc = QueryBuilder.create(BaremetalDhcpVO.class); if (cmd.getDeviceType() != null) { sc.and(sc.entity().getDeviceType(), Op.EQ, cmd.getDeviceType()); } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java index 661f39134c7..aa0ff1c0360 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalKickStartServiceImpl.java @@ -32,7 +32,6 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.AddBaremetalKickStartPxeCmd; import org.apache.cloudstack.api.AddBaremetalPxeCmd; import org.apache.cloudstack.api.ListBaremetalPxeServersCmd; -import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; @@ -57,9 +56,8 @@ import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.uservm.UserVm; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -87,7 +85,7 @@ public class BaremetalKickStartServiceImpl extends BareMetalPxeServiceBase imple @Override public boolean prepare(VirtualMachineProfile profile, NicProfile nic, DeployDestination dest, ReservationContext context) { NetworkVO nwVO = _nwDao.findById(nic.getNetworkId()); - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); + QueryBuilder sc = QueryBuilder.create(BaremetalPxeVO.class); sc.and(sc.entity().getDeviceType(), Op.EQ, BaremetalPxeType.KICK_START.toString()); sc.and(sc.entity().getPhysicalNetworkId(), Op.EQ, nwVO.getPhysicalNetworkId()); BaremetalPxeVO pxeVo = sc.find(); diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java index f869fe65461..244ce8c823c 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeElement.java @@ -5,16 +5,16 @@ // 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. -// +// // Automatically generated by addcopyright.py at 01/29/2013 package com.cloud.baremetal.networkservice; @@ -46,16 +46,14 @@ import com.cloud.network.element.NetworkElement; import com.cloud.offering.NetworkOffering; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; import com.cloud.vm.ReservationContext; import com.cloud.vm.VMInstanceVO; -import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.dao.NicDao; @@ -91,7 +89,7 @@ public class BaremetalPxeElement extends AdapterBase implements NetworkElement { private boolean canHandle(DeployDestination dest, TrafficType trafficType, GuestType networkType) { Pod pod = dest.getPod(); if (pod != null && dest.getDataCenter().getNetworkType() == NetworkType.Basic && trafficType == TrafficType.Guest) { - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); + QueryBuilder sc = QueryBuilder.create(BaremetalPxeVO.class); sc.and(sc.entity().getPodId(), Op.EQ, pod.getId()); return sc.find() != null; } diff --git a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java index ae3898bc315..ef6ec312d13 100755 --- a/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java +++ b/plugins/hypervisors/baremetal/src/com/cloud/baremetal/networkservice/BaremetalPxeManagerImpl.java @@ -36,9 +36,8 @@ import org.apache.log4j.Logger; import org.apache.cloudstack.api.AddBaremetalKickStartPxeCmd; import org.apache.cloudstack.api.AddBaremetalPxeCmd; import org.apache.cloudstack.api.AddBaremetalPxePingServerCmd; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.api.ListBaremetalPxeServersCmd; -import org.apache.log4j.Logger; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -62,9 +61,8 @@ import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.uservm.UserVm; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; @@ -220,7 +218,7 @@ public class BaremetalPxeManagerImpl extends ManagerBase implements BaremetalPxe } PhysicalNetworkVO phy = phys.get(0); - GenericQueryBuilder sc = GenericQueryBuilder.create(BaremetalPxeVO.class); + QueryBuilder sc = QueryBuilder.create(BaremetalPxeVO.class); //TODO: handle both kickstart and PING //sc.addAnd(sc.getEntity().getPodId(), Op.EQ, vm.getPodIdToDeployIn()); sc.and(sc.entity().getPhysicalNetworkId(), Op.EQ, phy.getId()); diff --git a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java index dec4a79a425..8da9da086af 100755 --- a/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java +++ b/plugins/hypervisors/ucs/src/com/cloud/ucs/manager/UcsManagerImpl.java @@ -30,8 +30,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.log4j.Logger; + import org.apache.cloudstack.api.AddUcsManagerCmd; import org.apache.cloudstack.api.AssociateUcsProfileToBladeCmd; +import org.apache.cloudstack.api.DeleteUcsManagerCmd; import org.apache.cloudstack.api.ListUcsBladeCmd; import org.apache.cloudstack.api.ListUcsManagerCmd; import org.apache.cloudstack.api.ListUcsProfileCmd; @@ -40,8 +43,6 @@ import org.apache.cloudstack.api.response.UcsBladeResponse; import org.apache.cloudstack.api.response.UcsManagerResponse; import org.apache.cloudstack.api.response.UcsProfileResponse; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.log4j.Logger; -import org.apache.cloudstack.api.DeleteUcsManagerCmd; import com.cloud.configuration.Config; import com.cloud.dc.ClusterDetailsDao; @@ -60,9 +61,8 @@ import com.cloud.ucs.structure.UcsCookie; import com.cloud.ucs.structure.UcsProfile; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.xmlobject.XmlObject; @@ -132,7 +132,7 @@ public class UcsManagerImpl implements UcsManager { } private void syncBlades(UcsManagerVO mgr) { - GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); + QueryBuilder q = QueryBuilder.create(UcsBladeVO.class); q.and(q.entity().getUcsManagerId(), Op.EQ, mgr.getId()); List pblades = q.list(); if (pblades.isEmpty()) { @@ -210,7 +210,7 @@ public class UcsManagerImpl implements UcsManager { @Override @DB public UcsManagerResponse addUcsManager(AddUcsManagerCmd cmd) { - GenericQueryBuilder q = GenericQueryBuilder.create(UcsManagerVO.class); + QueryBuilder q = QueryBuilder.create(UcsManagerVO.class); q.and(q.entity().getUrl(), Op.EQ, cmd.getUrl()); UcsManagerVO mgrvo = q.find(); if (mgrvo != null) { @@ -342,7 +342,7 @@ public class UcsManagerImpl implements UcsManager { @Override public UcsBladeResponse associateProfileToBlade(AssociateUcsProfileToBladeCmd cmd) { - GenericQueryBuilder q = GenericQueryBuilder.create(UcsBladeVO.class); + QueryBuilder q = QueryBuilder.create(UcsBladeVO.class); q.and(q.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); q.and(q.entity().getId(), Op.EQ, cmd.getBladeId()); UcsBladeVO bvo = q.find(); @@ -424,7 +424,7 @@ public class UcsManagerImpl implements UcsManager { return response; } - GenericQueryBuilder serv = GenericQueryBuilder.create(UcsManagerVO.class); + QueryBuilder serv = QueryBuilder.create(UcsManagerVO.class); serv.and(serv.entity().getZoneId(), Op.EQ, cmd.getZoneId()); List vos = serv.list(); @@ -454,7 +454,7 @@ public class UcsManagerImpl implements UcsManager { @Override public ListResponse listUcsBlades(ListUcsBladeCmd cmd) { - GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); + QueryBuilder serv = QueryBuilder.create(UcsBladeVO.class); serv.and(serv.entity().getUcsManagerId(), Op.EQ, cmd.getUcsManagerId()); List vos = serv.list(); @@ -509,7 +509,7 @@ public class UcsManagerImpl implements UcsManager { @Override public void deleteUcsManager(Long id) { - GenericQueryBuilder serv = GenericQueryBuilder.create(UcsBladeVO.class); + QueryBuilder serv = QueryBuilder.create(UcsBladeVO.class); serv.and(serv.entity().getUcsManagerId(), Op.EQ, id); List vos = serv.list(); for (UcsBladeVO vo : vos) { diff --git a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java index bb357cabd64..bb058e3d175 100755 --- a/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java +++ b/plugins/hypervisors/xen/src/com/cloud/hypervisor/xen/discoverer/XcpServerDiscoverer.java @@ -16,6 +16,31 @@ // under the License. package com.cloud.hypervisor.xen.discoverer; +import java.net.InetAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +import javax.ejb.Local; +import javax.inject.Inject; +import javax.naming.ConfigurationException; +import javax.persistence.EntityExistsException; + +import org.apache.log4j.Logger; +import org.apache.xmlrpc.XmlRpcException; + +import com.xensource.xenapi.Connection; +import com.xensource.xenapi.Host; +import com.xensource.xenapi.Pool; +import com.xensource.xenapi.Session; +import com.xensource.xenapi.Types.SessionAuthenticationFailed; +import com.xensource.xenapi.Types.XenAPIException; + import com.cloud.agent.AgentManager; import com.cloud.agent.Listener; import com.cloud.agent.api.AgentControlAnswer; @@ -69,33 +94,10 @@ import com.cloud.storage.VMTemplateVO; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; import com.cloud.utils.NumbersUtil; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.HypervisorVersionChangedException; -import com.xensource.xenapi.Connection; -import com.xensource.xenapi.Host; -import com.xensource.xenapi.Pool; -import com.xensource.xenapi.Session; -import com.xensource.xenapi.Types.SessionAuthenticationFailed; -import com.xensource.xenapi.Types.XenAPIException; -import org.apache.log4j.Logger; -import org.apache.xmlrpc.XmlRpcException; - -import javax.ejb.Local; -import javax.inject.Inject; -import javax.naming.ConfigurationException; -import javax.persistence.EntityExistsException; -import java.net.InetAddress; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; @Local(value=Discoverer.class) public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter { @@ -126,7 +128,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L try { _clusterDao.update(cluster.getId(), cluster); } catch (EntityExistsException e) { - GenericQueryBuilder sc = GenericQueryBuilder.create(ClusterVO.class); + QueryBuilder sc = QueryBuilder.create(ClusterVO.class); sc.and(sc.entity().getGuid(), Op.EQ, guid); List clusters = sc.list(); ClusterVO clu = clusters.get(0); diff --git a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java index 385ca3625dc..e29bb2bc04a 100644 --- a/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java +++ b/server/src/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java @@ -21,20 +21,17 @@ import java.util.List; import javax.ejb.Local; import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.api.query.vo.DiskOfferingJoinVO; -import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.DiskOfferingVO.Type; import com.cloud.utils.db.Attribute; -import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.SearchCriteria.Op; -import org.springframework.stereotype.Component; @Component @Local(value={DiskOfferingJoinDao.class}) @@ -42,7 +39,7 @@ public class DiskOfferingJoinDaoImpl extends GenericDaoBase dofIdSearch; + private final SearchBuilder dofIdSearch; private final Attribute _typeAttr; protected DiskOfferingJoinDaoImpl() { @@ -53,7 +50,7 @@ public class DiskOfferingJoinDaoImpl extends GenericDaoBase searchIncludingRemoved(SearchCriteria sc, final Filter filter, final Boolean lock, final boolean cache) { - sc.addAnd(_typeAttr, Op.EQ, Type.Disk); - return super.searchIncludingRemoved(sc, filter, lock, cache); - } - - @Override - public List customSearchIncludingRemoved(SearchCriteria sc, final Filter filter) { - sc.addAnd(_typeAttr, Op.EQ, Type.Disk); - return super.customSearchIncludingRemoved(sc, filter); - } } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index b6b9bb5114c..d51eb41c24f 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -117,9 +117,8 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.GlobalLock; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.events.SubscriptionMgr; import com.cloud.utils.exception.CloudRuntimeException; @@ -1693,7 +1692,7 @@ VirtualMachineGuru, SystemVmLoadScanHandler, ResourceStateAdapter { } protected HostVO findConsoleProxyHostByName(String name) { - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getType(), Op.EQ, Host.Type.ConsoleProxy); sc.and(sc.entity().getName(), Op.EQ, name); return sc.find(); diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index 2c6414e1097..c0cb2894fc0 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -20,18 +20,17 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; -import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.springframework.stereotype.Component; import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.ListStorageNetworkIpRangeCmd; import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; import com.cloud.dc.HostPodVO; import com.cloud.dc.StorageNetworkIpAddressVO; @@ -46,9 +45,8 @@ import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkVO; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.db.DB; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.net.NetUtils; @@ -339,7 +337,7 @@ public class StorageNetworkManagerImpl extends ManagerBase implements StorageNet @Override public boolean isStorageIpRangeAvailable(long zoneId) { - GenericQueryBuilder sc = GenericQueryBuilder.create(StorageNetworkIpRangeVO.class); + QueryBuilder sc = QueryBuilder.create(StorageNetworkIpRangeVO.class); sc.and(sc.entity().getDataCenterId(), Op.EQ, zoneId); List entries = sc.list(); return entries.size() > 0; diff --git a/server/src/com/cloud/storage/OCFS2ManagerImpl.java b/server/src/com/cloud/storage/OCFS2ManagerImpl.java index e38ca5bae2f..505a18dc2ad 100755 --- a/server/src/com/cloud/storage/OCFS2ManagerImpl.java +++ b/server/src/com/cloud/storage/OCFS2ManagerImpl.java @@ -25,11 +25,12 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; -import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; + import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.PrepareOCFS2NodesCommand; @@ -47,9 +48,8 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.dao.StoragePoolHostDao; import com.cloud.utils.Ternary; import com.cloud.utils.component.ManagerBase; +import com.cloud.utils.db.QueryBuilder; import com.cloud.utils.db.SearchCriteria.Op; -import com.cloud.utils.db.GenericQueryBuilder; -import com.cloud.utils.db.GenericQueryBuilder; import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -141,7 +141,7 @@ public class OCFS2ManagerImpl extends ManagerBase implements OCFS2Manager, Resou throw new CloudRuntimeException("Cannot find cluster for ID " + clusterId); } - GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class); + QueryBuilder sc = QueryBuilder.create(HostVO.class); sc.and(sc.entity().getClusterId(), Op.EQ, clusterId); sc.and(sc.entity().getPodId(), Op.EQ, cluster.getPodId()); sc.and(sc.entity().getDataCenterId(), Op.EQ, cluster.getDataCenterId()); From b998fba4da4909915b36ae93f826808eeee327b1 Mon Sep 17 00:00:00 2001 From: Alex Huang Date: Sat, 28 Sep 2013 11:50:02 -0700 Subject: [PATCH 08/27] Added comments for the search builder classes on how to use them --- .../cloud/utils/db/GenericQueryBuilder.java | 96 +++++++++++++++++-- .../cloud/utils/db/GenericSearchBuilder.java | 66 ++++++++++++- 2 files changed, 149 insertions(+), 13 deletions(-) diff --git a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java index 885bebb2ab3..28cfebc5f94 100755 --- a/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericQueryBuilder.java @@ -23,6 +23,39 @@ import java.util.UUID; import com.cloud.utils.db.SearchCriteria.Op; +/** + * GenericQueryBuilder builds a search query during runtime. It allows the + * search query to be built completely in Java rather than part SQL fragments + * and part entity field like HQL or JPQL. This class is different from + * GenericSearchBuilder in that it is used for building queries during runtime + * where GenericSearchBuilder expects the query to be built during load time + * and parameterized values to be set during runtime. + * + * GenericQueryBuilder allows results to be a native type, the entity bean, + * and a composite type. If you are just retrieving the entity bean, there + * is a simpler class called QueryBuilder that you can use. The usage + * is approximately the same. + * + * + * // Note that in the following search, it selects a func COUNT to be the + * // return result so for the second parameterized type is long. + * // Note the entity object itself must have came from search and + * // it uses the getters of the object to retrieve the field used in the search. + * + * GenericQueryBuilder sc = GenericQueryBuilder.create(HostVO.class, Long.class); + * HostVO entity = CountSearch.entity(); + * sc.select(null, FUNC.COUNT, null, null).where(entity.getType(), Op.EQ, Host.Type.Routing); + * sc.and(entity.getCreated(), Op.LT, new Date()); + * Long count = sc.find(); + * + * * + * + * @see GenericSearchBuilder + * @see QueryBuilder + * + * @param Entity object to perform the search on + * @param Result object + */ public class GenericQueryBuilder extends SearchBase, T, K> { final HashMap _params = new HashMap(); @@ -30,6 +63,12 @@ public class GenericQueryBuilder extends SearchBase GenericQueryBuilder create(Class entityType, Class resultType) { GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); @@ -37,31 +76,60 @@ public class GenericQueryBuilder extends SearchBase(entityType, resultType); } - public GenericQueryBuilder and(Object useless, Op op, Object... values) { + /** + * Adds AND search condition + * + * @param field the field of the entity to perform the search on. + * @param op operator + * @param values parameterized values + * @return this + */ + public GenericQueryBuilder and(Object field, Op op, Object... values) { String uuid = UUID.randomUUID().toString(); constructCondition(uuid, " AND ", _specifiedAttrs.get(0), op); _params.put(uuid, values); return this; } - public GenericQueryBuilder or(Object useless, Op op, Object... values) { + /** + * Adds OR search condition + * + * @param field the field of the entity to perform the search on. + * @param op operator + * @param values parameterized values + * @return this + */ + public GenericQueryBuilder or(Object field, Op op, Object... values) { String uuid = UUID.randomUUID().toString(); constructCondition(uuid, " OR ", _specifiedAttrs.get(0), op); _params.put(uuid, values); return this; } - protected GenericQueryBuilder left(Object useless, Op op, Object... values) { + protected GenericQueryBuilder left(Object field, Op op, Object... values) { String uuid = UUID.randomUUID().toString(); constructCondition(uuid, " ( ", _specifiedAttrs.get(0), op); _params.put(uuid, values); return this; } - public GenericQueryBuilder op(Object useless, Op op, Object... values) { - return left(useless, op, values); + /** + * Adds search condition that starts with an open parenthesis. Call cp() + * to close the parenthesis. + * + * @param field the field of the entity to perform the search on. + * @param op operator + * @param values parameterized values + * @return this + */ + public GenericQueryBuilder op(Object field, Op op, Object... values) { + return left(field, op, values); } + /** + * If the query is supposed to return a list, use this. + * @return List of result objects + */ @SuppressWarnings("unchecked") public List list() { finalize(); @@ -75,6 +143,9 @@ public class GenericQueryBuilder extends SearchBase create() { SearchCriteria sc = super.create(); @@ -86,11 +157,20 @@ public class GenericQueryBuilder extends SearchBase lst = list(); + return lst.get(0); + } } } diff --git a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java index b9bef61beeb..72ad278730b 100755 --- a/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java +++ b/framework/db/src/com/cloud/utils/db/GenericSearchBuilder.java @@ -36,6 +36,28 @@ import com.cloud.utils.db.SearchCriteria.Op; * runtime and, more importantly, the proper construction can be checked when * components are being loaded. However, if you prefer to just construct * the entire search at runtime, you can use GenericQueryBuilder. + * + * + * // To specify the GenericSearchBuilder, you should do this at load time. + * // Note that in the following search, it selects a func COUNT to be the + * // return result so for the second parameterized type is long. It also + * // presets the type in the search and declares created to be set during + * // runtime. Note the entity object itself must have came from search and + * // it uses the getters of the object to retrieve the field used in the search. + * + * GenericSearchBuilder CountSearch = _hostDao.createSearchBuilder(Long.class); + * HostVO entity = CountSearch.entity(); + * CountSearch.select(null, FUNC.COUNT, null, null).where(entity.getType(), Op.EQ).value(Host.Type.Routing); + * CountSearch.and(entity.getCreated(), Op.LT, "create_date").done(); + * + * // Later in the code during runtime + * SearchCriteria sc = CountSearch.create(); + * sc.setParameter("create_date", new Date()); + * Long count = _hostDao.customizedSearch(sc, null); + * + * + * @see GenericQueryBuilder for runtime construction of search query + * @see SearchBuilder for returning VO objects itself * * @param VO object this Search is build for. * @param Result object that should contain the results. @@ -118,11 +140,13 @@ public class GenericSearchBuilder extends SearchBase op(Object field, Op op, String name) { return left(field, op, name); @@ -132,6 +156,15 @@ public class GenericSearchBuilder extends SearchBase op(String name, Object field, Op op) { return left(field, op, name); } @@ -149,16 +182,39 @@ public class GenericSearchBuilder extends SearchBase or(Object field, Op op, String name) { constructCondition(name, " OR ", _specifiedAttrs.get(0), op); return this; } + /** + * Adds an OR condition but the values can be preset + * + * @param field field of the entity object + * @param op operator + * @return Preset + */ public Preset or(Object field, Op op) { Condition condition = constructCondition(UUID.randomUUID().toString(), " OR ", _specifiedAttrs.get(0), op); return new Preset(this, condition); } + /** + * Convenience method to create the search criteria and set a + * parameter in the search. + * + * @param name parameter name set during construction + * @param values values to be inserted for that parameter + * @return SearchCriteria + */ public SearchCriteria create(String name, Object... values) { SearchCriteria sc = create(); sc.setParameters(name, values); From 43770e0cb25c7ea2fd3a12dab652d5f312635ec6 Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Sat, 28 Sep 2013 20:42:52 -0700 Subject: [PATCH 09/27] CLOUDSTACK-4744: enhanced root admin API updateVolume with state/storageId parameters as a part of "Better control over first party objects" feature. Also fixed existing bugs for the API: * corrected action event to be VOLUME.UPDATE (was VOLUME.ATTACH) * all parameters to update, should be optional - fixed that. If nothing is specified, the db object will remain with its original fields --- api/src/com/cloud/event/EventTypes.java | 2 + .../com/cloud/storage/VolumeApiService.java | 2 +- .../command/user/volume/UpdateVolumeCmd.java | 47 ++++++++++++++----- .../src/com/cloud/storage/VolumeVO.java | 7 +++ .../cloud/storage/VolumeApiServiceImpl.java | 38 ++++++++++----- 5 files changed, 72 insertions(+), 24 deletions(-) diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index b3aa91a442a..ec9604e3f90 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -188,6 +188,8 @@ public class EventTypes { public static final String EVENT_VOLUME_DETAIL_UPDATE = "VOLUME.DETAIL.UPDATE"; public static final String EVENT_VOLUME_DETAIL_ADD = "VOLUME.DETAIL.ADD"; public static final String EVENT_VOLUME_DETAIL_REMOVE = "VOLUME.DETAIL.REMOVE"; + public static final String EVENT_VOLUME_UPDATE = "VOLUME.UPDATE"; + // Domains public static final String EVENT_DOMAIN_CREATE = "DOMAIN.CREATE"; diff --git a/api/src/com/cloud/storage/VolumeApiService.java b/api/src/com/cloud/storage/VolumeApiService.java index 0194c817cac..e8fb8de9aca 100644 --- a/api/src/com/cloud/storage/VolumeApiService.java +++ b/api/src/com/cloud/storage/VolumeApiService.java @@ -84,7 +84,7 @@ public interface VolumeApiService { Snapshot allocSnapshot(Long volumeId, Long policyId) throws ResourceAllocationException; - Volume updateVolume(UpdateVolumeCmd updateVolumeCmd); + Volume updateVolume(long volumeId, String path, String state, Long storageId); /** * Extracts the volume to a particular location. diff --git a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java index ad7c9920ad4..bc17b2e22c0 100644 --- a/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UpdateVolumeCmd.java @@ -23,15 +23,14 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; -import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.cloudstack.context.CallContext; - import org.apache.log4j.Logger; import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; import com.cloud.storage.Volume; -import com.cloud.user.Account; @APICommand(name = "updateVolume", description="Updates the volume.", responseObject=VolumeResponse.class) public class UpdateVolumeCmd extends BaseAsyncCmd { @@ -42,13 +41,18 @@ public class UpdateVolumeCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, - required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, description="the ID of the disk volume") private Long id; - @Parameter(name=ApiConstants.PATH, type=CommandType.STRING, - required=true, description="the path of the volume") + @Parameter(name=ApiConstants.PATH, type=CommandType.STRING, description="The path of the volume") private String path; + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="Destination storage pool UUID for the volume", since="4.3") + private Long storageId; + + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="The state of the volume", since="4.3") + private String state; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -61,6 +65,15 @@ public class UpdateVolumeCmd extends BaseAsyncCmd { public Long getId() { return id; } + + public Long getStorageId() { + return storageId; + } + + public String getState() { + return state; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -83,25 +96,37 @@ public class UpdateVolumeCmd extends BaseAsyncCmd { public long getEntityOwnerId() { Volume volume = _responseGenerator.findVolumeById(getId()); if (volume == null) { - return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked + throw new InvalidParameterValueException("Invalid volume id was provided"); } return volume.getAccountId(); } @Override public String getEventType() { - return EventTypes.EVENT_VOLUME_ATTACH; + return EventTypes.EVENT_VOLUME_UPDATE; } @Override public String getEventDescription() { - return "adding detail to the volume: " + getId(); + StringBuffer desc = new StringBuffer(); + desc.append(" with"); + if (getPath() != null) { + desc.append(" path " + getPath()); + } + if (getStorageId() != null) { + desc.append(", storage id " + getStorageId()); + } + + if (getState() != null) { + desc.append(", state " + getState()); + } + return "Updating volume: " + getId() + desc.toString(); } @Override public void execute(){ CallContext.current().setEventDetails("Volume Id: "+getId()); - Volume result = _volumeService.updateVolume(this); + Volume result = _volumeService.updateVolume(getId(), getPath(), getState(), getStorageId()); if (result != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(result); response.setResponseName(getCommandName()); diff --git a/engine/schema/src/com/cloud/storage/VolumeVO.java b/engine/schema/src/com/cloud/storage/VolumeVO.java index ea3d6bffa67..43a8d4c571b 100755 --- a/engine/schema/src/com/cloud/storage/VolumeVO.java +++ b/engine/schema/src/com/cloud/storage/VolumeVO.java @@ -35,6 +35,7 @@ import javax.persistence.Transient; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; @Entity @Table(name = "volumes") @@ -573,4 +574,10 @@ public class VolumeVO implements Volume { public void setIsoId(long isoId) { this.isoId =isoId; } + + // don't use this directly, use volume state machine instead + // This method is used by UpdateVolume as a part of "Better control over first class objects in CS" + public void setState(State state) { + this.state = state; + } } diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java index 16eecd60bc3..b573786e0bf 100644 --- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java @@ -25,8 +25,6 @@ import java.util.concurrent.ExecutionException; import javax.inject.Inject; -import org.apache.log4j.Logger; - import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; @@ -34,7 +32,6 @@ import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; import org.apache.cloudstack.api.command.user.volume.MigrateVolumeCmd; import org.apache.cloudstack.api.command.user.volume.ResizeVolumeCmd; -import org.apache.cloudstack.api.command.user.volume.UpdateVolumeCmd; import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.orchestration.service.VolumeOrchestrationService; @@ -67,6 +64,7 @@ import org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; import org.apache.cloudstack.storage.image.datastore.ImageStoreEntity; +import org.apache.log4j.Logger; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; @@ -1108,16 +1106,32 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic } @Override - public Volume updateVolume(UpdateVolumeCmd cmd) { - Long volumeId = cmd.getId(); - String path = cmd.getPath(); - - if (path == null) { - throw new InvalidParameterValueException("Failed to update the volume as path was null"); + @ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPDATE, eventDescription = "updating volume", async = true) + public Volume updateVolume(long volumeId, String path, String state, Long storageId) { + VolumeVO volume = _volumeDao.findById(volumeId); + + if (path != null) { + volume.setPath(path); } - - VolumeVO volume = ApiDBUtils.findVolumeById(volumeId); - volume.setPath(path); + + if (state != null) { + try { + Volume.State volumeState = Volume.State.valueOf(state); + volume.setState(volumeState); + } + catch(IllegalArgumentException ex) { + throw new InvalidParameterValueException("Invalid volume state specified"); + } + } + + if (storageId != null) { + StoragePool pool = _storagePoolDao.findById(storageId); + if (pool.getDataCenterId() != volume.getDataCenterId()) { + throw new InvalidParameterValueException("Invalid storageId specified; refers to the pool outside of the volume's zone"); + } + volume.setPoolId(pool.getId()); + } + _volumeDao.update(volumeId, volume); return volume; From 3ae80acb4015d3304b36e64615d26200c968445b Mon Sep 17 00:00:00 2001 From: Alena Prokharchyk Date: Sat, 28 Sep 2013 22:18:27 -0700 Subject: [PATCH 10/27] Added missing license to SearchBase.java - fixed broken RAT check --- .../db/src/com/cloud/utils/db/SearchBase.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/framework/db/src/com/cloud/utils/db/SearchBase.java b/framework/db/src/com/cloud/utils/db/SearchBase.java index 99c4679af9d..eb2b64b5d15 100644 --- a/framework/db/src/com/cloud/utils/db/SearchBase.java +++ b/framework/db/src/com/cloud/utils/db/SearchBase.java @@ -1,3 +1,20 @@ +// 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.utils.db; import java.io.Serializable; From e6fd794ca0b10a00f3fc93e5f3e81ab342f5b860 Mon Sep 17 00:00:00 2001 From: Wido den Hollander Date: Sun, 29 Sep 2013 12:22:46 +0200 Subject: [PATCH 11/27] packaging: Do not depend on JNA and don't include it in the classpath It's now packaged with maven due to libvirt 0.5.1 and will be included in the classpath automatically. --- debian/control | 2 +- packaging/centos63/cloud-agent.rc | 3 +-- packaging/centos63/cloud.spec | 1 - packaging/debian/init/cloud-agent | 3 +-- 4 files changed, 3 insertions(+), 6 deletions(-) diff --git a/debian/control b/debian/control index e6d1ef088f2..b20743da0a9 100644 --- a/debian/control +++ b/debian/control @@ -22,7 +22,7 @@ Description: CloudStack server library Package: cloudstack-agent Architecture: all -Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, libjna-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt +Depends: openjdk-6-jre | openjdk-7-jre, cloudstack-common (= ${source:Version}), lsb-base (>= 3.2), libcommons-daemon-java, openssh-client, libvirt0, sysvinit-utils, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, perl-base, perl-modules, ebtables, vlan, wget, jsvc, ipset, python-libvirt Conflicts: cloud-agent, cloud-agent-libs, cloud-agent-deps, cloud-agent-scripts Description: CloudStack agent The CloudStack agent is in charge of managing shared computing resources in diff --git a/packaging/centos63/cloud-agent.rc b/packaging/centos63/cloud-agent.rc index b3784882975..ab49524af4b 100755 --- a/packaging/centos63/cloud-agent.rc +++ b/packaging/centos63/cloud-agent.rc @@ -61,8 +61,7 @@ PCP=`ls /usr/share/cloudstack-agent/plugins/*.jar 2>/dev/null | tr '\n' ':' | se # We need to append the JSVC daemon JAR to the classpath # AgentShell implements the JSVC daemon methods -# We also need JNA in the classpath (from the distribution) for the Libvirt Java bindings -export CLASSPATH="/usr/share/java/commons-daemon.jar:/usr/share/java/jna.jar:$ACP:$PCP:/etc/cloudstack/agent:/usr/share/cloudstack-common/scripts" +export CLASSPATH="/usr/share/java/commons-daemon.jar:$ACP:$PCP:/etc/cloudstack/agent:/usr/share/cloudstack-common/scripts" start() { echo -n $"Starting $PROGNAME: " diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec index b5174c5ae40..17fb2b13308 100644 --- a/packaging/centos63/cloud.spec +++ b/packaging/centos63/cloud.spec @@ -112,7 +112,6 @@ The Apache CloudStack files shared between agent and management server %package agent Summary: CloudStack Agent for KVM hypervisors Requires: java >= 1.6.0 -Requires: jna >= 3.2.4 Requires: %{name}-common = %{_ver} Requires: libvirt Requires: bridge-utils diff --git a/packaging/debian/init/cloud-agent b/packaging/debian/init/cloud-agent index 29f64881626..e7338752f3e 100755 --- a/packaging/debian/init/cloud-agent +++ b/packaging/debian/init/cloud-agent @@ -60,8 +60,7 @@ PCP=`ls /usr/share/cloudstack-agent/plugins/*.jar 2>/dev/null | tr '\n' ':' | se # We need to append the JSVC daemon JAR to the classpath # AgentShell implements the JSVC daemon methods -# We also need JNA in the classpath (from the distribution) for the Libvirt Java bindings -export CLASSPATH="/usr/share/java/commons-daemon.jar:/usr/share/java/jna.jar:$ACP:$PCP:/etc/cloudstack/agent" +export CLASSPATH="/usr/share/java/commons-daemon.jar:$ACP:$PCP:/etc/cloudstack/agent" wait_for_network() { i=1 From ff0f7389739b4792613d1c8da6326affd2c1e5f8 Mon Sep 17 00:00:00 2001 From: SrikanteswaraRao Talluri Date: Tue, 17 Sep 2013 15:59:34 +0530 Subject: [PATCH 12/27] CLOUDSTACK-4344: pass delay and retries explicitly to remoteSSHclient to reduce time taken by the tests Signed-off-by: venkataswamybabu budumuru (cherry picked from commit 94f741bbf5e025c230172df2977a0986c5b73ec2) --- test/integration/smoke/test_network.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/test/integration/smoke/test_network.py b/test/integration/smoke/test_network.py index 042ac84ae53..f2045959697 100644 --- a/test/integration/smoke/test_network.py +++ b/test/integration/smoke/test_network.py @@ -464,7 +464,9 @@ class TestPortForwarding(cloudstackTestCase): src_nat_ip_addr.ipaddress, self.virtual_machine.ssh_port, self.virtual_machine.username, - self.virtual_machine.password + self.virtual_machine.password, + retries=2, + delay=0 ) return @@ -580,7 +582,9 @@ class TestPortForwarding(cloudstackTestCase): ip_address.ipaddress.ipaddress, self.virtual_machine.ssh_port, self.virtual_machine.username, - self.virtual_machine.password + self.virtual_machine.password, + retries=2, + delay=0 ) return @@ -883,7 +887,9 @@ class TestReleaseIP(cloudstackTestCase): self.ip_addr.ipaddress, self.services["natrule"]["publicport"], self.virtual_machine.username, - self.virtual_machine.password + self.virtual_machine.password, + retries=2, + delay=0 ) return From ff2bd3d44325ef915cb3d7b11a966c9c7c387cb3 Mon Sep 17 00:00:00 2001 From: sanjeevneelarapu Date: Mon, 23 Sep 2013 16:41:11 +0530 Subject: [PATCH 13/27] CLOUDSTACK-702: Adding test for deploying vm in new cidr 1. Add guest ip range in new cidr and deploy vm in that Signed-off-by: sanjeevneelarapu Signed-off-by: venkataswamybabu budumuru --- .../maint/test_multiple_ip_ranges.py | 337 ++++++++++++++++++ 1 file changed, 337 insertions(+) create mode 100644 test/integration/component/maint/test_multiple_ip_ranges.py diff --git a/test/integration/component/maint/test_multiple_ip_ranges.py b/test/integration/component/maint/test_multiple_ip_ranges.py new file mode 100644 index 00000000000..782957c6717 --- /dev/null +++ b/test/integration/component/maint/test_multiple_ip_ranges.py @@ -0,0 +1,337 @@ +# 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. +""" Tests for Multiple IP Ranges feature +""" +from marvin.cloudstackTestCase import * +from marvin.cloudstackAPI import * +from marvin.cloudstackException import cloudstackAPIException +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * +#from netaddr import * +import netaddr + +from nose.plugins.attrib import attr + +class Services: + """Test Multiple IP Ranges + """ + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + # Random characters are appended for unique + # username + "password": "password", + }, + "service_offering": { + "name": "Tiny Instance", + "displaytext": "Tiny Instance", + "cpunumber": 1, + "cpuspeed": 200, # in MHz + "memory": 256, # In MBs + }, + "disk_offering": { + "displaytext": "Small Disk", + "name": "Small Disk", + "disksize": 1 + }, + "templates": { + "displaytext": 'Template', + "name": 'Template', + "ostype": "CentOS 5.3 (64-bit)", + "templatefilter": 'self', + }, + "vlan_ip_range": { + "startip": "", + "endip": "", + "netmask": "", + "gateway": "", + "forvirtualnetwork": "false", + "vlan": "untagged", + }, + "server_without_disk": { + "displayname": "Test VM-No Disk", + "username": "root", + "password": "password", + "hypervisor": 'XenServer', + }, + "cidr": { + "name": "cidr1 -Test", + "gateway" :"10.147.43.1", + "netmask" :"255.255.255.128", + "startip" :"10.147.43.3", + "endip" :"10.147.43.10", + }, + "ostype": "CentOS 5.3 (64-bit)", + "sleep": 60, + "timeout": 10, + } + +class TestMultipleIpRanges(cloudstackTestCase): + """Test Multiple IP Ranges for guest network + """ + + + @classmethod + def setUpClass(cls): + cls.api_client = super(TestMultipleIpRanges, cls).getClsTestClient().getApiClient() + cls.services = Services().services + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + cls.pod = get_pod(cls.api_client, cls.zone.id, cls.services) + cls.services['mode'] = cls.zone.networktype + cls.services["domainid"] = cls.domain.id + cls.services["zoneid"] = cls.zone.id + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + cls.services["account"] = cls.account.name + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostype"] + ) + cls.services["templates"]["ostypeid"] = cls.template.ostypeid + cls.services["diskoffering"] = cls.disk_offering.id + cls._cleanup = [ + cls.account, + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.api_client, cls._cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def setUp(self): + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [ ] + return + + def tearDown(self): + try: + #Clean up, terminate the resources created + cleanup_resources(self.apiclient, self.cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def verify_vlan_range(self,vlan,services): + #compare vlan_list response with configured values + self.assertEqual( + isinstance(vlan, list), + True, + "Check list response returned a valid list" + ) + self.assertNotEqual( + len(vlan), + 0, + "check list vlan response" + ) + self.assertEqual( + str(vlan[0].startip), + str(services["startip"]), + "Start IP in vlan ip range is not matched with the configured start ip" + ) + self.assertEqual( + str(vlan[0].endip), + str(services["endip"]), + "End IP in vlan ip range is not matched with the configured end ip" + ) + self.assertEqual( + str(vlan[0].gateway), + str(services["gateway"]), + "gateway in vlan ip range is not matched with the configured gateway" + ) + self.assertEqual( + str(vlan[0].netmask), + str(services["netmask"]), + "netmask in vlan ip range is not matched with the configured netmask" + ) + return + + def list_Routers(self): + """Check if any VR is already present in the setup + Will return True if yes else return False + """ + list_zone = Zone.list(self.apiclient) + network_type = list_zone[0].networktype + sg_enabled = list_zone[0].securitygroupsenabled + if network_type == "Basic": + vr_list = Router.list(self.apiclient, listall='true') + self.debug("vr list {}".format(vr_list)) + if isinstance(vr_list,list) and len(vr_list) > 0: + self.debug("VR is running in the setup") + return True + else: + self.debug("VR is not present in the setup") + return False + elif network_type == "Advanced" and sg_enabled == True: + nw_list = Network.list( + self.apiclient, + supportedservices='SecurityGroup', + ) + nw_id = nw_list[0].id + vr_list = Router.list( + self.apiclient, + networkid = nw_id, + listall = 'true', + ) + if isinstance(vr_list, list) and len(vr_list) > 0: + self.debug("VR is present in the setup") + return True + else : + self.debug("VR is not present in the setup") + return False + else : + self.debug("Network type is not shared") + return None + + def test_01_deploy_vm_in_new_cidr(self): + """Deploy guest vm after adding guest IP range in new CIDR + + 1.Add IP range in new CIDR + 2.Deploy guest vm + """ + dc_id = self.dbclient.execute( + "select id from data_center where uuid = '%s';" % str(self.services["zoneid"]) + ) + dc_id = dc_id[0][0] + id_list = self.dbclient.execute( + "select id from user_ip_address where allocated is null and data_center_id = '%s';" % str(dc_id) + ) + ip_list = [] + for i in range(len(id_list)): + ip_list.append(id_list[i][0]) + #Check if VR is already present in the setup + vr_state = self.list_Routers(); + if vr_state is True : + for id in ip_list: + self.dbclient.execute( + "update user_ip_address set allocated=now() where id = '%s';" % str(id) + ) + else : + ip_list = ip_list[:-2] + for id in ip_list: + self.dbclient.execute( + "update user_ip_address set allocated=now() where id = '%s';" % str(id) + ) + #Add IP range in the new CIDR + test_gateway = self.services["cidr"]["gateway"] + test_startIp = self.services["cidr"]["startip"] + test_endIp = self.services["cidr"]["endip"] + test_netmask = self.services["cidr"]["netmask"] + #Populating services with new IP range + self.services["vlan_ip_range"]["startip"] = test_startIp + self.services["vlan_ip_range"]["endip"] = test_endIp + self.services["vlan_ip_range"]["gateway"] = test_gateway + self.services["vlan_ip_range"]["netmask"] = test_netmask + self.services["vlan_ip_range"]["zoneid"] = self.zone.id + self.services["vlan_ip_range"]["podid"] = self.pod.id + #create new vlan ip range + new_vlan = PublicIpRange.create(self.apiclient, self.services["vlan_ip_range"]) + self.debug("Created new vlan range with startip:%s and endip:%s" %(test_startIp,test_endIp)) + self.cleanup.append(new_vlan) + new_vlan_res = new_vlan.list(self.apiclient,id=new_vlan.vlan.id) + #Compare list output with configured values + self.verify_vlan_range(new_vlan_res,self.services["vlan_ip_range"]) + #Deploy vm in existing subnet if VR is not present + if vr_state is False : + vm_res = VirtualMachine.create( + self.apiclient, + self.services["server_without_disk"], + templateid = self.template.id, + accountid = self.account.name, + domainid = self.services["domainid"], + zoneid = self.services["zoneid"], + serviceofferingid = self.service_offering.id, + mode = self.services["mode"], + ) + self.cleanup.append(vm_res) + #Deploy guest vm + try : + self.virtual_machine = VirtualMachine.create( + self.apiclient, + self.services["server_without_disk"], + templateid = self.template.id, + accountid = self.account.name, + domainid = self.services["domainid"], + zoneid = self.services["zoneid"], + serviceofferingid = self.service_offering.id, + mode = self.services["mode"], + ) + except Exception as e : + raise Exception("Warning: Exception during vm deployment: {}".format(e)) + finally : + #Mark ip_Adddresses allocated state to Null which were marked as allocated at the beginning of the test + for id in ip_list : + self.dbclient.execute( + "update user_ip_address set allocated=default where id = '%s';" % str(id) + ) + self.vm_response = VirtualMachine.list( + self.apiclient, + id = self.virtual_machine.id + ) + self.assertEqual( + isinstance(self.vm_response, list), + True, + "Check VM list response returned a valid list" + ) + self.ip_range = list(netaddr.iter_iprange(unicode(self.services["cidr"]["startip"]), unicode(self.services["cidr"]["endip"]))) + self.nic_ip = netaddr.IPAddress(unicode(self.vm_response[0].nic[0].ipaddress)) + self.debug("vm got {} as ip address".format(self.nic_ip)) + self.assertIn( + self.nic_ip, + self.ip_range, + "VM did not get the ip address from the new ip range" + ) + self.virtual_machine.delete(self.apiclient) + expunge_del = Configurations.list( + self.apiclient, + name = 'expunge.delay' + ) + expunge_int = Configurations.list( + self.apiclient, + name = 'expunge.interval' + ) + wait_time = int(expunge_del[0].value) + int(expunge_int[0].value) + int(30) + + self.debug("Waiting for {} seconds for the vm to expunge".format(wait_time)) + #wait for the vm to expunge + time.sleep(wait_time) + return + From 65da24c35e58ac7dd796f48edaccc87400735f1c Mon Sep 17 00:00:00 2001 From: SrikanteswaraRao Talluri Date: Wed, 25 Sep 2013 15:16:13 +0530 Subject: [PATCH 14/27] CLOUDSTACK-4691: move egress rules host maintenance tests to maint folder Signed-off-by: venkataswamybabu budumuru (cherry picked from commit 6b28e03d6d88e9b6bd9d0521a45c93d5b4af6501) --- .../test_egress_rules_host_maintenance.py | 290 ++++++++++++++++++ .../maint/test_host_high_availability.py | 4 +- .../component/test_egress_rules.py | 12 +- tools/marvin/marvin/integration/lib/base.py | 10 +- .../demo/simulator/testcase/libs/base.py | 8 +- 5 files changed, 307 insertions(+), 17 deletions(-) create mode 100644 test/integration/component/maint/test_egress_rules_host_maintenance.py diff --git a/test/integration/component/maint/test_egress_rules_host_maintenance.py b/test/integration/component/maint/test_egress_rules_host_maintenance.py new file mode 100644 index 00000000000..6f0f768d37c --- /dev/null +++ b/test/integration/component/maint/test_egress_rules_host_maintenance.py @@ -0,0 +1,290 @@ +# 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. + +""" P1 for Egresss & Ingress rules +""" +#Import Local Modules +import marvin +from nose.plugins.attrib import attr +from marvin.cloudstackTestCase import * +from marvin.cloudstackAPI import * +from marvin.remoteSSHClient import remoteSSHClient +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * + +#Import System modules +import time +import subprocess + + +class Services: + """Test Security groups Services + """ + + def __init__(self): + self.services = { + "account": { + "email": "test@test.com", + "firstname": "Test", + "lastname": "User", + "username": "test", + # Random characters are appended in create account to + # ensure unique username generated each time + "password": "password", + }, + "virtual_machine": { + # Create a small virtual machine instance with disk offering + "displayname": "Test VM", + "username": "root", # VM creds for SSH + "password": "password", + "ssh_port": 22, + "hypervisor": 'XenServer', + "privateport": 22, + "publicport": 22, + "protocol": 'TCP', + "userdata": 'This is sample data', + }, + "service_offering": { + "name": "Tiny Instance", + "displaytext": "Tiny Instance", + "cpunumber": 1, + "cpuspeed": 100, # in MHz + "memory": 128, # In MBs + }, + "security_group": { + "name": 'SSH', + "protocol": 'TCP', + "startport": 22, + "endport": 22, + "cidrlist": '0.0.0.0/0', + }, + "ostype": 'CentOS 5.3 (64-bit)', + # CentOS 5.3 (64-bit) + "sleep": 60, + "timeout": 10, + } + + +class TestEgressAfterHostMaintenance(cloudstackTestCase): + + def setUp(self): + + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + return + + def tearDown(self): + try: + #Clean up, terminate the created templates + cleanup_resources(self.apiclient, self.cleanup) + + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + @classmethod + def setUpClass(cls): + cls.services = Services().services + cls.api_client = super( + TestEgressAfterHostMaintenance, + cls + ).getClsTestClient().getApiClient() + + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + cls.services['mode'] = cls.zone.networktype + cls.pod = get_pod( + cls.api_client, + zoneid=cls.zone.id + ) + + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostype"] + ) + cls.services["domainid"] = cls.domain.id + cls.services["virtual_machine"]["zoneid"] = cls.zone.id + cls.services["virtual_machine"]["template"] = template.id + + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + cls.services["account"] = cls.account.name + cls._cleanup = [ + cls.account, + cls.service_offering + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.api_client, cls._cleanup) + + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + + return + + @attr(speed = "slow") + @attr(tags = ["sg", "eip", "maintenance"]) + def test_egress_after_host_maintenance(self): + """Test maintenance case for egress + """ + + # Validate the following: + # 1. createaccount of type user + # 2. createsecuritygroup (ssh) for this account + # 3. authorizeSecurityGroupIngress to allow ssh access to the VM + # 4. authorizeSecurityGroupEgress to allow ssh access only out to + # CIDR: 0.0.0.0/0 + # 5. deployVirtualMachine into this security group (ssh) + # 6. deployed VM should be Running, ssh should be allowed into the VM + # 7. Enable maintenance mode for host, cance maintenance mode + # 8. User should be able to SSH into VM after maintainace + + security_group = SecurityGroup.create( + self.apiclient, + self.services["security_group"], + account=self.account.name, + domainid=self.account.domainid + ) + self.debug("Created security group with ID: %s" % security_group.id) + + # Default Security group should not have any ingress rule + sercurity_groups = SecurityGroup.list( + self.apiclient, + account=self.account.name, + domainid=self.account.domainid + ) + self.assertEqual( + isinstance(sercurity_groups, list), + True, + "Check for list security groups response" + ) + + self.assertEqual( + len(sercurity_groups), + 2, + "Check List Security groups response" + ) + # Authorize Security group to SSH to VM + self.debug( + "Authorizing ingress rule for sec group ID: %s for ssh access" + % security_group.id) + ingress_rule = security_group.authorize( + self.apiclient, + self.services["security_group"], + account=self.account.name, + domainid=self.account.domainid + ) + + self.assertEqual( + isinstance(ingress_rule, dict), + True, + "Check ingress rule created properly" + ) + + ssh_rule = (ingress_rule["ingressrule"][0]).__dict__ + + # Authorize Security group to SSH to VM + self.debug( + "Authorizing egress rule for sec group ID: %s for ssh access" + % security_group.id) + egress_rule = security_group.authorizeEgress( + self.apiclient, + self.services["security_group"], + account=self.account.name, + domainid=self.account.domainid + ) + + self.assertEqual( + isinstance(egress_rule, dict), + True, + "Check egress rule created properly" + ) + ssh_egress_rule = (egress_rule["egressrule"][0]).__dict__ + + self.virtual_machine = VirtualMachine.create( + self.apiclient, + self.services["virtual_machine"], + accountid=self.account.name, + domainid=self.account.domainid, + serviceofferingid=self.service_offering.id, + securitygroupids=[security_group.id] + ) + self.debug("Deploying VM in account: %s" % self.account.name) + + # Should be able to SSH VM + try: + self.debug("SSH into VM: %s" % self.virtual_machine.id) + ssh = self.virtual_machine.get_ssh_client() + except Exception as e: + self.fail("SSH Access failed for %s: %s" % \ + (self.virtual_machine.ipaddress, e) + ) + vms = VirtualMachine.list( + self.apiclient, + id=self.virtual_machine.id, + listall=True + ) + self.assertEqual( + isinstance(vms, list), + True, + "Check list VMs response for valid host" + ) + vm = vms[0] + + self.debug("Enabling host maintenance for ID: %s" % vm.hostid) + cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() + cmd.id = vm.hostid + self.apiclient.prepareHostForMaintenance(cmd) + + self.debug("Canceling host maintenance for ID: %s" % vm.hostid) + cmd = cancelHostMaintenance.cancelHostMaintenanceCmd() + cmd.id = vm.hostid + self.apiclient.cancelHostMaintenance(cmd) + + self.debug("Waiting for SSVMs to come up") + wait_for_ssvms( + self.apiclient, + zoneid=self.zone.id, + podid=self.pod.id, + ) + self.debug("Starting VM: %s" % self.virtual_machine.id) + + self.virtual_machine.start(self.apiclient) + # Should be able to SSH VM + try: + self.debug("SSH into VM: %s" % self.virtual_machine.id) + ssh = self.virtual_machine.get_ssh_client(reconnect=True) + except Exception as e: + self.fail("SSH Access failed for %s: %s" % \ + (self.virtual_machine.ipaddress, e) + ) + return diff --git a/test/integration/component/maint/test_host_high_availability.py b/test/integration/component/maint/test_host_high_availability.py index 5fb047ba6cb..b4c50c7114d 100644 --- a/test/integration/component/maint/test_host_high_availability.py +++ b/test/integration/component/maint/test_host_high_availability.py @@ -616,7 +616,7 @@ class TestHostHighAvailability(cloudstackTestCase): "The virtual machine is not ha enabled so check if VM is created on host which is also not ha enabled" ) - #put the Host in maintainance mode + #put the Host in maintenance mode self.debug("Enabling maintenance mode for host %s" % vm_with_ha_enabled.hostid) cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = vm_with_ha_enabled.hostid @@ -748,7 +748,7 @@ class TestHostHighAvailability(cloudstackTestCase): "The virtual machine is not ha enabled so check if VM is created on host which is also not ha enabled" ) - #put the Host in maintainance mode + #put the Host in maintenance mode self.debug("Enabling maintenance mode for host %s" % vm_with_ha_disabled.hostid) cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = vm_with_ha_disabled.hostid diff --git a/test/integration/component/test_egress_rules.py b/test/integration/component/test_egress_rules.py index 10e0d0356a5..05b45448765 100644 --- a/test/integration/component/test_egress_rules.py +++ b/test/integration/component/test_egress_rules.py @@ -2149,7 +2149,7 @@ class TestInvalidParametersForEgress(cloudstackTestCase): return -class TestEgressAfterHostMaintainance(cloudstackTestCase): +class TestEgressAfterHostMaintenance(cloudstackTestCase): def setUp(self): @@ -2171,7 +2171,7 @@ class TestEgressAfterHostMaintainance(cloudstackTestCase): def setUpClass(cls): cls.services = Services().services cls.api_client = super( - TestEgressAfterHostMaintainance, + TestEgressAfterHostMaintenance, cls ).getClsTestClient().getApiClient() @@ -2222,7 +2222,7 @@ class TestEgressAfterHostMaintainance(cloudstackTestCase): @attr(speed = "slow") @attr(tags = ["sg", "eip", "maintenance"]) - def test_egress_after_host_maintainance(self): + def test_egress_after_host_maintenance(self): """Test maintenance case for egress """ @@ -2234,7 +2234,7 @@ class TestEgressAfterHostMaintainance(cloudstackTestCase): # CIDR: 0.0.0.0/0 # 5. deployVirtualMachine into this security group (ssh) # 6. deployed VM should be Running, ssh should be allowed into the VM - # 7. Enable maintainance mode for host, cance maintainance mode + # 7. Enable maintenance mode for host, cance maintenance mode # 8. User should be able to SSH into VM after maintainace security_group = SecurityGroup.create( @@ -2329,12 +2329,12 @@ class TestEgressAfterHostMaintainance(cloudstackTestCase): ) vm = vms[0] - self.debug("Enabling host maintainance for ID: %s" % vm.hostid) + self.debug("Enabling host maintenance for ID: %s" % vm.hostid) cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = vm.hostid self.apiclient.prepareHostForMaintenance(cmd) - self.debug("Canceling host maintainance for ID: %s" % vm.hostid) + self.debug("Canceling host maintenance for ID: %s" % vm.hostid) cmd = cancelHostMaintenance.cancelHostMaintenanceCmd() cmd.id = vm.hostid self.apiclient.cancelHostMaintenance(cmd) diff --git a/tools/marvin/marvin/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py index df8140685e6..0d52224c535 100755 --- a/tools/marvin/marvin/integration/lib/base.py +++ b/tools/marvin/marvin/integration/lib/base.py @@ -1803,7 +1803,7 @@ class Host: return def enableMaintenance(self, apiclient): - """enables maintainance mode Host""" + """enables maintenance mode Host""" cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = self.id @@ -1811,14 +1811,14 @@ class Host: @classmethod def enableMaintenance(cls, apiclient, id): - """enables maintainance mode Host""" + """enables maintenance mode Host""" cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = id return apiclient.prepareHostForMaintenance(cmd) def cancelMaintenance(self, apiclient): - """Cancels maintainance mode Host""" + """Cancels maintenance mode Host""" cmd = cancelHostMaintenance.cancelHostMaintenanceCmd() cmd.id = self.id @@ -1826,7 +1826,7 @@ class Host: @classmethod def cancelMaintenance(cls, apiclient, id): - """Cancels maintainance mode Host""" + """Cancels maintenance mode Host""" cmd = cancelHostMaintenance.cancelHostMaintenanceCmd() cmd.id = id @@ -1895,7 +1895,7 @@ class StoragePool: return def enableMaintenance(self, apiclient): - """enables maintainance mode Storage pool""" + """enables maintenance mode Storage pool""" cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() cmd.id = self.id diff --git a/tools/marvin/marvin/sandbox/demo/simulator/testcase/libs/base.py b/tools/marvin/marvin/sandbox/demo/simulator/testcase/libs/base.py index 0b5da5c162f..7c8546c092c 100644 --- a/tools/marvin/marvin/sandbox/demo/simulator/testcase/libs/base.py +++ b/tools/marvin/marvin/sandbox/demo/simulator/testcase/libs/base.py @@ -1053,8 +1053,8 @@ class Host: return def enableMaintenance(self, apiclient): - """enables maintainance mode Host""" - + """enables maintenance mode Host""" + cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd() cmd.id = self.id return apiclient.prepareHostForMaintenance(cmd) @@ -1113,8 +1113,8 @@ class StoragePool: return def enableMaintenance(self, apiclient): - """enables maintainance mode Storage pool""" - + """enables maintenance mode Storage pool""" + cmd = enableStorageMaintenance.enableStorageMaintenanceCmd() cmd.id = self.id return apiclient.enableStorageMaintenance(cmd) From 55ef4b8c3c6d583c7e4de4b11613db718c590b82 Mon Sep 17 00:00:00 2001 From: SrikanteswaraRao Talluri Date: Mon, 23 Sep 2013 14:28:24 +0530 Subject: [PATCH 15/27] CLOUDSTACK-4646: Increase the wait time for the routers to go into stopped state Signed-off-by: venkataswamybabu budumuru --- test/integration/component/test_redundant_router_cleanups.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/component/test_redundant_router_cleanups.py b/test/integration/component/test_redundant_router_cleanups.py index 303ca8b8da6..e30c1020243 100644 --- a/test/integration/component/test_redundant_router_cleanups.py +++ b/test/integration/component/test_redundant_router_cleanups.py @@ -653,7 +653,7 @@ class TestRedundantRouterNetworkCleanups(cloudstackTestCase): self.debug("Sleeping for network gc wait + interval time") # Sleep to ensure that all resources are deleted - time.sleep((delay + exp) * 2) + time.sleep((delay + exp) * 3) routers = Router.list( self.apiclient, From b7e00d37006aef9d5c832fa43f7f3ddcdff7eadb Mon Sep 17 00:00:00 2001 From: Gaurav Aradhye Date: Wed, 18 Sep 2013 20:50:37 -0400 Subject: [PATCH 16/27] CLOUDSTACK: 4706 - Adding missing method get_region in common.py Signed-off-by: venkataswamybabu budumuru (cherry picked from commit 503fe75dc93be209f0382ddf9c0b548009342565) --- tools/marvin/marvin/integration/lib/common.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tools/marvin/marvin/integration/lib/common.py b/tools/marvin/marvin/integration/lib/common.py index e8958850ce5..164ef2052dd 100644 --- a/tools/marvin/marvin/integration/lib/common.py +++ b/tools/marvin/marvin/integration/lib/common.py @@ -94,6 +94,22 @@ def add_netscaler(apiclient, zoneid, NSservice): return netscaler +def get_region(apiclient, services=None): + "Returns a default region" + + cmd = listRegions.listRegionsCmd() + if services: + if "regionid" in services: + cmd.id = services["regionid"] + + regions = apiclient.listRegions(cmd) + + if isinstance(regions, list): + assert len(regions) > 0 + return regions[0] + else: + raise Exception("Failed to find specified region.") + def get_domain(apiclient, services=None): "Returns a default domain" From c61997f022b6064eab39ca911434dc626944a28a Mon Sep 17 00:00:00 2001 From: Laszlo Hornyak Date: Tue, 24 Sep 2013 23:01:30 +0200 Subject: [PATCH 17/27] basic test for ApiDispatcher Signed-off-by: Laszlo Hornyak --- .../cloudstack/context/CallContext.java | 2 +- .../test/com/cloud/api/ApiDispatcherTest.java | 90 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 server/test/com/cloud/api/ApiDispatcherTest.java diff --git a/api/src/org/apache/cloudstack/context/CallContext.java b/api/src/org/apache/cloudstack/context/CallContext.java index a62a3da72c4..114f626cf95 100644 --- a/api/src/org/apache/cloudstack/context/CallContext.java +++ b/api/src/org/apache/cloudstack/context/CallContext.java @@ -37,7 +37,7 @@ import com.cloud.utils.exception.CloudRuntimeException; */ public class CallContext { private static final Logger s_logger = Logger.getLogger(CallContext.class); - private static ThreadLocal s_currentContext = new ThreadLocal(); + private static final ThreadLocal s_currentContext = new ThreadLocal(); private String contextId; private Account account; diff --git a/server/test/com/cloud/api/ApiDispatcherTest.java b/server/test/com/cloud/api/ApiDispatcherTest.java new file mode 100644 index 00000000000..9d54aaaef38 --- /dev/null +++ b/server/test/com/cloud/api/ApiDispatcherTest.java @@ -0,0 +1,90 @@ +package com.cloud.api; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.context.CallContext; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; + +@RunWith(MockitoJUnitRunner.class) +public class ApiDispatcherTest { + + @Mock + AccountManager accountManager; + + public static class TestCmd extends BaseCmd { + + @Parameter(name = "strparam1") + String strparam1; + + @Parameter(name="intparam1", type=CommandType.INTEGER) + int intparam1; + + @Parameter(name="boolparam1", type=CommandType.BOOLEAN) + boolean boolparam1; + + @Override + public void execute() throws ResourceUnavailableException, + InsufficientCapacityException, ServerApiException, + ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + // well documented nothing + } + + @Override + public String getCommandName() { + return "test"; + } + + @Override + public long getEntityOwnerId() { + return 0; + } + + } + + @Before + public void setup() { + CallContext.register(Mockito.mock(User.class), Mockito.mock(Account.class)); + new ApiDispatcher().init(); + ApiDispatcher.getInstance()._accountMgr = accountManager; + } + + @After + public void cleanup() { + CallContext.unregister(); + } + + @Test + public void processParameters() { + HashMap params = new HashMap(); + params.put("strparam1", "foo"); + params.put("intparam1", "100"); + params.put("boolparam1", "true"); + TestCmd cmd = new TestCmd(); + //how lucky that field is not protected, this test would be impossible + ApiDispatcher.processParameters(cmd, params); + Assert.assertEquals("foo", cmd.strparam1); + Assert.assertEquals(100, cmd.intparam1); + } + +} From 13e7a7308b75bfccd1f3fb9686244ad2129ef7f0 Mon Sep 17 00:00:00 2001 From: Laszlo Hornyak Date: Sun, 29 Sep 2013 15:25:53 +0200 Subject: [PATCH 18/27] Test for URLEncoder - test added - source formatted Signed-off-by: Laszlo Hornyak --- .../com/cloud/utils/encoding/URLEncoder.java | 44 +++++++++---------- .../cloud/utils/encoding/UrlEncoderTest.java | 14 ++++++ 2 files changed, 34 insertions(+), 24 deletions(-) create mode 100644 utils/test/com/cloud/utils/encoding/UrlEncoderTest.java diff --git a/utils/src/com/cloud/utils/encoding/URLEncoder.java b/utils/src/com/cloud/utils/encoding/URLEncoder.java index 30deb024a90..8c9e35ce01f 100644 --- a/utils/src/com/cloud/utils/encoding/URLEncoder.java +++ b/utils/src/com/cloud/utils/encoding/URLEncoder.java @@ -34,19 +34,16 @@ import java.util.BitSet; * @author Remy Maucherat */ - - - public class URLEncoder { protected static final char[] hexadecimal = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static CharsetEncoder asciiEncoder = Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1 - + //Array containing the safe characters set. protected BitSet safeCharacters = new BitSet(256); - + public URLEncoder() { for (char i = 'a'; i <= 'z'; i++) { addSafeCharacter(i); @@ -59,15 +56,14 @@ public class URLEncoder { } } - public void addSafeCharacter(char c) { + private void addSafeCharacter(char c) { safeCharacters.set(c); } - + public String encode(String path) { int maxBytesPerChar = 10; StringBuffer rewrittenPath = new StringBuffer(path.length()); - ByteArrayOutputStream buf = new ByteArrayOutputStream( - maxBytesPerChar); + ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(buf, "UTF8"); @@ -75,10 +71,11 @@ public class URLEncoder { e.printStackTrace(); writer = new OutputStreamWriter(buf); } - + for (int i = 0; i < path.length(); i++) { int c = (int) path.charAt(i); - //NOTICE - !isPureAscii(path.charAt(i)) check was added by CloudStack + // NOTICE - !isPureAscii(path.charAt(i)) check was added by + // CloudStack if (safeCharacters.get(c) || !isPureAscii(path.charAt(i))) { rewrittenPath.append((char) c); } else { @@ -95,20 +92,19 @@ public class URLEncoder { // Converting each byte in the buffer byte toEncode = ba[j]; rewrittenPath.append('%'); - int low = (int) (toEncode & 0x0f); - int high = (int) ((toEncode & 0xf0) >> 4); - rewrittenPath.append(hexadecimal[high]); - rewrittenPath.append(hexadecimal[low]); - } - buf.reset(); + int low = (int) (toEncode & 0x0f); + int high = (int) ((toEncode & 0xf0) >> 4); + rewrittenPath.append(hexadecimal[high]); + rewrittenPath.append(hexadecimal[low]); } + buf.reset(); } - return rewrittenPath.toString(); - } - - - //NOTICE - this part was added by CloudStack - public static boolean isPureAscii(Character v) { - return asciiEncoder.canEncode(v); } + return rewrittenPath.toString(); + } + + // NOTICE - this part was added by CloudStack + public static boolean isPureAscii(Character v) { + return asciiEncoder.canEncode(v); + } } diff --git a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java new file mode 100644 index 00000000000..322ac78dc9f --- /dev/null +++ b/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java @@ -0,0 +1,14 @@ +package com.cloud.utils.encoding; + +import org.junit.Assert; +import org.junit.Test; + +public class UrlEncoderTest { + @Test + public void encode() { + Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/")); + Assert.assertEquals("%20", new URLEncoder().encode(" ")); + Assert.assertEquals("%5F", new URLEncoder().encode("_")); + Assert.assertEquals("%25", new URLEncoder().encode("%")); + } +} From 2e29c89b841f6c00e30ea8fdc02510c2dbb41d39 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 08:54:02 -0700 Subject: [PATCH 19/27] Default null value in ConfigKey results in NPE on second start --- .../cloudstack/framework/config/impl/ConfigDepotImpl.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java index b516596febc..97430ef91f9 100644 --- a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java +++ b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java @@ -25,13 +25,13 @@ import javax.annotation.PostConstruct; import javax.inject.Inject; import org.apache.log4j.Logger; - import org.apache.cloudstack.framework.config.ConfigDepot; import org.apache.cloudstack.framework.config.ConfigDepotAdmin; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.framework.config.ScopedConfigStorage; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.commons.lang.ObjectUtils; import com.cloud.utils.Pair; import com.cloud.utils.component.SystemIntegrityChecker; @@ -97,10 +97,8 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin, SystemInt _configDao.persist(vo); } else { if (vo.isDynamic() != key.isDynamic() || - !vo.getDescription().equals(key.description()) || - ((vo.getDefaultValue() != null && key.defaultValue() == null) || - (vo.getDefaultValue() == null && key.defaultValue() != null) || - !vo.getDefaultValue().equals(key.defaultValue()))) { + !ObjectUtils.equals(vo.getDescription(), vo.getDescription()) || + !ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue())) { vo.setDynamic(key.isDynamic()); vo.setDescription(key.description()); vo.setDefaultValue(key.defaultValue()); From 9a083b9e66c15bd5b6d4a79e6952e3b6d778950b Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:23:23 -0700 Subject: [PATCH 20/27] Add Named interface to recognize objects with a getName() --- .../utils/component/ComponentLifecycle.java | 4 +-- .../src/com/cloud/utils/component/Named.java | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 utils/src/com/cloud/utils/component/Named.java diff --git a/utils/src/com/cloud/utils/component/ComponentLifecycle.java b/utils/src/com/cloud/utils/component/ComponentLifecycle.java index ea671af0d83..aac4eb05bb9 100644 --- a/utils/src/com/cloud/utils/component/ComponentLifecycle.java +++ b/utils/src/com/cloud/utils/component/ComponentLifecycle.java @@ -20,7 +20,7 @@ import java.util.Map; import javax.naming.ConfigurationException; -public interface ComponentLifecycle { +public interface ComponentLifecycle extends Named { public static final int RUN_LEVEL_SYSTEM_BOOTSTRAP = 0; // for system level bootstrap components public static final int RUN_LEVEL_SYSTEM = 1; // for system level service components (i.e., DAOs) public static final int RUN_LEVEL_FRAMEWORK_BOOTSTRAP = 2; // for framework startup checkers (i.e., DB migration check) @@ -30,7 +30,7 @@ public interface ComponentLifecycle { public static final int RUN_LEVEL_APPLICATION_MAINLOOP = 6; public static final int MAX_RUN_LEVELS = 7; - + @Override String getName(); void setName(String name); diff --git a/utils/src/com/cloud/utils/component/Named.java b/utils/src/com/cloud/utils/component/Named.java new file mode 100644 index 00000000000..6960b4c7566 --- /dev/null +++ b/utils/src/com/cloud/utils/component/Named.java @@ -0,0 +1,25 @@ +/* + * 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.utils.component; + +public interface Named { + + String getName(); + +} From 78040f8769721ab68fa835dde199fbbc45167c2d Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:26:17 -0700 Subject: [PATCH 21/27] Add registry interface Registry interface will be used to store and discover extensions --- .../com/cloud/utils/component/Registry.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 utils/src/com/cloud/utils/component/Registry.java diff --git a/utils/src/com/cloud/utils/component/Registry.java b/utils/src/com/cloud/utils/component/Registry.java new file mode 100644 index 00000000000..c2a74aeb517 --- /dev/null +++ b/utils/src/com/cloud/utils/component/Registry.java @@ -0,0 +1,50 @@ +/* + * 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.utils.component; + +import java.util.List; + +/** + * Simple interface to represents a registry of items + * + * @param + */ +public interface Registry extends Named { + + /** + * Registers an item. If the item has already been registered the implementation + * should detect that it is registered and not re-register it. + * + * @param type + * @return true if register, false if not registered or already exists + */ + boolean register(T type); + + void unregister(T type); + + /** + * Returns a list that will dynamically change as items are registered/unregister. + * The list is thread safe to iterate upon. Traversing the list using an index + * would not be safe as the size may changed during traversal. + * + * @return Unmodifiable list of registered items + */ + List getRegistered(); + +} From 766a0a2229e270e964adc9801eccd010475d0b9a Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:30:54 -0700 Subject: [PATCH 22/27] Add ability to programatically disable CloudStack ComponentConext intialization As we moved to a more Spring managed lifecycle, the lifecycle management in ComponentContext is not needed. The transition to fully spring managed will not happen all at once. The management server will be done first and then AWSAPI and UsageServer will come later. This change allows the ComponentContext in the context of the management server to be bypassed. Note, by default, the ComponentContext will run its initialization. --- .../com/cloud/utils/component/ComponentContext.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/utils/src/com/cloud/utils/component/ComponentContext.java b/utils/src/com/cloud/utils/component/ComponentContext.java index 065fd3b22d0..332e4eca1a0 100644 --- a/utils/src/com/cloud/utils/component/ComponentContext.java +++ b/utils/src/com/cloud/utils/component/ComponentContext.java @@ -49,6 +49,7 @@ public class ComponentContext implements ApplicationContextAware { private static final Logger s_logger = Logger.getLogger(ComponentContext.class); private static ApplicationContext s_appContext; + private static boolean s_initializeBeans = true; @Override public void setApplicationContext(ApplicationContext applicationContext) { @@ -61,6 +62,9 @@ public class ComponentContext implements ApplicationContextAware { } public static void initComponentsLifeCycle() { + if ( ! s_initializeBeans ) + return; + AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory(); Map interceptableComponents = getApplicationContext().getBeansOfType(ComponentMethodInterceptable.class); @@ -234,4 +238,12 @@ public class ComponentContext implements ApplicationContextAware { beanFactory.autowireBean(instance); return (T)instance; } + + public boolean isInitializeBeans() { + return s_initializeBeans; + } + + public void setInitializeBeans(boolean initializeBeans) { + s_initializeBeans = initializeBeans; + } } From 692535f92847fb6e4b2d349b55137cb7025567dd Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:33:33 -0700 Subject: [PATCH 23/27] Cleanup DefaultUserAuthenticator and removed masking _name variable DefaultUserAuthenticator maskes the _name varible in ComponentLifecycleBase making the setName() method not work as expected. This patch cleans up the code such that getName() will be getClass().getSimpleName() unless overridden in the Spring configuration. --- .../cloudstack/ldap/LdapAuthenticator.java | 10 ------- .../server/auth/MD5UserAuthenticator.java | 14 +--------- .../auth/PlainTextUserAuthenticator.java | 15 ----------- .../auth/SHA256SaltedUserAuthenticator.java | 11 -------- .../server/auth/DefaultUserAuthenticator.java | 27 ------------------- 5 files changed, 1 insertion(+), 76 deletions(-) diff --git a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java index e62a3d8f1dc..559a9794b2d 100644 --- a/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/org/apache/cloudstack/ldap/LdapAuthenticator.java @@ -19,7 +19,6 @@ package org.apache.cloudstack.ldap; import java.util.Map; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; @@ -47,15 +46,6 @@ public class LdapAuthenticator extends DefaultUserAuthenticator { _userAccountDao = userAccountDao; } - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - if (name == null) { - name = "LDAP"; - } - super.configure(name, params); - return true; - } - @Override public boolean authenticate(final String username, final String password, final Long domainId, final Map requestParameters) { diff --git a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java index e5b169fc456..63583af4ad6 100644 --- a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java +++ b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java @@ -22,12 +22,11 @@ import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; + import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; - import com.cloud.utils.exception.CloudRuntimeException; /** @@ -59,17 +58,6 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { return true; } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - if(name == null) { - name = "MD5"; - } - super.configure(name, params); - return true; - } - - @Override public String encode(String password) { MessageDigest md5 = null; try { diff --git a/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java index f102275905f..849e82e093d 100644 --- a/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java +++ b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java @@ -15,20 +15,15 @@ package com.cloud.server.auth; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; -import com.cloud.utils.exception.CloudRuntimeException; @Local(value={UserAuthenticator.class}) @@ -56,16 +51,6 @@ public class PlainTextUserAuthenticator extends DefaultUserAuthenticator { return true; } - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - if (name == null) { - name = "PLAINTEXT"; - } - super.configure(name, params); - return true; - } - @Override public String encode(String password) { // Plaintext so no encoding at all diff --git a/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java index 91be922c9a9..3592ddc8169 100644 --- a/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java +++ b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java @@ -24,7 +24,6 @@ import java.util.Map; import javax.ejb.Local; import javax.inject.Inject; -import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.bouncycastle.util.encoders.Base64; @@ -42,16 +41,6 @@ public class SHA256SaltedUserAuthenticator extends DefaultUserAuthenticator { private UserAccountDao _userAccountDao; private static final int s_saltlen = 32; - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - if (name == null) { - name = "SHA256SALT"; - } - super.configure(name, params); - return true; - } - /* (non-Javadoc) * @see com.cloud.server.auth.UserAuthenticator#authenticate(java.lang.String, java.lang.String, java.lang.Long, java.util.Map) */ diff --git a/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java b/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java index 952f724bac9..253b0ac3ec4 100644 --- a/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java +++ b/server/src/com/cloud/server/auth/DefaultUserAuthenticator.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.auth; -import java.util.Map; - import javax.ejb.Local; -import javax.naming.ConfigurationException; import com.cloud.utils.component.AdapterBase; @@ -29,28 +26,4 @@ import com.cloud.utils.component.AdapterBase; */ @Local(value={UserAuthenticator.class}) public abstract class DefaultUserAuthenticator extends AdapterBase implements UserAuthenticator { - private String _name = null; - - @Override - public boolean configure(String name, Map params) - throws ConfigurationException { - _name = name; - return true; - } - - @Override - public String getName() { - return _name; - } - - @Override - public boolean start() { - return true; - } - - @Override - public boolean stop() { - return true; - } - } From efbfae723ec5583378cb90c54fc63b6975c7fc24 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:45:07 -0700 Subject: [PATCH 24/27] Switch to setter injection for extensibility Various classes are using member injection to inject extensible objects. Really those object should come from an AdapterList that is injected in. This patch switches the code to use setter injection that will later allow spring to inject an AdapterList or something similar to allow extensibility. --- .../cloud/vm/VirtualMachineManagerImpl.java | 10 ++++++- .../cloud/entity/api/VMEntityManagerImpl.java | 10 ++++++- .../acl/StaticRoleBasedAPIAccessChecker.java | 11 ++++++- server/src/com/cloud/api/ApiServer.java | 22 ++++++++++++-- .../ConfigurationManagerImpl.java | 10 ++++++- .../consoleproxy/ConsoleProxyManagerImpl.java | 10 ++++++- .../hypervisor/HypervisorGuruManagerImpl.java | 30 +++++++++++++++++-- .../com/cloud/network/NetworkServiceImpl.java | 11 ++++++- .../cloud/server/ManagementServerImpl.java | 10 ++++++- .../cloud/storage/VolumeApiServiceImpl.java | 10 ++++++- .../SecondaryStorageManagerImpl.java | 10 ++++++- .../cloud/template/TemplateManagerImpl.java | 10 ++++++- 12 files changed, 139 insertions(+), 15 deletions(-) diff --git a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java index af6ca6d643d..560bab26fff 100755 --- a/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -257,7 +257,6 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac this._hostAllocators = _hostAllocators; } - @Inject protected List _storagePoolAllocators; @Inject @@ -3271,4 +3270,13 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VmOpWaitInterval}; } + public List getStoragePoolAllocators() { + return _storagePoolAllocators; + } + + @Inject + public void setStoragePoolAllocators(List storagePoolAllocators) { + this._storagePoolAllocators = storagePoolAllocators; + } + } diff --git a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java index 204b832ab4a..e784295b1d3 100755 --- a/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java +++ b/engine/orchestration/src/org/apache/cloudstack/engine/cloud/entity/api/VMEntityManagerImpl.java @@ -99,7 +99,6 @@ public class VMEntityManagerImpl implements VMEntityManager { @Inject protected VirtualMachineManager _itMgr; - @Inject protected List _planners; @Inject @@ -257,4 +256,13 @@ public class VMEntityManagerImpl implements VMEntityManager { return true; } + public List getPlanners() { + return _planners; + } + + @Inject + public void setPlanners(List planners) { + this._planners = planners; + } + } diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java index d4d73d1f77b..affcf919daf 100644 --- a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -46,7 +46,7 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC private static Map> s_roleBasedApisMap = new HashMap>(); - @Inject List _services; + List _services; @Inject AccountService _accountService; protected StaticRoleBasedAPIAccessChecker() { @@ -95,4 +95,13 @@ public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIC } } } + + public List getServices() { + return _services; + } + + @Inject + public void setServices(List _services) { + this._services = _services; + } } diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 550626f111c..26789e3a81a 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -169,8 +169,8 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer @Inject private EntityManager _entityMgr; - @Inject List _pluggableServices; - @Inject List _apiAccessCheckers; + List _pluggableServices; + List _apiAccessCheckers; @Inject protected ApiAsyncJobDispatcher _asyncDispatcher; @@ -1096,4 +1096,22 @@ public class ApiServer extends ManagerBase implements HttpRequestHandler, ApiSer } return responseText; } + + public List getPluggableServices() { + return _pluggableServices; + } + + @Inject + public void setPluggableServices(List _pluggableServices) { + this._pluggableServices = _pluggableServices; + } + + public List getApiAccessCheckers() { + return _apiAccessCheckers; + } + + @Inject + public void setApiAccessCheckers(List _apiAccessCheckers) { + this._apiAccessCheckers = _apiAccessCheckers; + } } diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 8a0f7a65a12..2b86bf51238 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -250,7 +250,6 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati @Inject AlertManager _alertMgr; // @com.cloud.utils.component.Inject(adapter = SecurityChecker.class) - @Inject List _secChecker; @Inject @@ -4934,5 +4933,14 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati return false; } + public List getSecChecker() { + return _secChecker; + } + + @Inject + public void setSecChecker(List secChecker) { + this._secChecker = secChecker; + } + } diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index d51eb41c24f..030a31fb5e6 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -166,7 +166,6 @@ VirtualMachineGuru, SystemVmLoadScanHandler, ResourceStateAdapter { private int _mgmt_port = 8250; - @Inject private List _consoleProxyAllocators; @Inject @@ -1702,4 +1701,13 @@ VirtualMachineGuru, SystemVmLoadScanHandler, ResourceStateAdapter { public void prepareStop(VirtualMachineProfile profile) { } + public List getConsoleProxyAllocators() { + return _consoleProxyAllocators; + } + + @Inject + public void setConsoleProxyAllocators(List consoleProxyAllocators) { + this._consoleProxyAllocators = consoleProxyAllocators; + } + } diff --git a/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java b/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java index 4d1e1b50b40..d0effaba607 100644 --- a/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java +++ b/server/src/com/cloud/hypervisor/HypervisorGuruManagerImpl.java @@ -19,6 +19,7 @@ package com.cloud.hypervisor; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import javax.ejb.Local; @@ -26,6 +27,7 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import com.cloud.utils.Pair; + import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -43,8 +45,8 @@ public class HypervisorGuruManagerImpl extends ManagerBase implements Hypervisor @Inject HostDao _hostDao; - @Inject List _hvGuruList; - Map _hvGurus = new HashMap(); + List _hvGuruList; + Map _hvGurus = new ConcurrentHashMap(); @PostConstruct public void init() { @@ -55,7 +57,19 @@ public class HypervisorGuruManagerImpl extends ManagerBase implements Hypervisor @Override public HypervisorGuru getGuru(HypervisorType hypervisorType) { - return _hvGurus.get(hypervisorType); + HypervisorGuru result = _hvGurus.get(hypervisorType); + + if ( result == null ) { + for ( HypervisorGuru guru : _hvGuruList ) { + if ( guru.getHypervisorType() == hypervisorType ) { + _hvGurus.put(hypervisorType, guru); + result = guru; + break; + } + } + } + + return result; } @Override @@ -68,4 +82,14 @@ public class HypervisorGuruManagerImpl extends ManagerBase implements Hypervisor } return hostId; } + + public List getHvGuruList() { + return _hvGuruList; + } + + @Inject + public void setHvGuruList(List hvGuruList) { + this._hvGuruList = hvGuruList; + } + } diff --git a/server/src/com/cloud/network/NetworkServiceImpl.java b/server/src/com/cloud/network/NetworkServiceImpl.java index 598b31c7bfe..61c070a86c4 100755 --- a/server/src/com/cloud/network/NetworkServiceImpl.java +++ b/server/src/com/cloud/network/NetworkServiceImpl.java @@ -230,7 +230,7 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { @Inject UsageEventDao _usageEventDao; - @Inject List _networkGurus; + List _networkGurus; @Inject NetworkDomainDao _networkDomainDao; @@ -3944,4 +3944,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService { return _networkMgr.listVmNics(vmId, nicId); } + public List getNetworkGurus() { + return _networkGurus; + } + + @Inject + public void setNetworkGurus(List networkGurus) { + this._networkGurus = networkGurus; + } + } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index c0a52f78cef..1c316103424 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -675,7 +675,6 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe @Inject private HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; private List _hostAllocators; - @Inject private List _storagePoolAllocators; @Inject private ResourceTagDao _resourceTagDao; @@ -3870,4 +3869,13 @@ public class ManagementServerImpl extends ManagerBase implements ManagementServe _dpMgr.cleanupVMReservations(); } + + public List getStoragePoolAllocators() { + return _storagePoolAllocators; + } + + @Inject + public void setStoragePoolAllocators(List storagePoolAllocators) { + this._storagePoolAllocators = storagePoolAllocators; + } } diff --git a/server/src/com/cloud/storage/VolumeApiServiceImpl.java b/server/src/com/cloud/storage/VolumeApiServiceImpl.java index b573786e0bf..faff10f11fd 100644 --- a/server/src/com/cloud/storage/VolumeApiServiceImpl.java +++ b/server/src/com/cloud/storage/VolumeApiServiceImpl.java @@ -273,7 +273,6 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic protected VmDiskStatisticsDao _vmDiskStatsDao; @Inject protected VMSnapshotDao _vmSnapshotDao; - @Inject protected List _storagePoolAllocators; @Inject ConfigurationDao _configDao; @@ -1693,4 +1692,13 @@ public class VolumeApiServiceImpl extends ManagerBase implements VolumeApiServic return true; } + public List getStoragePoolAllocators() { + return _storagePoolAllocators; + } + + @Inject + public void setStoragePoolAllocators(List storagePoolAllocators) { + this._storagePoolAllocators = storagePoolAllocators; + } + } diff --git a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java index 3a070349ace..007557dcbc5 100755 --- a/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java +++ b/server/src/com/cloud/storage/secondary/SecondaryStorageManagerImpl.java @@ -169,7 +169,6 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar private int _mgmt_port = 8250; - @Inject private List _ssVmAllocators; @Inject @@ -1374,4 +1373,13 @@ public class SecondaryStorageManagerImpl extends ManagerBase implements Secondar public void prepareStop(VirtualMachineProfile profile) { } + + public List getSecondaryStorageVmAllocators() { + return _ssVmAllocators; + } + + @Inject + public void setSecondaryStorageVmAllocators(List ssVmAllocators) { + this._ssVmAllocators = ssVmAllocators; + } } diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 9fa2e8bf2f2..5240102a879 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -291,7 +291,6 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, boolean _disableExtraction = false; ExecutorService _preloadExecutor; - @Inject protected List _adapters; @Inject @@ -1823,4 +1822,13 @@ public class TemplateManagerImpl extends ManagerBase implements TemplateManager, public ConfigKey[] getConfigKeys() { return new ConfigKey[] {AllowPublicUserTemplates}; } + + public List getTemplateAdapters() { + return _adapters; + } + + @Inject + public void setTemplateAdapters(List adapters) { + this._adapters = adapters; + } } From cba8e40e4bb060f2768d3b3a364d33f27c50891e Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 09:51:45 -0700 Subject: [PATCH 25/27] Add license headers to fix build --- .../test/com/cloud/api/ApiDispatcherTest.java | 18 ++++++++++++++++++ .../cloud/utils/encoding/UrlEncoderTest.java | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/server/test/com/cloud/api/ApiDispatcherTest.java b/server/test/com/cloud/api/ApiDispatcherTest.java index 9d54aaaef38..4fca289a774 100644 --- a/server/test/com/cloud/api/ApiDispatcherTest.java +++ b/server/test/com/cloud/api/ApiDispatcherTest.java @@ -1,3 +1,21 @@ +/* + * 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.api; import java.util.HashMap; diff --git a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java index 322ac78dc9f..73d9a21d570 100644 --- a/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java +++ b/utils/test/com/cloud/utils/encoding/UrlEncoderTest.java @@ -1,3 +1,21 @@ +/* + * 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.utils.encoding; import org.junit.Assert; From 19ef999e36c07e113c19154731661ba47a0af169 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Mon, 30 Sep 2013 10:07:28 -0700 Subject: [PATCH 26/27] Wrong field was used in check --- .../cloudstack/framework/config/impl/ConfigDepotImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java index 97430ef91f9..11281bf0293 100644 --- a/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java +++ b/framework/config/src/org/apache/cloudstack/framework/config/impl/ConfigDepotImpl.java @@ -97,7 +97,7 @@ public class ConfigDepotImpl implements ConfigDepot, ConfigDepotAdmin, SystemInt _configDao.persist(vo); } else { if (vo.isDynamic() != key.isDynamic() || - !ObjectUtils.equals(vo.getDescription(), vo.getDescription()) || + !ObjectUtils.equals(vo.getDescription(), key.description()) || !ObjectUtils.equals(vo.getDefaultValue(), key.defaultValue())) { vo.setDynamic(key.isDynamic()); vo.setDescription(key.description()); From 1a23d6ebab7864eb2840676e7eab6c2aa30b3a54 Mon Sep 17 00:00:00 2001 From: Brian Federle Date: Mon, 30 Sep 2013 10:06:29 -0700 Subject: [PATCH 27/27] Remove file added by accident in previous commit. --- ui/plugins/netapp | 1 - 1 file changed, 1 deletion(-) delete mode 120000 ui/plugins/netapp diff --git a/ui/plugins/netapp b/ui/plugins/netapp deleted file mode 120000 index 21f67e4ad49..00000000000 --- a/ui/plugins/netapp +++ /dev/null @@ -1 +0,0 @@ -/Users/csuich/CloudStack/workspace/ui-plugin/ \ No newline at end of file