bug 5764: changing from networkoffering to network profile

This commit is contained in:
Alex Huang 2010-08-24 00:00:43 -07:00
parent e91617bc6f
commit 20b26082db
22 changed files with 303 additions and 72 deletions

View File

@ -3,6 +3,8 @@
*/
package com.cloud.acl;
import java.security.acl.NotOwnerException;
import com.cloud.domain.PartOf;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.user.Account;
@ -23,7 +25,7 @@ public interface SecurityChecker extends Adapter {
* @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkOwnership(Account account, OwnedBy object) throws PermissionDeniedException;
boolean checkOwnership(Account account, OwnedBy object) throws NotOwnerException;
/**
* Checks if the user belongs to an account that owns the object.
@ -33,7 +35,7 @@ public interface SecurityChecker extends Adapter {
* @return true if access allowed. false if this adapter cannot authenticate ownership.
* @throws PermissionDeniedException if this adapter is suppose to authenticate ownership and the check failed.
*/
boolean checkOwnership(User user, OwnedBy object) throws PermissionDeniedException;
boolean checkOwnership(User user, OwnedBy object) throws NotOwnerException;
/**
* Checks if the account can access the object.

View File

@ -0,0 +1,16 @@
/**
*
*/
package com.cloud.exception;
import com.cloud.utils.SerialVersionUID;
public class ConflictingNetworkSettingsException extends Exception {
private static final long serialVersionUID = SerialVersionUID.ConflictingNetworkSettingException;
public ConflictingNetworkSettingsException() {
super();
}
}

View File

@ -0,0 +1,26 @@
/**
*
*/
package com.cloud.network;
import com.cloud.network.Network.BroadcastDomainType;
import com.cloud.network.Network.Mode;
import com.cloud.network.Network.TrafficType;
import com.cloud.user.OwnedBy;
public interface NetworkProfile extends OwnedBy {
long getId();
Mode getMode();
BroadcastDomainType getBroadcastDomainType();
TrafficType getTrafficType();
String getGateway();
String getCidr();
void setCidr(String cidr);
}

View File

@ -0,0 +1,25 @@
/**
*
*/
package com.cloud.network;
import java.util.Collection;
import java.util.List;
import com.cloud.exception.ConflictingNetworkSettingsException;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.utils.component.Adapter;
import com.cloud.vm.VirtualMachine;
/**
* NetworkProfiler takes the list of network offerings requested and figures
* out what are the additional network profiles that are needed to add
* to the account in order to support this network.
*
*/
public interface NetworkProfiler extends Adapter {
List<? extends NetworkProfile> convert(Collection<? extends NetworkOffering> networkOfferings, Account owner);
boolean check(VirtualMachine vm, ServiceOffering serviceOffering, Collection<? extends NetworkProfile> networkProfiles) throws ConflictingNetworkSettingsException;
}

View File

@ -1,18 +0,0 @@
/**
*
*/
package com.cloud.vm;
import java.util.Collection;
import java.util.List;
import com.cloud.offering.DiskOffering;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Adapter;
public interface NetworkProfiler extends Adapter {
Ternary<VmCharacteristics, List<NetworkCharacteristics>, List<DiskCharacteristics>> convert(VirtualMachine vm, ServiceOffering serviceOffering, List<NetworkOffering> networkOfferings, Collection<DiskOffering> diskOfferings, Account owner);
}

View File

@ -35,6 +35,11 @@ import com.cloud.utils.db.GenericDao;
@Entity
@Table(name="network_offerings")
public class NetworkOfferingVO implements NetworkOffering {
public final static String SystemVmPublicNetwork = "System-Vm-Public-Network";
public final static String SystemVmGuestNetwork = "System-Vm-Guest-Network";
public final static String SystemVmLinkLocalNetwork = "System-Vm-LinkLocal-Network";
public final static String SystemVmManagementNetwork = "System-Vm-Management-Network";
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
@ -46,10 +51,10 @@ public class NetworkOfferingVO implements NetworkOffering {
@Column(name="display_text")
String displayText;
@Column(name="rate")
@Column(name="nw_rate")
Integer rateMbps;
@Column(name="multicast_rate")
@Column(name="mc_rate")
Integer multicastRateMbps;
@Column(name="concurrent_connections")

View File

@ -93,7 +93,15 @@ public class ConsoleProxyVO extends VMInstanceVO implements ConsoleProxy {
@Transient
private int port;
/**
* Correct constructor to use.
*/
public ConsoleProxyVO(long id, String name, long templateId, long guestOSId, long dataCenterId, int activeSession) {
super(id, name, name, Type.ConsoleProxy, templateId, guestOSId, false);
this.activeSession = activeSession;
}
public ConsoleProxyVO(
long id,
String name,

View File

@ -22,6 +22,7 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
@ -96,9 +97,11 @@ import com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo;
import com.cloud.maid.StackMaid;
import com.cloud.network.IpAddrAllocator;
import com.cloud.network.IpAddrAllocator.networkInfo;
import com.cloud.network.NetworkProfileVO;
import com.cloud.network.Network.TrafficType;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.StorageManager;
@ -111,6 +114,7 @@ import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
@ -219,16 +223,23 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
private StorageManager _storageMgr;
@Inject
private HighAvailabilityManager _haMgr;
@Inject AccountManager _accountMgr;
@Inject
private EventDao _eventDao;
@Inject
ServiceOfferingDao _offeringDao;
@Inject
NetworkOfferingDao _networkOfferingDao;
private IpAddrAllocator _IpAllocator;
private ConsoleProxyListener _listener;
private ServiceOfferingVO _serviceOffering;
private VMTemplateVO _template;
NetworkOfferingVO _publicNetworkOffering;
NetworkOfferingVO _managementNetworkOffering;
NetworkOfferingVO _linkLocalNetworkOffering;
@Inject
private AsyncJobManager _asyncMgr;
@ -252,10 +263,6 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
private String _domain;
private String _instance;
private NetworkProfileVO _publicNetworkProfile;
private NetworkProfileVO _managementNetworkProfile;
private NetworkProfileVO _controlNetworkProfile;
// private String _privateNetmask;
private int _proxyCmdPort = DEFAULT_PROXY_CMD_PORT;
@ -1000,11 +1007,21 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
@DB
protected Map<String, Object> createProxyInstance2(long dataCenterId) {
long id = _consoleProxyDao.getNextInSequence(Long.class, "id");
String name = VirtualMachineName.getConsoleProxyName(id, _instance);
ConsoleProxyVO proxy = new ConsoleProxyVO(id, name, _template.getId(), _template.getGuestOSId(), dataCenterId, 0);
proxy = _consoleProxyDao.persist(proxy);
ArrayList<NetworkOfferingVO> networkOfferings = new ArrayList<NetworkOfferingVO>(3);
networkOfferings.add(_managementNetworkOffering);
networkOfferings.add(_linkLocalNetworkOffering);
networkOfferings.add(_publicNetworkOffering);
_vmMgr.allocate(proxy, _serviceOffering, null, networkOfferings, null, null, null, _accountMgr.getSystemAccount());
Map<String, Object> context = new HashMap<String, Object>();
String publicIpAddress = null;
return null;
/*
Transaction txn = Transaction.currentTxn();
try {
DataCenterVO dc = _dcDao.findById(dataCenterId);
@ -1044,7 +1061,6 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
context.put("proxyVmId", (long) 0);
return context;
}
long id = _consoleProxyDao.getNextInSequence(Long.class, "id");
context.put("publicIpAddress", publicIpAndVlan._ipAddr);
@ -1090,7 +1106,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
context.put("proxyVmId", (long) 0);
return context;
}
}*/
}
@DB
@ -2337,6 +2353,13 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
throw new ConfigurationException("Unable to find the template for console proxy VMs");
}
_publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmPublicNetwork, TrafficType.Public, null);
_publicNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_publicNetworkOffering);
_managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmManagementNetwork, TrafficType.Management, null);
_managementNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_managementNetworkOffering);
_linkLocalNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmLinkLocalNetwork, TrafficType.LinkLocal, null);
_linkLocalNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_linkLocalNetworkOffering);
_capacityScanScheduler.scheduleAtFixedRate(getCapacityScanTask(), STARTUP_DELAY, _capacityScanInterval, TimeUnit.MILLISECONDS);
if (s_logger.isInfoEnabled())

