CLOUDSTACK-1339: Using Sping interface injection pattern to avoid using CGLIB proxying mode. Spring with CGLIB proxying will concflict with CGLIB usage in CloudStack DB code, CloudStack CGLIB usage can cause Spring to lose tack of its proxied object and therefore creates a massive amount of objects in memory

This commit is contained in:
Kelven Yang 2013-02-24 13:28:39 -08:00
parent 72e6fd6e8d
commit 333dd810d2
56 changed files with 1439 additions and 177 deletions

View File

@ -37,7 +37,7 @@
<!--
@DB support
-->
<aop:config proxy-target-class="true">
<aop:config>
<aop:aspect id="dbContextBuilder" ref="transactionContextBuilder">
<aop:pointcut id="captureAnyMethod"
expression="execution(* *(..))"
@ -50,15 +50,14 @@
<aop:pointcut id="captureEventMethod"
expression="execution(* *(..)) and @annotation(com.cloud.event.ActionEvent)"
/>
<aop:around pointcut-ref="captureEventMethod" method="AroundAnyMethod"/>
</aop:aspect>
</aop:config>
<bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
<bean id="actionEventInterceptor" class="com.cloud.event.ActionEventInterceptor" />
<!--
RPC/Async/EventBus
-->

View File

@ -49,13 +49,13 @@ public class VMEntityDaoImpl extends GenericDaoBase<VMEntityVO, Long> implements
public static final Logger s_logger = Logger.getLogger(VMEntityDaoImpl.class);
@Inject protected VMReservationDaoImpl _vmReservationDao;
@Inject protected VMReservationDao _vmReservationDao;
@Inject protected VMComputeTagDaoImpl _vmComputeTagDao;
@Inject protected VMComputeTagDao _vmComputeTagDao;
@Inject protected VMRootDiskTagDaoImpl _vmRootDiskTagsDao;
@Inject protected VMRootDiskTagDao _vmRootDiskTagsDao;
@Inject protected VMNetworkMapDaoImpl _vmNetworkMapDao;
@Inject protected VMNetworkMapDao _vmNetworkMapDao;
@Inject

View File

@ -43,7 +43,7 @@ public class VMReservationDaoImpl extends GenericDaoBase<VMReservationVO, Long>
protected SearchBuilder<VMReservationVO> VmIdSearch;
@Inject protected VolumeReservationDaoImpl _volumeReservationDao;
@Inject protected VolumeReservationDao _volumeReservationDao;
public VMReservationDaoImpl() {
}

View File

@ -84,9 +84,6 @@ public class CloudOrchestrator implements OrchestrationService {
@Inject
protected DiskOfferingDao _diskOfferingDao = null;
@Inject
protected VirtualMachineEntityFactory _vmEntityFactory;
@Inject
protected NetworkDao _networkDao;
@ -230,7 +227,9 @@ public class CloudOrchestrator implements OrchestrationService {
// VirtualMachineEntityImpl vmEntity = new VirtualMachineEntityImpl(id, owner, hostName, displayName, cpu, speed, memory, computeTags, rootDiskTags, networks, vmEntityManager);
VirtualMachineEntityImpl vmEntity = null;
try {
vmEntity = _vmEntityFactory.getObject();
vmEntity = VirtualMachineEntityImpl.class.newInstance();
vmEntity = ComponentContext.inject(vmEntity);
} catch (Exception e) {
// add error handling here
}

View File

@ -240,4 +240,10 @@ public class DirectAgentManagerSimpleImpl extends ManagerBase implements AgentMa
return null;
}
@Override
public void disconnectWithInvestigation(long hostId, Event event) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,975 @@
/*
* 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 org.apache.cloudstack.storage.image.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.storage.image.TemplateEvent;
import org.apache.cloudstack.storage.image.TemplateState;
import org.apache.cloudstack.storage.image.format.ISO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.TemplateType;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateZoneVO;
import com.cloud.storage.dao.VMTemplateDaoImpl;
import com.cloud.storage.dao.VMTemplateDetailsDao;
import com.cloud.storage.dao.VMTemplateZoneDao;
import com.cloud.tags.ResourceTagVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.template.VirtualMachineTemplate.TemplateFilter;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
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.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
public class ImageDataDaoImpl extends GenericDaoBase<ImageDataVO, Long> implements ImageDataDao {
private static final Logger s_logger = Logger.getLogger(VMTemplateDaoImpl.class);
@Inject
VMTemplateZoneDao templateZoneDao;
@Inject
VMTemplateDetailsDao templateDetailsDao;
@Inject
ConfigurationDao configDao;
@Inject
HostDao hostDao;
@Inject
DomainDao domainDao;
@Inject
DataCenterDao dcDao;
private final String SELECT_TEMPLATE_HOST_REF = "SELECT t.id, h.data_center_id, t.unique_name, t.name, t.public, t.featured, t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, "
+ "t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type FROM vm_template t";
private final String SELECT_TEMPLATE_ZONE_REF = "SELECT t.id, tzr.zone_id, t.unique_name, t.name, t.public, t.featured, t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, "
+ "t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type FROM vm_template t INNER JOIN template_zone_ref tzr on (t.id = tzr.template_id) ";
private final String SELECT_TEMPLATE_SWIFT_REF = "SELECT t.id, t.unique_name, t.name, t.public, t.featured, t.type, t.hvm, t.bits, t.url, t.format, t.created, t.account_id, "
+ "t.checksum, t.display_text, t.enable_password, t.guest_os_id, t.bootable, t.prepopulate, t.cross_zones, t.hypervisor_type FROM vm_template t";
protected SearchBuilder<ImageDataVO> TemplateNameSearch;
protected SearchBuilder<ImageDataVO> UniqueNameSearch;
protected SearchBuilder<ImageDataVO> tmpltTypeSearch;
protected SearchBuilder<ImageDataVO> tmpltTypeHyperSearch;
protected SearchBuilder<ImageDataVO> tmpltTypeHyperSearch2;
protected SearchBuilder<ImageDataVO> AccountIdSearch;
protected SearchBuilder<ImageDataVO> NameSearch;
protected SearchBuilder<ImageDataVO> TmpltsInZoneSearch;
private SearchBuilder<ImageDataVO> PublicSearch;
private SearchBuilder<ImageDataVO> NameAccountIdSearch;
private SearchBuilder<ImageDataVO> PublicIsoSearch;
private SearchBuilder<ImageDataVO> UserIsoSearch;
private GenericSearchBuilder<ImageDataVO, Long> CountTemplatesByAccount;
private SearchBuilder<ImageDataVO> updateStateSearch;
@Inject
ResourceTagDao _tagsDao = null;
private String routerTmpltName;
private String consoleProxyTmpltName;
protected ImageDataDaoImpl() {
}
@Override
public List<ImageDataVO> listByPublic() {
SearchCriteria<ImageDataVO> sc = PublicSearch.create();
sc.setParameters("public", 1);
return listBy(sc);
}
@Override
public ImageDataVO findByName(String templateName) {
SearchCriteria<ImageDataVO> sc = UniqueNameSearch.create();
sc.setParameters("uniqueName", templateName);
return findOneIncludingRemovedBy(sc);
}
@Override
public ImageDataVO findByTemplateName(String templateName) {
SearchCriteria<ImageDataVO> sc = NameSearch.create();
sc.setParameters("name", templateName);
return findOneIncludingRemovedBy(sc);
}
@Override
public List<ImageDataVO> publicIsoSearch(Boolean bootable, boolean listRemoved, Map<String, String> tags) {
SearchBuilder<ImageDataVO> sb = null;
if (tags == null || tags.isEmpty()) {
sb = PublicIsoSearch;
} else {
sb = createSearchBuilder();
sb.and("public", sb.entity().isPublicTemplate(), SearchCriteria.Op.EQ);
sb.and("format", sb.entity().getFormat(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getTemplateType(), SearchCriteria.Op.EQ);
sb.and("bootable", sb.entity().isBootable(), SearchCriteria.Op.EQ);
sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.EQ);
SearchBuilder<ResourceTagVO> tagSearch = _tagsDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
SearchCriteria<ImageDataVO> sc = sb.create();
sc.setParameters("public", 1);
sc.setParameters("format", "ISO");
sc.setParameters("type", TemplateType.PERHOST.toString());
if (bootable != null) {
sc.setParameters("bootable", bootable);
}
if (!listRemoved) {
sc.setParameters("removed", (Object) null);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.ISO.toString());
for (String key : tags.keySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
count++;
}
}
return listBy(sc);
}
@Override
public List<ImageDataVO> userIsoSearch(boolean listRemoved) {
SearchBuilder<ImageDataVO> sb = null;
sb = UserIsoSearch;
SearchCriteria<ImageDataVO> sc = sb.create();
sc.setParameters("format", Storage.ImageFormat.ISO);
sc.setParameters("type", TemplateType.USER.toString());
if (!listRemoved) {
sc.setParameters("removed", (Object) null);
}
return listBy(sc);
}
@Override
public List<ImageDataVO> listAllSystemVMTemplates() {
SearchCriteria<ImageDataVO> sc = tmpltTypeSearch.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM);
Filter filter = new Filter(ImageDataVO.class, "id", false, null, null);
return listBy(sc, filter);
}
@Override
public List<Long> listPrivateTemplatesByHost(Long hostId) {
String sql = "select * from template_host_ref as thr INNER JOIN vm_template as t ON t.id=thr.template_id "
+ "where thr.host_id=? and t.public=0 and t.featured=0 and t.type='USER' and t.removed is NULL";
List<Long> l = new ArrayList<Long>();
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
pstmt.setLong(1, hostId);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
l.add(rs.getLong(1));
}
} catch (SQLException e) {
} catch (Throwable e) {
}
return l;
}
@Override
public List<ImageDataVO> listReadyTemplates() {
SearchCriteria<ImageDataVO> sc = createSearchCriteria();
sc.addAnd("ready", SearchCriteria.Op.EQ, true);
sc.addAnd("format", SearchCriteria.Op.NEQ, Storage.ImageFormat.ISO);
return listIncludingRemovedBy(sc);
}
@Override
public List<ImageDataVO> findIsosByIdAndPath(Long domainId, Long accountId, String path) {
SearchCriteria<ImageDataVO> sc = createSearchCriteria();
sc.addAnd("iso", SearchCriteria.Op.EQ, true);
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
if (accountId != null) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
}
if (path != null) {
sc.addAnd("path", SearchCriteria.Op.EQ, path);
}
return listIncludingRemovedBy(sc);
}
@Override
public List<ImageDataVO> listByAccountId(long accountId) {
SearchCriteria<ImageDataVO> sc = AccountIdSearch.create();
sc.setParameters("accountId", accountId);
return listBy(sc);
}
@Override
public List<ImageDataVO> listByHypervisorType(List<HypervisorType> hyperTypes) {
SearchCriteria<ImageDataVO> sc = createSearchCriteria();
hyperTypes.add(HypervisorType.None);
sc.addAnd("hypervisorType", SearchCriteria.Op.IN, hyperTypes.toArray());
return listBy(sc);
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
boolean result = super.configure(name, params);
PublicSearch = createSearchBuilder();
PublicSearch.and("public", PublicSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ);
routerTmpltName = (String) params.get("routing.uniquename");
s_logger.debug("Found parameter routing unique name " + routerTmpltName);
if (routerTmpltName == null) {
routerTmpltName = "routing";
}
consoleProxyTmpltName = (String) params.get("consoleproxy.uniquename");
if (consoleProxyTmpltName == null) {
consoleProxyTmpltName = "routing";
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Use console proxy template : " + consoleProxyTmpltName);
}
UniqueNameSearch = createSearchBuilder();
UniqueNameSearch.and("uniqueName", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ);
NameSearch = createSearchBuilder();
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
NameAccountIdSearch = createSearchBuilder();
NameAccountIdSearch.and("name", NameAccountIdSearch.entity().getName(), SearchCriteria.Op.EQ);
NameAccountIdSearch.and("accountId", NameAccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
PublicIsoSearch = createSearchBuilder();
PublicIsoSearch.and("public", PublicIsoSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ);
PublicIsoSearch.and("format", PublicIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ);
PublicIsoSearch.and("type", PublicIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
PublicIsoSearch.and("bootable", PublicIsoSearch.entity().isBootable(), SearchCriteria.Op.EQ);
PublicIsoSearch.and("removed", PublicIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ);
UserIsoSearch = createSearchBuilder();
UserIsoSearch.and("format", UserIsoSearch.entity().getFormat(), SearchCriteria.Op.EQ);
UserIsoSearch.and("type", UserIsoSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
UserIsoSearch.and("removed", UserIsoSearch.entity().getRemoved(), SearchCriteria.Op.EQ);
tmpltTypeHyperSearch = createSearchBuilder();
tmpltTypeHyperSearch.and("templateType", tmpltTypeHyperSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
SearchBuilder<HostVO> hostHyperSearch = hostDao.createSearchBuilder();
hostHyperSearch.and("type", hostHyperSearch.entity().getType(), SearchCriteria.Op.EQ);
hostHyperSearch.and("zoneId", hostHyperSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
hostHyperSearch.groupBy(hostHyperSearch.entity().getHypervisorType());
tmpltTypeHyperSearch.join("tmplHyper", hostHyperSearch, hostHyperSearch.entity().getHypervisorType(), tmpltTypeHyperSearch.entity().getHypervisorType(), JoinBuilder.JoinType.INNER);
hostHyperSearch.done();
tmpltTypeHyperSearch.done();
tmpltTypeHyperSearch2 = createSearchBuilder();
tmpltTypeHyperSearch2.and("templateType", tmpltTypeHyperSearch2.entity().getTemplateType(), SearchCriteria.Op.EQ);
tmpltTypeHyperSearch2.and("hypervisorType", tmpltTypeHyperSearch2.entity().getHypervisorType(), SearchCriteria.Op.EQ);
tmpltTypeSearch = createSearchBuilder();
tmpltTypeSearch.and("removed", tmpltTypeSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
tmpltTypeSearch.and("templateType", tmpltTypeSearch.entity().getTemplateType(), SearchCriteria.Op.EQ);
AccountIdSearch = createSearchBuilder();
AccountIdSearch.and("accountId", AccountIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
AccountIdSearch.and("publicTemplate", AccountIdSearch.entity().isPublicTemplate(), SearchCriteria.Op.EQ);
AccountIdSearch.done();
SearchBuilder<VMTemplateZoneVO> tmpltZoneSearch = templateZoneDao.createSearchBuilder();
tmpltZoneSearch.and("removed", tmpltZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
tmpltZoneSearch.and("zoneId", tmpltZoneSearch.entity().getZoneId(), SearchCriteria.Op.EQ);
TmpltsInZoneSearch = createSearchBuilder();
TmpltsInZoneSearch.and("removed", TmpltsInZoneSearch.entity().getRemoved(), SearchCriteria.Op.NULL);
TmpltsInZoneSearch.and().op("avoidtype", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NEQ);
TmpltsInZoneSearch.or("templateType", TmpltsInZoneSearch.entity().getTemplateType(), SearchCriteria.Op.NULL);
TmpltsInZoneSearch.cp();
TmpltsInZoneSearch.join("tmpltzone", tmpltZoneSearch, tmpltZoneSearch.entity().getTemplateId(), TmpltsInZoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
tmpltZoneSearch.done();
TmpltsInZoneSearch.done();
CountTemplatesByAccount = createSearchBuilder(Long.class);
CountTemplatesByAccount.select(null, Func.COUNT, null);
CountTemplatesByAccount.and("account", CountTemplatesByAccount.entity().getAccountId(), SearchCriteria.Op.EQ);
CountTemplatesByAccount.and("removed", CountTemplatesByAccount.entity().getRemoved(), SearchCriteria.Op.NULL);
CountTemplatesByAccount.done();
updateStateSearch = this.createSearchBuilder();
updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
updateStateSearch.done();
return result;
}
@Override
public String getRoutingTemplateUniqueName() {
return routerTmpltName;
}
@Override
public Set<Pair<Long, Long>> searchSwiftTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List<HypervisorType> hypers, Boolean bootable, DomainVO domain,
Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List<Account> permittedAccounts, Account caller, Map<String, String> tags) {
StringBuilder builder = new StringBuilder();
if (!permittedAccounts.isEmpty()) {
for (Account permittedAccount : permittedAccounts) {
builder.append(permittedAccount.getAccountId() + ",");
}
}
String permittedAccountsStr = builder.toString();
if (permittedAccountsStr.length() > 0) {
// chop the "," off
permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1);
}
Transaction txn = Transaction.currentTxn();
txn.start();
Set<Pair<Long, Long>> templateZonePairList = new HashSet<Pair<Long, Long>>();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = SELECT_TEMPLATE_SWIFT_REF;
try {
String joinClause = "";
String whereClause = " WHERE t.removed IS NULL";
if (isIso) {
whereClause += " AND t.format = 'ISO'";
if (!hyperType.equals(HypervisorType.None)) {
joinClause = " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) ";
whereClause += " AND goh.hypervisor_type = '" + hyperType.toString() + "'";
}
} else {
whereClause += " AND t.format <> 'ISO'";
if (hypers.isEmpty()) {
return templateZonePairList;
} else {
StringBuilder relatedHypers = new StringBuilder();
for (HypervisorType hyper : hypers) {
relatedHypers.append("'");
relatedHypers.append(hyper.toString());
relatedHypers.append("'");
relatedHypers.append(",");
}
relatedHypers.setLength(relatedHypers.length() - 1);
whereClause += " AND t.hypervisor_type IN (" + relatedHypers + ")";
}
}
joinClause += " INNER JOIN template_swift_ref tsr on (t.id = tsr.template_id)";
if (keyword != null) {
whereClause += " AND t.name LIKE \"%" + keyword + "%\"";
} else if (name != null) {
whereClause += " AND t.name LIKE \"%" + name + "%\"";
}
if (bootable != null) {
whereClause += " AND t.bootable = " + bootable;
}
if (!showDomr) {
whereClause += " AND t.type != '" + Storage.TemplateType.SYSTEM.toString() + "'";
}
if (templateFilter == TemplateFilter.featured) {
whereClause += " AND t.public = 1 AND t.featured = 1";
} else if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
joinClause += " INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)";
whereClause += " AND d.path LIKE '" + domain.getPath() + "%'";
} else {
whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")";
}
} else if (templateFilter == TemplateFilter.sharedexecutable && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
joinClause += " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE" + " (t.account_id IN (" + permittedAccountsStr + ") OR" + " lp.account_id IN ("
+ permittedAccountsStr + "))";
} else {
joinClause += " INNER JOIN account a on (t.account_id = a.id) ";
}
} else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) {
whereClause += " AND (t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))";
} else if (templateFilter == TemplateFilter.community) {
whereClause += " AND t.public = 1 AND t.featured = 0";
} else if (templateFilter == TemplateFilter.all && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) {
} else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
return templateZonePairList;
}
sql += joinClause + whereClause + getOrderByLimit(pageSize, startIndex);
pstmt = txn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Pair<Long, Long> templateZonePair = new Pair<Long, Long>(rs.getLong(1), -1L);
templateZonePairList.add(templateZonePair);
}
} catch (Exception e) {
s_logger.warn("Error listing templates", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
txn.commit();
} catch (SQLException sqle) {
s_logger.warn("Error in cleaning up", sqle);
}
}
return templateZonePairList;
}
@Override
public Set<Pair<Long, Long>> searchTemplates(String name, String keyword, TemplateFilter templateFilter, boolean isIso, List<HypervisorType> hypers, Boolean bootable, DomainVO domain,
Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List<Account> permittedAccounts, Account caller,
ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags) {
StringBuilder builder = new StringBuilder();
if (!permittedAccounts.isEmpty()) {
for (Account permittedAccount : permittedAccounts) {
builder.append(permittedAccount.getAccountId() + ",");
}
}
String permittedAccountsStr = builder.toString();
if (permittedAccountsStr.length() > 0) {
// chop the "," off
permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1);
}
Transaction txn = Transaction.currentTxn();
txn.start();
/* Use LinkedHashSet here to guarantee iteration order */
Set<Pair<Long, Long>> templateZonePairList = new LinkedHashSet<Pair<Long, Long>>();
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuilder relatedDomainIds = new StringBuilder();
String sql = SELECT_TEMPLATE_ZONE_REF;
String groupByClause = "";
try {
// short accountType;
// String accountId = null;
String guestOSJoin = "";
StringBuilder templateHostRefJoin = new StringBuilder();
String dataCenterJoin = "", lpjoin = "";
String tagsJoin = "";
if (isIso && !hyperType.equals(HypervisorType.None)) {
guestOSJoin = " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) ";
}
if (onlyReady) {
templateHostRefJoin.append(" INNER JOIN template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)");
sql = SELECT_TEMPLATE_HOST_REF;
groupByClause = " GROUP BY t.id, h.data_center_id ";
}
if ((templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.community)) {
dataCenterJoin = " INNER JOIN data_center dc on (h.data_center_id = dc.id)";
}
if (templateFilter == TemplateFilter.sharedexecutable) {
lpjoin = " INNER JOIN launch_permission lp ON t.id = lp.template_id ";
}
if (tags != null && !tags.isEmpty()) {
tagsJoin = " INNER JOIN resource_tags r ON t.id = r.resource_id ";
}
sql += guestOSJoin + templateHostRefJoin + dataCenterJoin + lpjoin + tagsJoin;
String whereClause = "";
// All joins have to be made before we start setting the condition
// settings
if ((listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources || (!permittedAccounts.isEmpty() && !(templateFilter == TemplateFilter.community || templateFilter == TemplateFilter.featured)))
&& !(caller.getType() != Account.ACCOUNT_TYPE_NORMAL && templateFilter == TemplateFilter.all)) {
whereClause += " INNER JOIN account a on (t.account_id = a.id)";
if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable)
&& (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
whereClause += " INNER JOIN domain d on (a.domain_id = d.id) WHERE d.path LIKE '" + domain.getPath() + "%'";
if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
whereClause += " AND a.type != " + Account.ACCOUNT_TYPE_PROJECT;
}
} else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
whereClause += " WHERE a.type != " + Account.ACCOUNT_TYPE_PROJECT;
}
}
if (!permittedAccounts.isEmpty()) {
for (Account account : permittedAccounts) {
// accountType = account.getType();
// accountId = Long.toString(account.getId());
DomainVO accountDomain = domainDao.findById(account.getDomainId());
// get all parent domain ID's all the way till root domain
DomainVO domainTreeNode = accountDomain;
while (true) {
relatedDomainIds.append(domainTreeNode.getId());
relatedDomainIds.append(",");
if (domainTreeNode.getParent() != null) {
domainTreeNode = domainDao.findById(domainTreeNode.getParent());
} else {
break;
}
}
// get all child domain ID's
if (isAdmin(account.getType())) {
List<DomainVO> allChildDomains = domainDao.findAllChildren(accountDomain.getPath(), accountDomain.getId());
for (DomainVO childDomain : allChildDomains) {
relatedDomainIds.append(childDomain.getId());
relatedDomainIds.append(",");
}
}
relatedDomainIds.setLength(relatedDomainIds.length() - 1);
}
}
String attr = " AND ";
if (whereClause.endsWith(" WHERE ")) {
attr += " WHERE ";
}
if (!isIso) {
if (hypers.isEmpty()) {
return templateZonePairList;
} else {
StringBuilder relatedHypers = new StringBuilder();
for (HypervisorType hyper : hypers) {
relatedHypers.append("'");
relatedHypers.append(hyper.toString());
relatedHypers.append("'");
relatedHypers.append(",");
}
relatedHypers.setLength(relatedHypers.length() - 1);
whereClause += attr + " t.hypervisor_type IN (" + relatedHypers + ")";
}
}
if (!permittedAccounts.isEmpty() && !(templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community || templateFilter == TemplateFilter.executable)
&& !isAdmin(caller.getType())) {
whereClause += attr + "t.account_id IN (" + permittedAccountsStr + ")";
}
if (templateFilter == TemplateFilter.featured) {
whereClause += attr + "t.public = 1 AND t.featured = 1";
if (!permittedAccounts.isEmpty()) {
whereClause += attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)";
}
} else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")";
} else if (templateFilter == TemplateFilter.sharedexecutable) {
whereClause += " AND " + " (t.account_id IN (" + permittedAccountsStr + ") OR" + " lp.account_id IN (" + permittedAccountsStr + "))";
} else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) {
whereClause += attr + "(t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))";
} else if (templateFilter == TemplateFilter.community) {
whereClause += attr + "t.public = 1 AND t.featured = 0";
if (!permittedAccounts.isEmpty()) {
whereClause += attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)";
}
} else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && !isIso) {
return templateZonePairList;
}
if (tags != null && !tags.isEmpty()) {
whereClause += " AND (";
boolean first = true;
for (String key : tags.keySet()) {
if (!first) {
whereClause += " OR ";
}
whereClause += "(r.key=\"" + key + "\" and r.value=\"" + tags.get(key) + "\")";
first = false;
}
whereClause += ")";
}
if (whereClause.equals("")) {
whereClause += " WHERE ";
} else if (!whereClause.equals(" WHERE ")) {
whereClause += " AND ";
}
sql += whereClause + getExtrasWhere(templateFilter, name, keyword, isIso, bootable, hyperType, zoneId, onlyReady, showDomr) + groupByClause + getOrderByLimit(pageSize, startIndex);
pstmt = txn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Pair<Long, Long> templateZonePair = new Pair<Long, Long>(rs.getLong(1), rs.getLong(2));
templateZonePairList.add(templateZonePair);
}
// for now, defaulting pageSize to a large val if null; may need to
// revisit post 2.2RC2
if (isIso &&
templateZonePairList.size() < (pageSize != null ? pageSize : 500) &&
templateFilter != TemplateFilter.community &&
!(templateFilter == TemplateFilter.self) /* TODO: Fix this! && !BaseCmd.isRootAdmin(caller.getType())*/) { // evaluates
// to
// true
// If
// root
// admin
// and
// filter=self
List<ImageDataVO> publicIsos = publicIsoSearch(bootable, false, tags);
List<ImageDataVO> userIsos = userIsoSearch(false);
// Listing the ISOs according to the page size.Restricting the
// total no. of ISOs on a page
// to be less than or equal to the pageSize parameter
int i = 0;
if (startIndex > userIsos.size()) {
i = (int) (startIndex - userIsos.size());
}
for (; i < publicIsos.size(); i++) {
if (templateZonePairList.size() >= pageSize) {
break;
} else {
if (keyword != null && publicIsos.get(i).getName().contains(keyword)) {
templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
continue;
} else if (name != null && publicIsos.get(i).getName().contains(name)) {
templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
continue;
} else if (keyword == null && name == null) {
templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
}
}
}
}
} catch (Exception e) {
s_logger.warn("Error listing templates", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
txn.commit();
} catch (SQLException sqle) {
s_logger.warn("Error in cleaning up", sqle);
}
}
return templateZonePairList;
}
private String getExtrasWhere(TemplateFilter templateFilter, String name, String keyword, boolean isIso, Boolean bootable, HypervisorType hyperType, Long zoneId, boolean onlyReady,
boolean showDomr) {
String sql = "";
if (keyword != null) {
sql += " t.name LIKE \"%" + keyword + "%\" AND";
} else if (name != null) {
sql += " t.name LIKE \"%" + name + "%\" AND";
}
if (isIso) {
sql += " t.format = 'ISO'";
if (!hyperType.equals(HypervisorType.None)) {
sql += " AND goh.hypervisor_type = '" + hyperType.toString() + "'";
}
} else {
sql += " t.format <> 'ISO'";
if (!hyperType.equals(HypervisorType.None)) {
sql += " AND t.hypervisor_type = '" + hyperType.toString() + "'";
}
}
if (bootable != null) {
sql += " AND t.bootable = " + bootable;
}
if (onlyReady) {
sql += " AND thr.download_state = '" + Status.DOWNLOADED.toString() + "'" + " AND thr.destroyed=0 ";
if (zoneId != null) {
sql += " AND h.data_center_id = " + zoneId;
}
} else if (zoneId != null) {
sql += " AND tzr.zone_id = " + zoneId + " AND tzr.removed is null";
} else {
sql += " AND tzr.removed is null ";
}
if (!showDomr) {
sql += " AND t.type != '" + Storage.TemplateType.SYSTEM.toString() + "'";
}
sql += " AND t.removed IS NULL";
return sql;
}
private String getOrderByLimit(Long pageSize, Long startIndex) {
Boolean isAscending = Boolean.parseBoolean(configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
String sql;
if (isAscending) {
sql = " ORDER BY t.sort_key ASC";
} else {
sql = " ORDER BY t.sort_key DESC";
}
if ((pageSize != null) && (startIndex != null)) {
sql += " LIMIT " + startIndex.toString() + "," + pageSize.toString();
}
return sql;
}
@Override
@DB
public long addTemplateToZone(ImageDataVO tmplt, long zoneId) {
Transaction txn = Transaction.currentTxn();
txn.start();
ImageDataVO tmplt2 = findById(tmplt.getId());
if (tmplt2 == null) {
if (persist(tmplt) == null) {
throw new CloudRuntimeException("Failed to persist the template " + tmplt);
}
if (tmplt.getDetails() != null) {
templateDetailsDao.persist(tmplt.getId(), tmplt.getDetails());
}
}
VMTemplateZoneVO tmpltZoneVO = templateZoneDao.findByZoneTemplate(zoneId, tmplt.getId());
if (tmpltZoneVO == null) {
tmpltZoneVO = new VMTemplateZoneVO(zoneId, tmplt.getId(), new Date());
templateZoneDao.persist(tmpltZoneVO);
} else {
tmpltZoneVO.setRemoved(null);
tmpltZoneVO.setLastUpdated(new Date());
templateZoneDao.update(tmpltZoneVO.getId(), tmpltZoneVO);
}
txn.commit();
return tmplt.getId();
}
@Override
@DB
public List<ImageDataVO> listAllInZone(long dataCenterId) {
SearchCriteria<ImageDataVO> sc = TmpltsInZoneSearch.create();
sc.setParameters("avoidtype", TemplateType.PERHOST.toString());
sc.setJoinParameters("tmpltzone", "zoneId", dataCenterId);
return listBy(sc);
}
@Override
public List<ImageDataVO> listDefaultBuiltinTemplates() {
SearchCriteria<ImageDataVO> sc = tmpltTypeSearch.create();
sc.setParameters("templateType", Storage.TemplateType.BUILTIN);
return listBy(sc);
}
@Override
public ImageDataVO findSystemVMTemplate(long zoneId) {
SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM);
sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing);
sc.setJoinParameters("tmplHyper", "zoneId", zoneId);
// order by descending order of id and select the first (this is going
// to be the latest)
List<ImageDataVO> tmplts = listBy(sc, new Filter(ImageDataVO.class, "id", false, null, 1l));
if (tmplts.size() > 0) {
return tmplts.get(0);
} else {
return null;
}
}
@Override
public ImageDataVO findSystemVMTemplate(long zoneId, HypervisorType hType) {
SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM);
sc.setJoinParameters("tmplHyper", "type", Host.Type.Routing);
sc.setJoinParameters("tmplHyper", "zoneId", zoneId);
// order by descending order of id
List<ImageDataVO> tmplts = listBy(sc, new Filter(ImageDataVO.class, "id", false, null, null));
for (ImageDataVO tmplt : tmplts) {
if (tmplt.getHypervisorType() == hType) {
return tmplt;
}
}
if (tmplts.size() > 0 && hType == HypervisorType.Any) {
return tmplts.get(0);
}
return null;
}
@Override
public ImageDataVO findRoutingTemplate(HypervisorType hType) {
SearchCriteria<ImageDataVO> sc = tmpltTypeHyperSearch2.create();
sc.setParameters("templateType", Storage.TemplateType.SYSTEM);
sc.setParameters("hypervisorType", hType);
// order by descending order of id and select the first (this is going
// to be the latest)
List<ImageDataVO> tmplts = listBy(sc, new Filter(ImageDataVO.class, "id", false, null, 1l));
if (tmplts.size() > 0) {
return tmplts.get(0);
} else {
return null;
}
}
@Override
public Long countTemplatesForAccount(long accountId) {
SearchCriteria<Long> sc = CountTemplatesByAccount.create();
sc.setParameters("account", accountId);
return customSearch(sc, null).get(0);
}
@Override
@DB
public boolean remove(Long id) {
Transaction txn = Transaction.currentTxn();
txn.start();
ImageDataVO template = createForUpdate();
template.setRemoved(new Date());
ImageDataVO vo = findById(id);
if (vo != null) {
if (vo.getFormat().equalsIgnoreCase(new ISO().toString())) {
_tagsDao.removeByIdAndType(id, TaggedResourceType.ISO);
} else {
_tagsDao.removeByIdAndType(id, TaggedResourceType.Template);
}
}
boolean result = update(id, template);
txn.commit();
return result;
}
private boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
@Override
public boolean updateState(TemplateState currentState, TemplateEvent event,
TemplateState nextState, ImageDataVO vo, Object data) {
Long oldUpdated = vo.getUpdatedCount();
Date oldUpdatedTime = vo.getUpdated();
SearchCriteria<ImageDataVO> sc = updateStateSearch.create();
sc.setParameters("id", vo.getId());
sc.setParameters("state", currentState);
sc.setParameters("updatedCount", vo.getUpdatedCount());
vo.incrUpdatedCount();
UpdateBuilder builder = getUpdateBuilder(vo);
builder.set(vo, "state", nextState);
builder.set(vo, "updated", new Date());
int rows = update((ImageDataVO) vo, sc);
if (rows == 0 && s_logger.isDebugEnabled()) {
ImageDataVO dbVol = findByIdIncludingRemoved(vo.getId());
if (dbVol != null) {
StringBuilder str = new StringBuilder("Unable to update ").append(vo.toString());
str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState()).append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
.append(dbVol.getUpdated());
str.append(": New Data={id=").append(vo.getId()).append("; state=").append(nextState).append("; event=").append(event).append("; updatecount=").append(vo.getUpdatedCount())
.append("; updatedTime=").append(vo.getUpdated());
str.append(": stale Data={id=").append(vo.getId()).append("; state=").append(currentState).append("; event=").append(event).append("; updatecount=").append(oldUpdated)
.append("; updatedTime=").append(oldUpdatedTime);
} else {
s_logger.debug("Unable to update objectIndatastore: id=" + vo.getId() + ", as there is no such object exists in the database anymore");
}
}
return rows > 0;
}
}