View File

@ -129,6 +129,7 @@ import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory;
@ -192,6 +193,8 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
@Inject ServiceOfferingDao _serviceOfferingDao = null;
@Inject UserStatisticsDao _statsDao = null;
@Inject NetworkOfferingDao _networkOfferingDao = null;
Adapters<NetworkProfiler> _networkProfilers;
long _routerTemplateId = -1;
int _routerRamSize;
@ -1776,6 +1779,8 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
_executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RouterMonitor"));
final ComponentLocator locator = ComponentLocator.getCurrentLocator();
_networkProfilers = locator.getAdapters(NetworkProfiler.class);
final Map<String, String> configs = _configDao.getConfiguration("AgentManager", params);
_routerTemplateId = NumbersUtil.parseInt(configs.get("router.template.id"), 1);
@ -1826,14 +1831,19 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
throw new ConfigurationException("Unable to find the template for the router: " + _routerTemplateId);
}
_publicNetworkOffering = new NetworkOfferingVO("System-VM-Public-Network", TrafficType.Public, null);
_publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmPublicNetwork, TrafficType.Public, null);
_publicNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_publicNetworkOffering);
_managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmManagementNetwork, TrafficType.Management, null);
_managementNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_managementNetworkOffering);
_linkLocalNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmLinkLocalNetwork, TrafficType.LinkLocal, null);
_linkLocalNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_linkLocalNetworkOffering);
_guestNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemVmGuestNetwork, TrafficType.Guest, GuestIpType.Virtualized);
_guestNetworkOffering = _networkOfferingDao.persistSystemNetworkOffering(_guestNetworkOffering);
_managementNetworkOffering = new NetworkOfferingVO("System-VM-Management-Network", TrafficType.Management, null);
_linkLocalNetworkOffering = new NetworkOfferingVO("System-VM-LinkLocal-Network", TrafficType.LinkLocal, null);
_guestNetworkOffering = new NetworkOfferingVO("System-VM-Guest-Network", TrafficType.Guest, GuestIpType.Virtualized);
// FIXME: Obviously Virtualized is not the only guest network. How do we determine which one to use?
s_logger.info("Network Manager is configured.");
return true;
@ -1846,6 +1856,15 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
@Override
public boolean start() {
List<NetworkOfferingVO> offerings = new ArrayList<NetworkOfferingVO>(4);
offerings.add(_publicNetworkOffering);
offerings.add(_guestNetworkOffering);
offerings.add(_linkLocalNetworkOffering);
offerings.add(_managementNetworkOffering);
for (NetworkProfiler profiler : _networkProfilers) {
List<? extends NetworkProfile> profiles = profiler.convert(offerings, _accountMgr.getSystemAccount());
}
_executor.scheduleAtFixedRate(new RouterCleanupTask(), _routerCleanupInterval, _routerCleanupInterval, TimeUnit.SECONDS);
_executor.scheduleAtFixedRate(new NetworkUsageTask(), _routerStatsInterval, _routerStatsInterval, TimeUnit.SECONDS);
return true;

View File

@ -57,6 +57,9 @@ public class NetworkProfileVO implements OwnedBy {
@Enumerated(value=EnumType.STRING)
TrafficType trafficType;
@Column(name="vlanIds")
String vlanIds;
@Column(name="gateway")
String gateway;
@ -125,4 +128,5 @@ public class NetworkProfileVO implements OwnedBy {
public void setCidr(String cidr) {
this.cidr = cidr;
}
}

View File

@ -0,0 +1,41 @@
/**
*
*/
package com.cloud.network;
import java.util.Collection;
import java.util.List;
import javax.ejb.Local;
import com.cloud.exception.ConflictingNetworkSettingsException;
import com.cloud.network.dao.NetworkProfileDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.ServiceOffering;
import com.cloud.user.Account;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.vm.VirtualMachine;
@Local(value=NetworkProfiler.class)
public class NetworkProfilerImpl extends AdapterBase implements NetworkProfiler {
@Inject protected NetworkProfileDao _profileDao;
protected NetworkProfilerImpl() {
super();
}
@Override
public List<? extends NetworkProfile> convert(Collection<? extends NetworkOffering> networkOfferings, Account owner) {
for (NetworkOffering offering : networkOfferings) {
}
return null;
}
@Override
public boolean check(VirtualMachine vm, ServiceOffering serviceOffering, Collection<? extends NetworkProfile> networkProfiles) throws ConflictingNetworkSettingsException {
// TODO Auto-generated method stub
return false;
}
}

View File

@ -19,11 +19,29 @@ package com.cloud.network.dao;
import javax.ejb.Local;
import com.cloud.network.Network.Mode;
import com.cloud.network.Network.TrafficType;
import com.cloud.network.NetworkProfileVO;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Local(value=NetworkProfileDao.class)
public class NetworkProfileDaoImpl extends GenericDaoBase<NetworkProfileVO, Long> {
public class NetworkProfileDaoImpl extends GenericDaoBase<NetworkProfileVO, Long> implements NetworkProfileDao {
final SearchBuilder<NetworkProfileVO> ProfileSearch;
protected NetworkProfileDaoImpl() {
super();
ProfileSearch = createSearchBuilder();
ProfileSearch.and("account", ProfileSearch.entity().getAccountId(), SearchCriteria.Op.EQ);
ProfileSearch.and("trafficType", ProfileSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
ProfileSearch.and("cidr", ProfileSearch.entity().getCidr(), SearchCriteria.Op.EQ);
ProfileSearch.and("broadcastType", ProfileSearch.entity().getBroadcastDomainType(), SearchCriteria.Op.EQ);
}
public NetworkProfileVO findBy(TrafficType trafficType, Mode mode, long accountId) {
return null;
}
}

View File

@ -12,7 +12,7 @@ import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Local(value=NetworkOfferingDao.class)
public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Long> {
public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Long> implements NetworkOfferingDao {
SearchBuilder<NetworkOfferingVO> NameSearch;
protected NetworkOfferingDaoImpl() {
@ -23,6 +23,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
NameSearch.done();
}
@Override
public NetworkOfferingVO findByName(String name) {
SearchCriteria<NetworkOfferingVO> sc = NameSearch.create();
@ -32,6 +33,7 @@ public class NetworkOfferingDaoImpl extends GenericDaoBase<NetworkOfferingVO, Lo
}
@Override
public NetworkOfferingVO persistSystemNetworkOffering(NetworkOfferingVO offering) {
assert offering.getName() != null : "how are you going to find this later if you don't set it?";
NetworkOfferingVO vo = findByName(offering.getName());

View File

@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import com.cloud.dc.DataCenterVO;
import com.cloud.network.NetworkManager;
@ -33,9 +34,11 @@ import com.cloud.utils.component.Inject;
@Local(value=VmManager.class)
public class MauriceMoss implements VmManager {
String _name;
@Inject private StorageManager _storageMgr;
@Inject private NetworkManager _networkMgr;
@Override
public VMInstanceVO allocate(VMInstanceVO vm,
ServiceOfferingVO serviceOffering,
Long rootSize,
@ -46,6 +49,7 @@ public class MauriceMoss implements VmManager {
return null;
}
@Override
public VMInstanceVO allocate(VMInstanceVO vm,
ServiceOfferingVO serviceOffering,
Long rootSize,
@ -70,16 +74,27 @@ public class MauriceMoss implements VmManager {
}
@Override
public void start() {
// TODO Auto-generated method stub
public boolean start() {
return true;
}
@Override
public void stop() {
// TODO Auto-generated method stub
public boolean stop() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public String getName() {
return _name;
}
protected MauriceMoss() {
}
}

View File

@ -25,11 +25,12 @@ import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.user.AccountVO;
import com.cloud.utils.component.Manager;
/**
* Manages allocating resources to vms.
*/
public interface VmManager {
public interface VmManager extends Manager {
VMInstanceVO allocate(VMInstanceVO vm,
ServiceOfferingVO serviceOffering,
@ -51,10 +52,6 @@ public interface VmManager {
void create(VmCharacteristics vm, List<DiskCharacteristics> disks, List<NetworkCharacteristics> networks);
void start();
void stop();
void destroy();
}

View File

@ -122,7 +122,7 @@ CREATE TABLE `cloud`.`network_offerings` (
`concurrent_connections` int(10) unsigned COMMENT 'concurrent connections supported on this network',
`traffic_type` varchar(32) NOT NULL COMMENT 'traffic type carried on this network',
`created` datetime NOT NULL COMMENT 'time the entry was created',
`removed` datetime NOT NULL COMMENT 'time the entry was removed',
`removed` datetime DEFAULT NULL COMMENT 'time the entry was removed',
`system_only` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering for system use only',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -26,7 +26,7 @@ import java.util.Iterator;
*
* Why the heck didn't Iterator extend from Enumeration, I will probably never know. Tell me Lee Boyton!
**/
public class EnumerationImpl<T> implements Enumeration<T> {
public class EnumerationImpl<T> implements Enumeration<T>, Iterator<T> {
Iterator<T> _it;
// Can't use this.
@ -37,11 +37,28 @@ public class EnumerationImpl<T> implements Enumeration<T> {
_it = it;
}
@Override
public boolean hasMoreElements() {
return _it.hasNext();
}
@Override
public T nextElement() {
return _it.next();
}
@Override
public boolean hasNext() {
return _it.hasNext();
}
@Override
public T next() {
return _it.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("Enumerations do not support remove operation");
}
}

View File

@ -54,5 +54,6 @@ public interface SerialVersionUID {
public static final long OperationTimedoutException = Base | 0x18;
public static final long StorageUnavailableException = Base | 0x19;
public static final long InfficientVirtualNetworkCapacityException = Base | 0x1a;
public static final long DiscoveryException = Base | 0x1b;
public static final long DiscoveryException = Base | 0x1b;
public static final long ConflictingNetworkSettingException = Base | 0x1c;
}

View File

@ -18,6 +18,7 @@
package com.cloud.utils.component;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import com.cloud.utils.EnumerationImpl;
@ -30,7 +31,7 @@ import com.cloud.utils.EnumerationImpl;
* the iterator even during dynamic reloading.
*
**/
public class Adapters<T extends Adapter> {
public class Adapters<T extends Adapter> implements Iterable<T> {
private List<T> _adapters;
protected String _name;
@ -51,6 +52,11 @@ public class Adapters<T extends Adapter> {
public Enumeration<T> enumeration() {
return new EnumerationImpl<T>(_adapters.iterator());
}
@Override
public Iterator<T> iterator() {
return new EnumerationImpl<T>(_adapters.iterator());
}
protected List<T> get() {
return _adapters;

View File

@ -45,8 +45,11 @@ import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.TableGenerator;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.NoOp;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
@ -126,8 +129,11 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
protected final Map<Pair<String, String>, Attribute> _allColumns;
protected Enhancer _enhancer;
protected Factory _factory;
protected Enhancer _searchEnhancer;
protected int _timeoutSeconds;
protected final static CallbackFilter s_callbackFilter = new UpdateFilter();
protected static final String FOR_UPDATE_CLAUSE = " FOR UPDATE ";
protected static final String SHARE_MODE_CLAUSE = " LOCK IN SHARE MODE";
protected static final String SELECT_LAST_INSERT_ID_SQL = "SELECT LAST_INSERT_ID()";
@ -157,9 +163,10 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
return dao;
}
@Override
@SuppressWarnings("unchecked")
public <J> GenericSearchBuilder<T, J> createSearchBuilder(Class<J> resultType) {
final T entity = (T)_enhancer.create();
final T entity = (T)_searchEnhancer.create();
final Factory factory = (Factory)entity;
GenericSearchBuilder<T, J> builder = new GenericSearchBuilder<T, J>(entity, resultType, _allAttributes);
factory.setCallback(0, builder);
@ -210,11 +217,18 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
_tgs.put(tg.name(), tg);
}
Callback[] callbacks = new Callback[] { NoOp.INSTANCE, new UpdateBuilder(_allAttributes) };
_enhancer = new Enhancer();
_enhancer.setSuperclass(_entityBeanType);
_enhancer.setCallback(new UpdateBuilder(_allAttributes));
_enhancer.setCallbackFilter(s_callbackFilter);
_enhancer.setCallbacks(callbacks);
_factory = (Factory)_enhancer.create();
_searchEnhancer = new Enhancer();
_searchEnhancer.setSuperclass(_entityBeanType);
_searchEnhancer.setCallback(new UpdateBuilder(_allAttributes));
if (s_logger.isTraceEnabled()) {
s_logger.trace("Select SQL: " + _partialSelectSql.first().toString());
s_logger.trace("Remove SQL: " + (_removeSql != null ? _removeSql.first() : "No remove sql"));
@ -235,8 +249,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
@Override @DB(txn=false)
@SuppressWarnings("unchecked")
public T createForUpdate(final ID id) {
final T entity = (T)_enhancer.create();
final Factory factory = (Factory)entity;
final T entity = (T)_factory.newInstance(new Callback[] {NoOp.INSTANCE, new UpdateBuilder(_allAttributes)});
if (id != null) {
try {
_idField.set(entity, id);
@ -244,7 +257,6 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
} catch (final IllegalAccessException e) {
}
}
factory.setCallback(0, new UpdateBuilder(_allAttributes));
return entity;
}
@ -254,7 +266,6 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
}
@Override
@SuppressWarnings("unchecked")
public <K> K getNextInSequence(final Class<K> clazz, final String name) {
final TableGenerator tg = _tgs.get(name);
assert (tg != null) : "Couldn't find Table generator using " + name;
@ -285,6 +296,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
return searchAll(sc, filter, lock, cache);
}
@Override
public List<T> searchAll(SearchCriteria<T> sc, final Filter filter, final Boolean lock, final boolean cache) {
String clause = sc != null ? sc.getWhereClause() : null;
if (clause != null && clause.length() == 0) {
@ -377,7 +389,6 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
final Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = s_initStmt;
final List<T> result = new ArrayList<T>();
try {
pstmt = txn.prepareAutoCloseStatement(sql);
int i = 0;
@ -398,7 +409,6 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
}
ResultSet rs = pstmt.executeQuery();
SelectType st = sc.getSelectType();
ResultSetMetaData md = rs.getMetaData();
ArrayList<M> results = new ArrayList<M>();
List<Field> fields = sc.getSelectFields();
while (rs.next()) {
@ -505,8 +515,8 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
final Enumerated enumerated = field.getAnnotation(Enumerated.class);
final EnumType enumType = (enumerated == null) ? EnumType.STRING : enumerated.value();
final Enum[] enums = (Enum[])field.getType().getEnumConstants();
for (final Enum e : enums) {
final Enum<?>[] enums = (Enum<?>[])field.getType().getEnumConstants();
for (final Enum<?> e : enums) {
if ((enumType == EnumType.STRING && e.name().equalsIgnoreCase(rs.getString(index))) ||
(enumType == EnumType.ORDINAL && e.ordinal() == rs.getInt(index))) {
field.set(entity, e);
@ -626,7 +636,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
@DB(txn=false)
protected int update(final ID id, final UpdateBuilder ub) {
SearchCriteria sc = createSearchCriteria();
SearchCriteria<T> sc = createSearchCriteria();
sc.addAnd(_idAttributes.get(_table)[0], SearchCriteria.Op.EQ, id);
int rowsUpdated = update(ub, sc, null);
if (_cache != null) {
@ -761,7 +771,6 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
}
@Override @DB(txn=false)
@SuppressWarnings("unchecked")
public T findById(final ID id, boolean fresh) {
if(!fresh)
return findById(id);
@ -801,6 +810,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
return acquire(id, _timeoutSeconds);
}
@Override
public T acquire(final ID id, int seconds) {
Transaction txn = Transaction.currentTxn();
T t = null;
@ -941,6 +951,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
}
// FIXME: Does not work for joins.
@Override
public int delete(final SearchCriteria<T> sc) {
final StringBuilder str = new StringBuilder("DELETE FROM ");
str.append(_table);
@ -1176,7 +1187,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
if (type == EnumType.STRING) {
pstmt.setString(j, value == null ? null : value.toString());
} else if (type == EnumType.ORDINAL) {
pstmt.setInt(j, value == null ? null : ((Enum)value).ordinal());
pstmt.setInt(j, value == null ? null : ((Enum<?>)value).ordinal());
}
} else if (attr.field.getType() == byte[].class) {
pstmt.setBytes(j, (byte[])value);
@ -1204,7 +1215,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
@SuppressWarnings("unchecked") @DB(txn=false)
protected T toEntityBean(final ResultSet result, final boolean cache) throws SQLException {
final T entity = (T)_factory.newInstance(new UpdateBuilder(_allAttributes));
final T entity = (T)_factory.newInstance(new Callback[] {NoOp.INSTANCE, new UpdateBuilder(_allAttributes)});
toEntityBean(result, entity);
@ -1341,13 +1352,13 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
public static <T> UpdateBuilder getUpdateBuilder(final T entityObject) {
final Factory factory = (Factory)entityObject;
assert(factory != null);
return (UpdateBuilder)factory.getCallback(0);
return (UpdateBuilder)factory.getCallback(1);
}
@SuppressWarnings("unchecked")
@Override @DB(txn=false)
public SearchBuilder<T> createSearchBuilder() {
final T entity = (T)_enhancer.create();
final T entity = (T)_searchEnhancer.create();
final Factory factory = (Factory)entity;
SearchBuilder<T> builder = new SearchBuilder<T>(entity, _allAttributes);
factory.setCallback(0, builder);

View File

@ -18,16 +18,13 @@
package com.cloud.utils.db;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.exception.CloudRuntimeException;
@ -40,6 +37,7 @@ public class UpdateBuilder implements MethodInterceptor {
_changes = new HashMap<String, Ternary<Attribute, Boolean, Object>>();
}
@Override
public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
if (name.startsWith("set")) {
@ -125,7 +123,6 @@ public class UpdateBuilder implements MethodInterceptor {
}
public StringBuilder toSql(String tables) {
List<Pair<Attribute, Object>> setters = new ArrayList<Pair<Attribute, Object>>();
if (_changes.isEmpty()) {
return null;
}

View File

@ -0,0 +1,16 @@
/**
*
*/
package com.cloud.utils.db;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackFilter;
public class UpdateFilter implements CallbackFilter {
@Override
public int accept(Method method) {
String name = method.getName();
return (name.startsWith("set") || name.startsWith("incr") || name.startsWith("decr")) ? 1 : 0;
}
}