View File

@ -24,6 +24,7 @@ import java.util.Date;
import java.util.List;
import javax.ejb.Local;
import javax.inject.Inject;
import org.apache.cloudstack.engine.subsystem.api.storage.type.RootDisk;
import org.apache.cloudstack.engine.subsystem.api.storage.type.VolumeType;
@ -36,6 +37,7 @@ import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Volume;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.Pair;
@ -63,8 +65,7 @@ public class VolumeDao2Impl extends GenericDaoBase<VolumeVO, Long> implements Vo
protected final SearchBuilder<VolumeVO> InstanceStatesSearch;
protected final SearchBuilder<VolumeVO> AllFieldsSearch;
protected GenericSearchBuilder<VolumeVO, Long> CountByAccount;
//ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
ResourceTagsDaoImpl _tagsDao = null;
@Inject ResourceTagDao _tagsDao = null;
protected static final String SELECT_VM_SQL = "SELECT DISTINCT instance_id from volumes v where v.host_id = ? and v.mirror_state = ?";
protected static final String SELECT_HYPERTYPE_FROM_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?";

View File

@ -156,4 +156,6 @@ public interface AgentManager extends Manager {
boolean reconnect(long hostId);
Answer sendToSSVM(Long dcId, final Command cmd);
void disconnectWithInvestigation(final long hostId, final Status.Event event);
}

View File

@ -218,7 +218,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
protected int _pingInterval;
protected long _pingTimeout;
@Inject protected AgentMonitor _monitor;
@Inject protected AgentMonitorService _monitor;
protected ExecutorService _executor;
protected ThreadPoolExecutor _connectExecutor;
@ -668,7 +668,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
public boolean start() {
startDirectlyConnectedHosts();
if (_monitor != null) {
_monitor.start();
_monitor.startMonitoring();
}
if (_connection != null) {
_connection.start();
@ -1455,7 +1455,7 @@ public class AgentManagerImpl extends ManagerBase implements AgentManager, Handl
_executor.submit(new DisconnectTask(attache, event, false));
}
protected void disconnectWithInvestigation(AgentAttache attache, final Status.Event event) {
public void disconnectWithInvestigation(AgentAttache attache, final Status.Event event) {
_executor.submit(new DisconnectTask(attache, event, true));
}

View File

@ -26,6 +26,7 @@ import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
@ -56,13 +57,13 @@ import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.dao.VMInstanceDao;
@Component
public class AgentMonitor extends Thread implements Listener {
public class AgentMonitor extends Thread implements AgentMonitorService {
private static Logger s_logger = Logger.getLogger(AgentMonitor.class);
private static Logger status_Logger = Logger.getLogger(Status.class);
private long _pingTimeout;
@Inject private HostDao _hostDao;
private boolean _stop;
@Inject private AgentManagerImpl _agentMgr;
@Inject private AgentManager _agentMgr;
@Inject private VMInstanceDao _vmDao;
@Inject private DataCenterDao _dcDao = null;
@Inject private HostPodDao _podDao = null;
@ -296,4 +297,8 @@ public class AgentMonitor extends Thread implements Listener {
return -1;
}
public void startMonitoring() {
start();
}
}

View File

@ -0,0 +1,28 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.agent.manager;
import com.cloud.agent.Listener;
public interface AgentMonitorService extends Listener {
public Boolean isAgentBehindOnPing(long agentId);
public Long getAgentPingTime(long agentId);
public void pingBy(long agentId);
public void signalStop();
public void startMonitoring();
}

View File

@ -135,7 +135,9 @@ public class ApiDispatcher {
processParameters(cmd, params);
UserContext ctx = UserContext.current();
ctx.setAccountId(cmd.getEntityOwnerId());
if (cmd instanceof BaseAsyncCmd) {
BaseCmd realCmdObj = ComponentContext.getTargetObject(cmd);
if (realCmdObj instanceof BaseAsyncCmd) {
BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
String startEventId = params.get("ctxStartEventId");

View File

@ -142,7 +142,7 @@ import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
public class ApiServer implements HttpRequestHandler {
public class ApiServer implements HttpRequestHandler, ApiServerService {
private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
@ -500,22 +500,22 @@ public class ApiServer implements HttpRequestHandler {
// if the command is of the listXXXCommand, we will need to also return the
// the job id and status if possible
// For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views.
if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd)
&& !(cmdObj instanceof ListSecurityGroupsCmd)
&& !(cmdObj instanceof ListTagsCmd)
&& !(cmdObj instanceof ListEventsCmd)
&& !(cmdObj instanceof ListVMGroupsCmd)
&& !(cmdObj instanceof ListProjectsCmd)
&& !(cmdObj instanceof ListProjectAccountsCmd)
&& !(cmdObj instanceof ListProjectInvitationsCmd)
&& !(cmdObj instanceof ListHostsCmd)
&& !(cmdObj instanceof ListVolumesCmd)
&& !(cmdObj instanceof ListUsersCmd)
&& !(cmdObj instanceof ListAccountsCmd)
&& !(cmdObj instanceof ListStoragePoolsCmd)
&& !(cmdObj instanceof ListDiskOfferingsCmd)
&& !(cmdObj instanceof ListServiceOfferingsCmd)
&& !(cmdObj instanceof ListZonesByCmd)
if (realCmdObj instanceof BaseListCmd && !(realCmdObj instanceof ListVMsCmd) && !(realCmdObj instanceof ListRoutersCmd)
&& !(realCmdObj instanceof ListSecurityGroupsCmd)
&& !(realCmdObj instanceof ListTagsCmd)
&& !(realCmdObj instanceof ListEventsCmd)
&& !(realCmdObj instanceof ListVMGroupsCmd)
&& !(realCmdObj instanceof ListProjectsCmd)
&& !(realCmdObj instanceof ListProjectAccountsCmd)
&& !(realCmdObj instanceof ListProjectInvitationsCmd)
&& !(realCmdObj instanceof ListHostsCmd)
&& !(realCmdObj instanceof ListVolumesCmd)
&& !(realCmdObj instanceof ListUsersCmd)
&& !(realCmdObj instanceof ListAccountsCmd)
&& !(realCmdObj instanceof ListStoragePoolsCmd)
&& !(realCmdObj instanceof ListDiskOfferingsCmd)
&& !(realCmdObj instanceof ListServiceOfferingsCmd)
&& !(realCmdObj instanceof ListZonesByCmd)
) {
buildAsyncListResponse((BaseListCmd) cmdObj, caller);
}

View File

@ -0,0 +1,37 @@
// 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.Map;
import javax.servlet.http.HttpSession;
import org.apache.cloudstack.api.ServerApiException;
import com.cloud.exception.CloudAuthenticationException;
public interface ApiServerService {
public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException;
public Long fetchDomainId(String domainUUID);
public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath, String loginIpAddress ,Map<String, Object[]> requestParameters) throws CloudAuthenticationException;
public void logoutUser(long userId);
public boolean verifyUser(Long userId);
public String getSerializedApiError(int errorCode, String errorText, Map<String, Object[]> apiCommandParams, String responseType);
public String getSerializedApiError(ServerApiException ex, Map<String, Object[]> apiCommandParams, String responseType);
public String handleRequest(Map params, String responseType, StringBuffer auditTrailSb) throws ServerApiException;
}

View File

@ -50,7 +50,7 @@ public class ApiServlet extends HttpServlet {
public static final Logger s_logger = Logger.getLogger(ApiServlet.class.getName());
private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName());
@Inject ApiServer _apiServer;
@Inject ApiServerService _apiServer;
@Inject AccountService _accountMgr;
public ApiServlet() {

View File

@ -86,6 +86,7 @@ import com.cloud.dc.dao.AccountVlanMapDao;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterIpAddressDao;
import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDao;
import com.cloud.dc.dao.DataCenterLinkLocalIpAddressDaoImpl;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.PodVlanMapDao;
@ -249,7 +250,7 @@ public class ConfigurationManagerImpl extends ManagerBase implements Configurati
VpcManager _vpcMgr;
// FIXME - why don't we have interface for DataCenterLinkLocalIpAddressDao?
@Inject protected DataCenterLinkLocalIpAddressDaoImpl _LinkLocalIpAllocDao;
@Inject protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao;
private int _maxVolumeSizeInGb;
private long _defaultPageSize;

View File

@ -65,15 +65,6 @@ public class ConfigurationDaoImpl extends GenericDaoBase<ConfigurationVO, String
return _premium;
}
@PostConstruct
void initComponent() {
try {
configure(this.getClass().getSimpleName(), this.getConfigParams());
} catch (ConfigurationException e) {
s_logger.warn("Self configuration failed", e);
}
}
@Override
public void invalidateCache() {
_configs = null;

View File

@ -31,8 +31,10 @@ import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.ResourceLimit;
import com.cloud.domain.dao.DomainDao;
import com.cloud.domain.dao.DomainDaoImpl;
import com.cloud.exception.UnsupportedServiceException;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.AccountDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
@ -48,11 +50,8 @@ public class ResourceCountDaoImpl extends GenericDaoBase<ResourceCountVO, Long>
private final SearchBuilder<ResourceCountVO> AccountSearch;
private final SearchBuilder<ResourceCountVO> DomainSearch;
//protected final DomainDaoImpl _domainDao = ComponentLocator.inject(DomainDaoImpl.class);
//protected final AccountDaoImpl _accountDao = ComponentLocator.inject(AccountDaoImpl.class);
@Inject protected DomainDaoImpl _domainDao;
@Inject protected AccountDaoImpl _accountDao;
@Inject protected DomainDao _domainDao;
@Inject protected AccountDao _accountDao;
public ResourceCountDaoImpl() {
TypeSearch = createSearchBuilder();

View File

@ -63,11 +63,11 @@ public class DataCenterDaoImpl extends GenericDaoBase<DataCenterVO, Long> implem
protected SearchBuilder<DataCenterVO> DisabledZonesSearch;
protected SearchBuilder<DataCenterVO> TokenSearch;
@Inject protected DataCenterIpAddressDaoImpl _ipAllocDao = null;
@Inject protected DataCenterLinkLocalIpAddressDaoImpl _LinkLocalIpAllocDao = null;
@Inject protected DataCenterVnetDaoImpl _vnetAllocDao = null;
@Inject protected PodVlanDaoImpl _podVlanAllocDao = null;
@Inject protected DcDetailsDaoImpl _detailsDao = null;
@Inject protected DataCenterIpAddressDao _ipAllocDao = null;
@Inject protected DataCenterLinkLocalIpAddressDao _LinkLocalIpAllocDao = null;
@Inject protected DataCenterVnetDao _vnetAllocDao = null;
@Inject protected PodVlanDao _podVlanAllocDao = null;
@Inject protected DcDetailsDao _detailsDao = null;
protected long _prefix;
protected Random _rand = new Random(System.currentTimeMillis());

View File

@ -23,6 +23,12 @@ import com.cloud.utils.db.GenericDao;
public interface DataCenterIpAddressDao extends GenericDao<DataCenterIpAddressVO, Long> {
public DataCenterIpAddressVO takeIpAddress(long dcId, long podId, long instanceId, String reservationId);
public DataCenterIpAddressVO takeDataCenterIpAddress(long dcId, String reservationId);
public void addIpRange(long dcId, long podId, String start, String end);
public void releaseIpAddress(String ipAddress, long dcId, Long instanceId);
public void releaseIpAddress(long nicId, String reservationId);
boolean mark(long dcId, long podId, String ip);
List<DataCenterIpAddressVO> listByPodIdDcIdIpAddress(long podId, long dcId, String ipAddress);
List<DataCenterIpAddressVO> listByPodIdDcId(long podId, long dcId);

View File

@ -0,0 +1,16 @@
package com.cloud.dc.dao;
import java.util.List;
import com.cloud.dc.DataCenterLinkLocalIpAddressVO;
import com.cloud.utils.db.GenericDao;
public interface DataCenterLinkLocalIpAddressDao extends GenericDao<DataCenterLinkLocalIpAddressVO, Long>{
public DataCenterLinkLocalIpAddressVO takeIpAddress(long dcId, long podId, long instanceId, String reservationId);
public boolean deleteIpAddressByPod(long podId);
public void addIpRange(long dcId, long podId, String start, String end);
public void releaseIpAddress(String ipAddress, long dcId, long instanceId);
public void releaseIpAddress(long nicId, String reservationId);
public List<DataCenterLinkLocalIpAddressVO> listByPodIdDcId(long podId, long dcId);
public int countIPs(long podId, long dcId, boolean onlyCountAllocated);
}

View File

@ -42,7 +42,7 @@ import com.cloud.utils.net.NetUtils;
@Component
@Local(value={DataCenterLinkLocalIpAddressDaoImpl.class}) @DB(txn=false)
public class DataCenterLinkLocalIpAddressDaoImpl extends GenericDaoBase<DataCenterLinkLocalIpAddressVO, Long> implements GenericDao<DataCenterLinkLocalIpAddressVO, Long> {
public class DataCenterLinkLocalIpAddressDaoImpl extends GenericDaoBase<DataCenterLinkLocalIpAddressVO, Long> implements DataCenterLinkLocalIpAddressDao {
private static final Logger s_logger = Logger.getLogger(DataCenterLinkLocalIpAddressDaoImpl.class);
private final SearchBuilder<DataCenterLinkLocalIpAddressVO> AllFieldsSearch;

View File

@ -0,0 +1,38 @@
// 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.dc.dao;
import java.util.List;
import com.cloud.dc.DataCenterVnetVO;
import com.cloud.utils.db.GenericDao;
public interface DataCenterVnetDao extends GenericDao<DataCenterVnetVO, Long> {
public List<DataCenterVnetVO> listAllocatedVnets(long physicalNetworkId);
public List<DataCenterVnetVO> findVnet(long dcId, String vnet);
public int countZoneVlans(long dcId, boolean onlyCountAllocated);
public List<DataCenterVnetVO> findVnet(long dcId, long physicalNetworkId, String vnet);
public void add(long dcId, long physicalNetworkId, int start, int end);
public void delete(long physicalNetworkId);
public DataCenterVnetVO take(long physicalNetworkId, long accountId, String reservationId);
public void release(String vnet, long physicalNetworkId, long accountId, String reservationId);
}

View File

@ -41,7 +41,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
*/
@Component
@DB(txn=false)
public class DataCenterVnetDaoImpl extends GenericDaoBase<DataCenterVnetVO, Long> implements GenericDao<DataCenterVnetVO, Long> {
public class DataCenterVnetDaoImpl extends GenericDaoBase<DataCenterVnetVO, Long> implements DataCenterVnetDao {
private final SearchBuilder<DataCenterVnetVO> FreeVnetSearch;
private final SearchBuilder<DataCenterVnetVO> VnetDcSearch;
private final SearchBuilder<DataCenterVnetVO> VnetDcSearchAllocated;

View File

@ -0,0 +1,30 @@
// 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.dc.dao;
import java.util.List;
import com.cloud.dc.PodVlanVO;
import com.cloud.utils.db.GenericDao;
public interface PodVlanDao extends GenericDao<PodVlanVO, Long> {
public List<PodVlanVO> listAllocatedVnets(long podId);
public void add(long podId, int start, int end);
public void delete(long podId);
public PodVlanVO take(long podId, long accountId);
public void release(String vlan, long podId, long accountId);
}

View File

@ -35,7 +35,7 @@ import com.cloud.utils.exception.CloudRuntimeException;
* PodVlanDaoImpl maintains the one-to-many relationship between
*/
@Component
public class PodVlanDaoImpl extends GenericDaoBase<PodVlanVO, Long> implements GenericDao<PodVlanVO, Long> {
public class PodVlanDaoImpl extends GenericDaoBase<PodVlanVO, Long> implements PodVlanDao {
private final SearchBuilder<PodVlanVO> FreeVlanSearch;
private final SearchBuilder<PodVlanVO> VlanPodSearch;
private final SearchBuilder<PodVlanVO> PodSearchAllocated;

View File

@ -113,6 +113,7 @@ import com.cloud.utils.AnnotationHelper;
import com.cloud.utils.Journal;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.Manager;
import com.cloud.utils.component.ManagerBase;
import com.cloud.utils.db.*;
@ -2978,10 +2979,12 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName(), null, null);
// add instance of the provider
VirtualRouterElement element = (VirtualRouterElement) _networkModel.getElementImplementingProvider(Network.Provider.VirtualRouter.getName());
if (element == null) {
NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VirtualRouter Provider");
}
VirtualRouterElement element = ComponentContext.getTargetObject(networkElement);
element.addElement(nsp.getId(), VirtualRouterProviderType.VirtualRouter);
return nsp;
@ -3003,11 +3006,13 @@ public class NetworkServiceImpl extends ManagerBase implements NetworkService {
PhysicalNetworkServiceProvider nsp = addProviderToPhysicalNetwork(physicalNetworkId,
Network.Provider.VPCVirtualRouter.getName(), null, null);
// add instance of the provider
VpcVirtualRouterElement element = (VpcVirtualRouterElement) _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
if (element == null) {
NetworkElement networkElement = _networkModel.getElementImplementingProvider(Network.Provider.VPCVirtualRouter.getName());
if (networkElement == null) {
throw new CloudRuntimeException("Unable to find the Network Element implementing the VPCVirtualRouter Provider");
}
VpcVirtualRouterElement element = ComponentContext.getTargetObject(networkElement);
element.addElement(nsp.getId(), VirtualRouterProviderType.VPCVirtualRouter);
return nsp;

View File

@ -30,6 +30,7 @@ import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.FirewallRule.TrafficType;
import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
@ -53,8 +54,8 @@ public class FirewallRulesDaoImpl extends GenericDaoBase<FirewallRuleVO, Long> i
protected final SearchBuilder<FirewallRuleVO> SystemRuleSearch;
protected final GenericSearchBuilder<FirewallRuleVO, Long> RulesByIpCount;
@Inject protected FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject protected FirewallRulesCidrsDao _firewallRulesCidrsDao;
@Inject ResourceTagDao _tagsDao;
@Inject IPAddressDao _ipDao;
protected FirewallRulesDaoImpl() {

View File

@ -30,9 +30,11 @@ import org.springframework.stereotype.Component;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.VlanDao;
import com.cloud.dc.dao.VlanDaoImpl;
import com.cloud.network.IpAddress.State;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
@ -57,9 +59,9 @@ public class IPAddressDaoImpl extends GenericDaoBase<IPAddressVO, Long> implemen
protected GenericSearchBuilder<IPAddressVO, Integer> AllocatedIpCount;
protected GenericSearchBuilder<IPAddressVO, Integer> AllIpCountForDashboard;
protected GenericSearchBuilder<IPAddressVO, Long> AllocatedIpCountForAccount;
@Inject protected VlanDaoImpl _vlanDao;
@Inject protected VlanDao _vlanDao;
protected GenericSearchBuilder<IPAddressVO, Long> CountFreePublicIps;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
// make it public for JUnit test
public IPAddressDaoImpl() {

View File

@ -51,7 +51,7 @@ public class LoadBalancerDaoImpl extends GenericDaoBase<LoadBalancerVO, Long> im
private final SearchBuilder<LoadBalancerVO> AccountAndNameSearch;
protected final SearchBuilder<LoadBalancerVO> TransitionStateSearch;
@Inject protected FirewallRulesCidrsDaoImpl _portForwardingRulesCidrsDao;
@Inject protected FirewallRulesCidrsDao _portForwardingRulesCidrsDao;
protected LoadBalancerDaoImpl() {
ListByIp = createSearchBuilder();

View File

@ -0,0 +1,22 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.dao;
import com.cloud.utils.db.GenericDao;
public interface NetworkAccountDao extends GenericDao<NetworkAccountVO, Long> {
}

View File

@ -22,7 +22,7 @@ import com.cloud.utils.db.GenericDao;
import com.cloud.utils.db.GenericDaoBase;
@Component
public class NetworkAccountDaoImpl extends GenericDaoBase<NetworkAccountVO, Long> implements GenericDao<NetworkAccountVO, Long> {
public class NetworkAccountDaoImpl extends GenericDaoBase<NetworkAccountVO, Long> implements NetworkAccountDao {
public NetworkAccountDaoImpl() {
super();
}

View File

@ -39,13 +39,11 @@ import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingDaoImpl;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.*;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchCriteria.Func;
@ -76,13 +74,13 @@ public class NetworkDaoImpl extends GenericDaoBase<NetworkVO, Long> implements N
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject NetworkAccountDaoImpl _accountsDao;
@Inject NetworkDomainDaoImpl _domainsDao;
@Inject NetworkOpDaoImpl _opDao;
@Inject NetworkServiceMapDaoImpl _ntwkSvcMap;
@Inject NetworkOfferingDaoImpl _ntwkOffDao;
@Inject NetworkOpDaoImpl _ntwkOpDao;
@Inject ResourceTagDao _tagsDao;
@Inject NetworkAccountDao _accountsDao;
@Inject NetworkDomainDao _domainsDao;
@Inject NetworkOpDao _opDao;
@Inject NetworkServiceMapDao _ntwkSvcMap;
@Inject NetworkOfferingDao _ntwkOffDao;
@Inject NetworkOpDao _ntwkOpDao;
TableGenerator _tgMacAddress;

View File

@ -0,0 +1,26 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.dao;
import com.cloud.utils.db.GenericDao;
public interface NetworkOpDao extends GenericDao<NetworkOpVO, Long> {
public int getActiveNics(long networkId);
public void changeActiveNicsBy(long networkId, int count);
public void setCheckForGc(long networkId);
public void clearCheckForGc(long networkId);
}

View File

@ -30,7 +30,7 @@ import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.UpdateBuilder;
@Component
public class NetworkOpDaoImpl extends GenericDaoBase<NetworkOpVO, Long> implements GenericDao<NetworkOpVO, Long> {
public class NetworkOpDaoImpl extends GenericDaoBase<NetworkOpVO, Long> implements NetworkOpDao {
protected final SearchBuilder<NetworkOpVO> AllFieldsSearch;
protected final GenericSearchBuilder<NetworkOpVO, Integer> ActiveNicsSearch;
protected final Attribute _activeNicsAttribute;

View File

@ -36,7 +36,7 @@ import com.cloud.utils.db.SearchCriteria.Op;
public class PhysicalNetworkDaoImpl extends GenericDaoBase<PhysicalNetworkVO, Long> implements PhysicalNetworkDao {
final SearchBuilder<PhysicalNetworkVO> ZoneSearch;
@Inject protected PhysicalNetworkTrafficTypeDaoImpl _trafficTypeDao;
@Inject protected PhysicalNetworkTrafficTypeDao _trafficTypeDao;
protected PhysicalNetworkDaoImpl() {
super();

View File

@ -0,0 +1,26 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.network.dao;
import java.util.List;
import com.cloud.utils.db.GenericDao;
public interface RouterNetworkDao extends GenericDao<RouterNetworkVO, Long> {
public List<Long> getRouterNetworks(long routerId);
public RouterNetworkVO findByRouterAndNetwork (long routerId, long networkId);
}

View File

@ -28,7 +28,7 @@ import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
@Component
public class RouterNetworkDaoImpl extends GenericDaoBase<RouterNetworkVO, Long> implements GenericDao<RouterNetworkVO, Long>{
public class RouterNetworkDaoImpl extends GenericDaoBase<RouterNetworkVO, Long> implements RouterNetworkDao {
protected final GenericSearchBuilder<RouterNetworkVO, Long> RouterNetworksSearch;
protected final SearchBuilder<RouterNetworkVO> AllFieldsSearch;

View File

@ -35,8 +35,8 @@ import com.cloud.utils.db.SearchCriteria;
public class Site2SiteVpnConnectionDaoImpl extends GenericDaoBase<Site2SiteVpnConnectionVO, Long> implements Site2SiteVpnConnectionDao {
private static final Logger s_logger = Logger.getLogger(Site2SiteVpnConnectionDaoImpl.class);
@Inject protected IPAddressDaoImpl _addrDao;
@Inject protected Site2SiteVpnGatewayDaoImpl _vpnGatewayDao;
@Inject protected IPAddressDao _addrDao;
@Inject protected Site2SiteVpnGatewayDao _vpnGatewayDao;
private SearchBuilder<Site2SiteVpnConnectionVO> AllFieldsSearch;
private SearchBuilder<Site2SiteVpnConnectionVO> VpcSearch;

View File

@ -29,7 +29,7 @@ import com.cloud.utils.db.SearchCriteria;
@Component
@Local(value={Site2SiteVpnGatewayDao.class})
public class Site2SiteVpnGatewayDaoImpl extends GenericDaoBase<Site2SiteVpnGatewayVO, Long> implements Site2SiteVpnGatewayDao {
@Inject protected IPAddressDaoImpl _addrDao;
@Inject protected IPAddressDao _addrDao;
private static final Logger s_logger = Logger.getLogger(Site2SiteVpnGatewayDaoImpl.class);

View File

@ -23,6 +23,7 @@ import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.cloud.network.dao.FirewallRulesCidrsDao;
import com.cloud.network.dao.FirewallRulesCidrsDaoImpl;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRule.State;
@ -44,7 +45,7 @@ public class PortForwardingRulesDaoImpl extends GenericDaoBase<PortForwardingRul
protected final SearchBuilder<PortForwardingRuleVO> AllRulesSearchByVM;
protected final SearchBuilder<PortForwardingRuleVO> ActiveRulesSearchByAccount;
@Inject protected FirewallRulesCidrsDaoImpl _portForwardingRulesCidrsDao;
@Inject protected FirewallRulesCidrsDao _portForwardingRulesCidrsDao;
protected PortForwardingRulesDaoImpl() {
super();

View File

@ -25,6 +25,7 @@ import org.springframework.stereotype.Component;
import com.cloud.network.security.SecurityGroupVO;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
@ -39,7 +40,7 @@ public class SecurityGroupDaoImpl extends GenericDaoBase<SecurityGroupVO, Long>
private SearchBuilder<SecurityGroupVO> AccountIdSearch;
private SearchBuilder<SecurityGroupVO> AccountIdNameSearch;
private SearchBuilder<SecurityGroupVO> AccountIdNamesSearch;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
protected SecurityGroupDaoImpl() {

View File

@ -26,6 +26,7 @@ import org.springframework.stereotype.Component;
import com.cloud.network.vpc.StaticRoute;
import com.cloud.network.vpc.StaticRouteVO;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
@ -44,7 +45,7 @@ public class StaticRouteDaoImpl extends GenericDaoBase<StaticRouteVO, Long> impl
protected final SearchBuilder<StaticRouteVO> AllFieldsSearch;
protected final SearchBuilder<StaticRouteVO> NotRevokedSearch;
protected final GenericSearchBuilder<StaticRouteVO, Long> RoutesByGatewayCount;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
protected StaticRouteDaoImpl() {
super();

View File

@ -29,7 +29,7 @@ import org.springframework.stereotype.Component;
import com.cloud.network.vpc.Vpc;
import com.cloud.network.vpc.VpcVO;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
@ -47,8 +47,9 @@ public class VpcDaoImpl extends GenericDaoBase<VpcVO, Long> implements VpcDao{
final GenericSearchBuilder<VpcVO, Integer> CountByOfferingId;
final SearchBuilder<VpcVO> AllFieldsSearch;
final GenericSearchBuilder<VpcVO, Long> CountByAccountId;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject VpcServiceMapDaoImpl _vpcSvcMap;
@Inject ResourceTagDao _tagsDao;
@Inject VpcServiceMapDao _vpcSvcMap;
protected VpcDaoImpl() {
super();

View File

@ -27,6 +27,7 @@ import org.springframework.stereotype.Component;
import com.cloud.projects.Project;
import com.cloud.projects.ProjectVO;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.db.DB;
@ -45,7 +46,7 @@ public class ProjectDaoImpl extends GenericDaoBase<ProjectVO, Long> implements P
protected GenericSearchBuilder<ProjectVO, Long> CountByDomain;
protected GenericSearchBuilder<ProjectVO, Long> ProjectAccountSearch;
// ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
protected ProjectDaoImpl() {
AllFieldsSearch = createSearchBuilder();

View File

@ -16,6 +16,9 @@
// under the License.
package com.cloud.servlet;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@ -31,10 +34,22 @@ public class CloudStartupServlet extends HttpServlet {
public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName());
static final long serialVersionUID = SerialVersionUID.CloudStartupServlet;
Timer _timer = new Timer();
@Override
public void init(ServletConfig config) throws ServletException {
LogUtils.initLog4j("log4j-cloud.xml");
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
ComponentContext.initComponentsLifeCycle();
// wait when condition is ready for initialization
_timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(ComponentContext.getApplicationContext() != null) {
_timer.cancel();
ComponentContext.initComponentsLifeCycle();
}
}
}, 0, 1000);
}
}

View File

@ -35,16 +35,14 @@ import com.cloud.storage.Snapshot.Type;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
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.*;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.dao.VMInstanceDaoImpl;
@Component
@ -66,10 +64,10 @@ public class SnapshotDaoImpl extends GenericDaoBase<SnapshotVO, Long> implements
private SearchBuilder<SnapshotVO> InstanceIdSearch;
private SearchBuilder<SnapshotVO> StatusSearch;
private GenericSearchBuilder<SnapshotVO, Long> CountSnapshotsByAccount;
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
@Inject protected VMInstanceDaoImpl _instanceDao;
@Inject protected VolumeDaoImpl _volumeDao;
@Inject protected VMInstanceDao _instanceDao;
@Inject protected VolumeDao _volumeDao;
@Override
public SnapshotVO findNextSnapshot(long snapshotId) {

View File

@ -37,6 +37,7 @@ import com.cloud.storage.Volume.Event;
import com.cloud.storage.Volume.State;
import com.cloud.storage.Volume.Type;
import com.cloud.storage.VolumeVO;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.utils.Pair;
import com.cloud.utils.db.DB;
@ -61,8 +62,7 @@ public class VolumeDaoImpl extends GenericDaoBase<VolumeVO, Long> implements Vol
protected final SearchBuilder<VolumeVO> InstanceStatesSearch;
protected final SearchBuilder<VolumeVO> AllFieldsSearch;
protected GenericSearchBuilder<VolumeVO, Long> CountByAccount;
// ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
protected static final String SELECT_VM_SQL = "SELECT DISTINCT instance_id from volumes v where v.host_id = ? and v.mirror_state = ?";
protected static final String SELECT_HYPERTYPE_FROM_VOLUME = "SELECT c.hypervisor_type from volumes v, storage_pool s, cluster c where v.pool_id = s.id and s.cluster_id = c.id and v.id = ?";

View File

@ -25,15 +25,19 @@ import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDaoImpl;
import com.cloud.network.Network;
import com.cloud.network.dao.RouterNetworkDao;
import com.cloud.network.dao.RouterNetworkDaoImpl;
import com.cloud.network.dao.RouterNetworkVO;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.Role;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingDaoImpl;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.user.dao.UserStatisticsDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.GenericDaoBase;
@ -57,10 +61,10 @@ public class DomainRouterDaoImpl extends GenericDaoBase<DomainRouterVO, Long> im
protected SearchBuilder<DomainRouterVO> HostUpSearch;
protected SearchBuilder<DomainRouterVO> StateNetworkTypeSearch;
protected SearchBuilder<DomainRouterVO> OutsidePodSearch;
@Inject HostDaoImpl _hostsDao;
@Inject RouterNetworkDaoImpl _routerNetworkDao;
@Inject UserStatisticsDaoImpl _userStatsDao;
@Inject NetworkOfferingDaoImpl _offDao;
@Inject HostDao _hostsDao;
@Inject RouterNetworkDao _routerNetworkDao;
@Inject UserStatisticsDao _userStatsDao;
@Inject NetworkOfferingDao _offDao;
protected SearchBuilder<DomainRouterVO> VpcSearch;
public DomainRouterDaoImpl() {

View File

@ -35,6 +35,7 @@ import org.springframework.stereotype.Component;
import com.cloud.configuration.Resource;
import com.cloud.server.ResourceTag.TaggedResourceType;
import com.cloud.tags.dao.ResourceTagDao;
import com.cloud.tags.dao.ResourceTagsDaoImpl;
import com.cloud.user.Account;
@ -79,7 +80,7 @@ public class UserVmDaoImpl extends GenericDaoBase<UserVmVO, Long> implements Use
protected SearchBuilder<UserVmVO> UserVmByIsoSearch;
protected Attribute _updateTimeAttr;
// ResourceTagsDaoImpl _tagsDao = ComponentLocator.inject(ResourceTagsDaoImpl.class);
@Inject ResourceTagsDaoImpl _tagsDao;
@Inject ResourceTagDao _tagsDao;
private static final String LIST_PODS_HAVING_VMS_FOR_ACCOUNT = "SELECT pod_id FROM cloud.vm_instance WHERE data_center_id = ? AND account_id = ? AND pod_id IS NOT NULL AND (state = 'Running' OR state = 'Stopped') " +
"GROUP BY pod_id HAVING count(id) > 0 ORDER BY count(id) DESC";

View File

@ -188,4 +188,10 @@ public class MockAgentManagerImpl extends ManagerBase implements AgentManager {
return null;
}
@Override
public void disconnectWithInvestigation(long hostId, Event event) {
// TODO Auto-generated method stub
}
}

View File

@ -55,8 +55,18 @@ public class ComponentContext implements ApplicationContextAware {
private static ApplicationContext s_appContext;
private static Advisor s_advisor;
private static ProxyFactory s_pf;
static {
s_advisor = new DefaultPointcutAdvisor(new MatchAnyMethodPointcut(),
new TransactionContextBuilder());
s_pf = new ProxyFactory();
s_pf.addAdvisor(s_advisor);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
public void setApplicationContext(ApplicationContext applicationContext) {
s_logger.info("Setup Spring Application context");
s_appContext = applicationContext;
}
@ -157,27 +167,24 @@ public class ComponentContext implements ApplicationContextAware {
public static <T> T getComponent(Class<T> beanType) {
assert(s_appContext != null);
try {
return s_appContext.getBean(beanType);
} catch(NoSuchBeanDefinitionException e) {
Map<String, T> matchedTypes = getComponentsOfType(beanType);
if(matchedTypes.size() > 0) {
for(Map.Entry<String, T> entry : matchedTypes.entrySet()) {
Primary primary = getTargetClass(entry.getValue()).getAnnotation(Primary.class);
if(primary != null)
return entry.getValue();
}
if(matchedTypes.size() > 1) {
s_logger.warn("Unable to uniquely locate bean type " + beanType.getName());
for(Map.Entry<String, T> entry : matchedTypes.entrySet()) {
s_logger.warn("Candidate " + getTargetClass(entry.getValue()).getName());
}
}
return (T)matchedTypes.values().toArray()[0];
Map<String, T> matchedTypes = getComponentsOfType(beanType);
if(matchedTypes.size() > 0) {
for(Map.Entry<String, T> entry : matchedTypes.entrySet()) {
Primary primary = getTargetClass(entry.getValue()).getAnnotation(Primary.class);
if(primary != null)
return entry.getValue();
}
if(matchedTypes.size() > 1) {
s_logger.warn("Unable to uniquely locate bean type " + beanType.getName());
for(Map.Entry<String, T> entry : matchedTypes.entrySet()) {
s_logger.warn("Candidate " + getTargetClass(entry.getValue()).getName());
}
}
return (T)matchedTypes.values().toArray()[0];
}
throw new NoSuchBeanDefinitionException(beanType.getName());
}
@ -208,24 +215,19 @@ public class ComponentContext implements ApplicationContextAware {
return (T)instance;
}
@SuppressWarnings("unchecked")
public static <T> T inject(Class<T> clz) {
Object instance = s_appContext.getAutowireCapableBeanFactory().createBean(clz);
return (T)inject(instance);
public static <T> T inject(Class<T> clz) {
T instance = s_appContext.getAutowireCapableBeanFactory().createBean(clz);
return instance;
}
public static <T> T inject(Object instance) {
// autowire dynamically loaded object
AutowireCapableBeanFactory beanFactory = s_appContext.getAutowireCapableBeanFactory();
beanFactory.autowireBean(instance);
Advisor advisor = new DefaultPointcutAdvisor(new MatchAnyMethodPointcut(),
new TransactionContextBuilder());
ProxyFactory pf = new ProxyFactory();
pf.setTarget(instance);
pf.addAdvisor(advisor);
return (T)pf.getProxy();
return (T)instance;
/*
s_pf.setTarget(instance);
return (T)s_pf.getProxy();
*/
}
}

View File

@ -277,4 +277,6 @@ public interface GenericDao<T, ID extends Serializable> {
* @return
*/
Pair<List<T>, Integer> searchAndCount(SearchCriteria<T> sc, Filter filter);
Map<String, Attribute> getAllAttributes();
}

View File

@ -68,6 +68,7 @@ import com.cloud.utils.DateUtil;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.component.ComponentLifecycle;
import com.cloud.utils.component.ComponentLifecycleBase;
import com.cloud.utils.crypt.DBEncryptionUtil;
@ -118,7 +119,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
protected final static TimeZone s_gmtTimeZone = TimeZone.getTimeZone("GMT");
protected final static Map<Class<?>, GenericDaoBase<?, ? extends Serializable>> s_daoMaps = new ConcurrentHashMap<Class<?>, GenericDaoBase<?, ? extends Serializable>>(71);
protected final static Map<Class<?>, GenericDao<?, ? extends Serializable>> s_daoMaps = new ConcurrentHashMap<Class<?>, GenericDao<?, ? extends Serializable>>(71);
protected Class<T> _entityBeanType;
protected String _table;
@ -128,8 +129,8 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
protected Field[] _embeddedFields;
// This is private on purpose. Everyone should use createPartialSelectSql()
private final Pair<StringBuilder, Attribute[]> _partialSelectSql;
private final Pair<StringBuilder, Attribute[]> _partialQueryCacheSelectSql;
private Pair<StringBuilder, Attribute[]> _partialSelectSql;
private Pair<StringBuilder, Attribute[]> _partialQueryCacheSelectSql;
protected StringBuilder _discriminatorClause;
protected Map<String, Object> _discriminatorValues;
protected String _selectByIdSql;
@ -141,11 +142,11 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
protected Pair<String, Attribute> _removed;
protected Pair<String, Attribute[]> _removeSql;
protected List<Pair<String, Attribute[]>> _deleteSqls;
protected final Map<String, Attribute[]> _idAttributes;
protected final Map<String, TableGenerator> _tgs;
protected final Map<String, Attribute> _allAttributes;
protected final List<Attribute> _ecAttributes;
protected final Map<Pair<String, String>, Attribute> _allColumns;
protected Map<String, Attribute[]> _idAttributes;
protected Map<String, TableGenerator> _tgs;
protected Map<String, Attribute> _allAttributes;
protected List<Attribute> _ecAttributes;
protected Map<Pair<String, String>, Attribute> _allColumns;
protected Enhancer _enhancer;
protected Factory _factory;
protected Enhancer _searchEnhancer;
@ -159,9 +160,9 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
protected static final SequenceFetcher s_seqFetcher = SequenceFetcher.getInstance();
public static <J> GenericDaoBase<? extends J, ? extends Serializable> getDao(Class<J> entityType) {
public static <J> GenericDao<? extends J, ? extends Serializable> getDao(Class<J> entityType) {
@SuppressWarnings("unchecked")
GenericDaoBase<? extends J, ? extends Serializable> dao = (GenericDaoBase<? extends J, ? extends Serializable>)s_daoMaps.get(entityType);
GenericDao<? extends J, ? extends Serializable> dao = (GenericDao<? extends J, ? extends Serializable>)s_daoMaps.get(entityType);
assert dao != null : "Unable to find DAO for " + entityType + ". Are you sure you waited for the DAO to be initialized before asking for it?";
return dao;
}
@ -192,13 +193,15 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
( (Class<?>)((Class<?>)t).getGenericSuperclass()).getGenericSuperclass()).getActualTypeArguments()[0];
}
s_daoMaps.put(_entityBeanType, this);
/*
s_daoMaps.put(_entityBeanType, ComponentContext.getComponent(this.getClass()));
Class<?>[] interphaces = _entityBeanType.getInterfaces();
if (interphaces != null) {
for (Class<?> interphace : interphaces) {
s_daoMaps.put(interphace, this);
s_daoMaps.put(interphace, ComponentContext.getComponent(this.getClass()));
}
}
*/
_table = DbUtil.getTableName(_entityBeanType);
final SqlGenerator generator = new SqlGenerator(_entityBeanType);
@ -1747,6 +1750,25 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
Class<?> daoInterface = null;
for(Class<?> intf : this.getClass().getInterfaces()) {
if(GenericDao.class.isAssignableFrom(intf)) {
daoInterface = intf;
break;
}
}
if(daoInterface != null) {
s_logger.info("Register dao interface in GenericDaoBase entity-DAO map. " + daoInterface.getName());
s_daoMaps.put(_entityBeanType, (GenericDao<?, ? extends Serializable>) ComponentContext.getComponent(daoInterface));
Class<?>[] interphaces = _entityBeanType.getInterfaces();
if (interphaces != null) {
for (Class<?> interphace : interphaces) {
s_daoMaps.put(interphace, (GenericDao<?, ? extends Serializable>) ComponentContext.getComponent(daoInterface));
}
}
}
final String value = (String)params.get("lock.timeout");
_timeoutSeconds = NumbersUtil.parseInt(value, 300);

View File

@ -56,21 +56,21 @@ public class QueryBuilder<S, T> implements MethodInterceptor, SimpleQueryBuilder
}
}
protected HashMap<Class<?>, Pair<GenericDaoBase<?,?>, Object>> _entities;
protected HashMap<Class<?>, Pair<GenericDao<?,?>, Object>> _entities;
protected ArrayList<Attribute> _specifiedAttrs = new ArrayList<Attribute>();
protected T _resultSetClass;
protected ArrayList<Select<S, T>> _selects;
public QueryBuilder(Class<T> resultSetClass, Class<?>... clazzes) {
_entities = new HashMap<Class<?>, Pair<GenericDaoBase<?,?>, Object>>(clazzes.length);
_entities = new HashMap<Class<?>, Pair<GenericDao<?,?>, Object>>(clazzes.length);
for (Class<?> clazz : clazzes) {
GenericDaoBase<?,?> dao = GenericDaoBase.getDao(clazz);
GenericDao<?,?> dao = GenericDaoBase.getDao(clazz);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(clazz);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(clazz, new Pair<GenericDaoBase<?, ?>, Object>(dao, entity));
_entities.put(clazz, new Pair<GenericDao<?, ?>, Object>(dao, entity));
}
}
@ -86,14 +86,14 @@ public class QueryBuilder<S, T> implements MethodInterceptor, SimpleQueryBuilder
* @param resultSetClass result class to put the result set in.
*/
public QueryBuilder(Class<S> entityClass, Class<T> resultSetClass) {
_entities = new HashMap<Class<?>, Pair<GenericDaoBase<?,?>, Object>>(1);
GenericDaoBase<?,?> dao = GenericDaoBase.getDao(entityClass);
_entities = new HashMap<Class<?>, Pair<GenericDao<?,?>, Object>>(1);
GenericDao<?,?> dao = GenericDaoBase.getDao(entityClass);
Enhancer searchEnhancer = new Enhancer();
searchEnhancer.setSuperclass(entityClass);
searchEnhancer.setCallback(this);
Object entity = searchEnhancer.create();
_entities.put(entityClass, new Pair<GenericDaoBase<?, ?>, Object>(dao, entity));
_entities.put(entityClass, new Pair<GenericDao<?, ?>, Object>(dao, entity));
}
@Override
@ -114,7 +114,7 @@ public class QueryBuilder<S, T> implements MethodInterceptor, SimpleQueryBuilder
return this;
}
protected void set(GenericDaoBase<?, ?> dao , String name) {
protected void set(GenericDao<?, ?> dao , String name) {
Attribute attr = dao.getAllAttributes().get(name);
assert (attr != null) : "Searching for a field that's not there: " + name;
_specifiedAttrs.add(attr);
@ -125,9 +125,9 @@ public class QueryBuilder<S, T> implements MethodInterceptor, SimpleQueryBuilder
public Object intercept(Object entity, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Class<?> entityClass = entity.getClass().getSuperclass();
Pair<GenericDaoBase<?,?>, Object> daoInfo = _entities.get(entityClass);
Pair<GenericDao<?,?>, Object> daoInfo = _entities.get(entityClass);
assert (daoInfo != null) : "You need to specify " + entityClass + " as one of the entities in the Query";
GenericDaoBase<?,?> dao = daoInfo.first();
GenericDao<?,?> dao = daoInfo.first();
String name = method.getName();
if (name.startsWith("get")) {

View File

@ -33,16 +33,8 @@ public class TransactionContextBuilder implements MethodInterceptor {
public Object AroundAnyMethod(ProceedingJoinPoint call) throws Throwable {
MethodSignature methodSignature = (MethodSignature)call.getSignature();
Method targetMethod = methodSignature.getMethod();
if(needToIntercept(targetMethod)) {
Transaction txn = null;
try {
Signature s = call.getSignature();
String name = s.getName();
txn = Transaction.open(name);
} catch (Throwable e) {
s_logger.debug("Failed to open transaction: " + e.toString());
throw e;
}
if(true) { // TODO ??? needToIntercept(targetMethod)) {
Transaction txn = Transaction.open(call.getSignature().getName());
Object ret = null;
try {
ret = call.proceed();