domain router up and running...now on to patching through the network between the domain router and the vm

This commit is contained in:
Alex Huang 2010-10-29 11:57:15 -07:00
parent ea2c493fac
commit 14f80f2e13
32 changed files with 576 additions and 149 deletions

View File

@ -12,4 +12,5 @@ public interface DataCenter extends Grouping {
long getId();
String getDns1();
String getDns2();
String getGuestNetworkCidr();
}

View File

@ -0,0 +1,41 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.exception;
import com.cloud.utils.SerialVersionUID;
import com.cloud.utils.exception.CloudRuntimeException;
public class AccountLimitException extends CloudRuntimeException {
private static final long serialVersionUID = SerialVersionUID.AccountLimitException;
protected AccountLimitException() {
super();
}
public AccountLimitException(String msg) {
super(msg);
}
public AccountLimitException(String msg, Throwable cause) {
super(msg, cause);
}
// TODO: Add the actual thing that causes the exception. Is it ip address, vm, etc?
}

View File

@ -30,7 +30,10 @@ public class PermissionDeniedException extends CloudRuntimeException {
public PermissionDeniedException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
protected PermissionDeniedException() {
super();
}
}

View File

@ -3,6 +3,7 @@
*/
package com.cloud.network;
import java.net.URI;
import java.util.List;
import java.util.Set;
@ -92,7 +93,9 @@ public interface NetworkConfiguration extends ControlledEntity {
long getRelated();
String getBroadcastUri();
URI getBroadcastUri();
String getDns();
String getDns1();
String getDns2();
}

View File

@ -3,6 +3,7 @@
*/
package com.cloud.network.element;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
@ -23,11 +24,11 @@ public interface NetworkElement extends Adapter {
* @param offering network offering that originated the network configuration.
* @return true if network configuration is now usable; false if not; null if not handled by this element.
*/
Boolean implement(NetworkConfiguration config, NetworkOffering offering, Account user) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
boolean implement(NetworkConfiguration config, NetworkOffering offering, DeployDestination dest, Account user) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException;
Boolean prepare(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
boolean prepare(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, DeployDestination dest, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
Boolean release(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
boolean release(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
Boolean shutdown(NetworkConfiguration config, NetworkOffering offering, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
boolean shutdown(NetworkConfiguration config, NetworkOffering offering, Account user) throws ConcurrentOperationException, ResourceUnavailableException;
}

View File

@ -33,7 +33,7 @@ updateResourceLimit=com.cloud.api.commands.UpdateResourceLimitCmd;3
listResourceLimits=com.cloud.api.commands.ListResourceLimitsCmd;15
#### VM commands
deployVirtualMachine=com.cloud.api.commands.DeployVMCmd;11
deployVirtualMachine=com.cloud.api.commands.DeployVm2Cmd;11
destroyVirtualMachine=com.cloud.api.commands.DestroyVMCmd;15
rebootVirtualMachine=com.cloud.api.commands.RebootVMCmd;15
startVirtualMachine=com.cloud.api.commands.StartVMCmd;15

View File

@ -79,8 +79,8 @@ import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
@ -101,8 +101,8 @@ import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.StorageUnavailableException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Host.Type;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.info.ConsoleProxyConnectionInfo;
import com.cloud.info.ConsoleProxyInfo;
@ -113,10 +113,10 @@ import com.cloud.info.RunningHostInfoAgregator;
import com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo;
import com.cloud.maid.StackMaid;
import com.cloud.network.IpAddrAllocator;
import com.cloud.network.NetworkConfigurationVO;
import com.cloud.network.NetworkManager;
import com.cloud.network.IpAddrAllocator.networkInfo;
import com.cloud.network.Network.TrafficType;
import com.cloud.network.NetworkConfigurationVO;
import com.cloud.network.NetworkManager;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offerings.NetworkOfferingVO;
@ -128,9 +128,9 @@ import com.cloud.storage.GuestOSVO;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateHostDao;
@ -159,12 +159,12 @@ import com.cloud.vm.NicProfile;
import com.cloud.vm.State;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachineGuru;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineName;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.VmManager;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.dao.ConsoleProxyDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.google.gson.Gson;
@ -529,7 +529,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
@Override
public ConsoleProxyVO startProxy(long proxyVmId, long startEventId) {
try {
return start(proxyVmId, startEventId);
return start2(proxyVmId, startEventId);
} catch (StorageUnavailableException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
@ -885,7 +885,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
if (s_logger.isDebugEnabled())
s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
Map<String, Object> context = createProxyInstance(dataCenterId);
Map<String, Object> context = createProxyInstance2(dataCenterId);
long proxyVmId = (Long) context.get("proxyVmId");
if (proxyVmId == 0) {
@ -925,7 +925,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
if (s_logger.isDebugEnabled())
s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
Map<String, Object> context = createProxyInstance(dataCenterId);
Map<String, Object> context = createProxyInstance2(dataCenterId);
long proxyVmId = (Long) context.get("proxyVmId");
if (proxyVmId == 0) {
@ -1467,7 +1467,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
try {
if (proxyLock.lock(ACQUIRE_GLOBAL_LOCK_TIMEOUT_FOR_SYNC)) {
try {
readyProxy = start(readyProxy.getId(), 0);
readyProxy = start2(readyProxy.getId(), 0);
} finally {
proxyLock.unlock();
}
@ -2451,7 +2451,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, VirtualMach
if(certList.size()>0){
CertificateVO cert = certList.get(0);//there will only be 1 cert in db for now
String certStr = cert.getCertificate();
long proxyVmId = ((StartupProxyCommand)cmd).getProxyVmId();
long proxyVmId = (cmd).getProxyVmId();
ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(proxyVmId);
//find corresponding host
if(consoleProxy!=null){

View File

@ -17,6 +17,8 @@
*/
package com.cloud.network;
import java.net.URI;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
@ -24,6 +26,7 @@ import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Transient;
import com.cloud.network.Network.BroadcastDomainType;
import com.cloud.network.Network.Mode;
@ -56,7 +59,7 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
TrafficType trafficType;
@Column(name="broadcast_uri")
String broadcastUri;
URI broadcastUri;
@Column(name="gateway")
String gateway;
@ -80,8 +83,8 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
@Enumerated(value=EnumType.STRING)
State state;
@Column(name="dns")
String dns;
@Column(name="dns1")
String dns1;
@Column(name="domain_id")
long domainId;
@ -89,10 +92,19 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
@Column(name="account_id")
long accountId;
@Column(name="mac_address_seq", updatable=false, nullable=false)
@TableGenerator(name="mac_address_seq", table="network_configuration", pkColumnName="id", valueColumnName="mac_address_seq", allocationSize=1)
@Column(name="set_fields")
long setFields;
@TableGenerator(name="mac_address_seq", table="op_network_configurations", pkColumnName="id", valueColumnName="mac_address_seq", allocationSize=1)
@Transient
long macAddress = 1;
@Column(name="guru_data")
String guruData;
@Column(name="dns2")
String dns2;
public NetworkConfigurationVO() {
}
@ -116,6 +128,10 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
public NetworkConfigurationVO(long id, NetworkConfiguration that, long offeringId, long dataCenterId, String guruName, long domainId, long accountId, long related) {
this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, dataCenterId, domainId, accountId, related);
this.gateway = that.getGateway();
this.dns1 = that.getDns1();
this.dns2 = that.getDns2();
this.cidr = that.getCidr();
this.guruName = guruName;
this.state = that.getState();
if (state == null) {
@ -189,6 +205,14 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
return broadcastDomainType;
}
public String getGuruData() {
return guruData;
}
public void setGuruData(String guruData) {
this.guruData = guruData;
}
public String getGuruName() {
return guruName;
}
@ -229,11 +253,11 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
}
@Override
public String getBroadcastUri() {
public URI getBroadcastUri() {
return broadcastUri;
}
public void setBroadcastUri(String broadcastUri) {
public void setBroadcastUri(URI broadcastUri) {
this.broadcastUri = broadcastUri;
}
@ -248,14 +272,25 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
}
@Override
public String getDns() {
return dns;
public String getDns1() {
return dns1;
}
public void setDns(String dns) {
this.dns = dns;
public void setDns1(String dns) {
this.dns1 = dns;
}
@Override
public String getDns2() {
return dns2;
}
public void setDns2(String dns) {
this.dns2 = dns;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof NetworkConfigurationVO)) {
@ -276,4 +311,8 @@ public class NetworkConfigurationVO implements NetworkConfiguration {
return NetUtils.isNetworkAWithinNetworkB(this.cidr, that.cidr);
}
public boolean isImplemented() {
return broadcastUri != null && cidr != null && gateway != null && mode != null && broadcastDomainType != null;
}
}

View File

@ -36,6 +36,7 @@ import com.cloud.api.commands.StartRouterCmd;
import com.cloud.api.commands.StopRouterCmd;
import com.cloud.api.commands.UpdateLoadBalancerRuleCmd;
import com.cloud.api.commands.UpgradeRouterCmd;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
@ -318,4 +319,6 @@ public interface NetworkManager extends Manager {
List<NetworkConfigurationVO> getNetworkConfigurationsforOffering(long offeringId, long dataCenterId, long accountId);
List<NetworkConfigurationVO> setupNetworkConfiguration(Account owner, ServiceOfferingVO offering, DeploymentPlan plan);
String assignSourceNatIpAddress(Account account, DataCenter dc) throws InsufficientAddressCapacityException;
}

View File

@ -64,6 +64,7 @@ import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.dc.DataCenter;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.Vlan.VlanType;
@ -79,6 +80,7 @@ import com.cloud.event.EventTypes;
import com.cloud.event.EventUtils;
import com.cloud.event.EventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.exception.AccountLimitException;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
@ -358,6 +360,108 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
}
}
@Override @DB
public String assignSourceNatIpAddress(Account account, DataCenter dc) throws InsufficientAddressCapacityException {
final long dcId = dc.getId();
String sourceNat = null;
final long accountId = account.getId();
Transaction txn = Transaction.currentTxn();
try {
final EventVO event = new EventVO();
event.setUserId(1L); // system user performed the action...
event.setAccountId(account.getId());
event.setType(EventTypes.EVENT_NET_IP_ASSIGN);
txn.start();
account = _accountDao.acquire(accountId);
if (account == null) {
s_logger.warn("Unable to lock account " + accountId);
return null;
}
if(s_logger.isDebugEnabled())
s_logger.debug("lock account " + accountId + " is acquired");
boolean isAccountIP = false;
List<IPAddressVO> addrs = listPublicIpAddressesInVirtualNetwork(account.getId(), dcId, true);
if (addrs.size() == 0) {
// Check that the maximum number of public IPs for the given accountId will not be exceeded
if (_accountMgr.resourceLimitExceeded(account, ResourceType.public_ip)) {
throw new AccountLimitException("Maximum number of public IP addresses for account: " + account.getAccountName() + " has been exceeded.");
}
//check for account specific IP pool.
addrs = listPublicIpAddressesInVirtualNetwork(account.getId(), dcId, null);
if (addrs.size() == 0){
if (s_logger.isDebugEnabled()) {
s_logger.debug("assigning a new ip address");
}
Pair<String, VlanVO> ipAndVlan = _vlanDao.assignIpAddress(dc.getId(), accountId, account.getDomainId(), VlanType.VirtualNetwork, true);
if (ipAndVlan != null) {
sourceNat = ipAndVlan.first();
// Increment the number of public IPs for this accountId in the database
_accountMgr.incrementResourceCount(accountId, ResourceType.public_ip);
event.setParameters("address=" + sourceNat + "\nsourceNat=true\ndcId="+dcId);
event.setDescription("Acquired a public ip: " + sourceNat);
_eventDao.persist(event);
}
}else{
isAccountIP = true;
sourceNat = addrs.get(0).getAddress();
_ipAddressDao.setIpAsSourceNat(sourceNat);
s_logger.debug("assigning a new ip address " +sourceNat);
// Increment the number of public IPs for this accountId in the database
_accountMgr.incrementResourceCount(accountId, ResourceType.public_ip);
event.setParameters("address=" + sourceNat + "\nsourceNat=true\ndcId="+dcId);
event.setDescription("Acquired a public ip: " + sourceNat);
_eventDao.persist(event);
}
} else {
sourceNat = addrs.get(0).getAddress();
}
if (sourceNat == null) {
txn.rollback();
event.setLevel(EventVO.LEVEL_ERROR);
event.setParameters("dcId=" + dcId);
event.setDescription("Failed to acquire a public ip.");
_eventDao.persist(event);
s_logger.error("Unable to get source nat ip address for account " + account.getId());
return null;
}
UserStatisticsVO stats = _userStatsDao.findBy(account.getId(), dcId);
if (stats == null) {
stats = new UserStatisticsVO(account.getId(), dcId);
_userStatsDao.persist(stats);
}
txn.commit();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Source Nat is " + sourceNat);
}
return sourceNat;
} finally {
if (account != null) {
if(s_logger.isDebugEnabled())
s_logger.debug("Releasing lock account " + accountId);
_accountDao.release(accountId);
}
}
}
@Override
@DB
public DomainRouterVO createDhcpServerForDirectlyAttachedGuests(long userId, long accountId, DataCenterVO dc, HostPodVO pod, Long candidateHost, VlanVO guestVlan) throws ConcurrentOperationException{
@ -1766,12 +1870,11 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
to.setIp(nic.getIp4Address());
to.setNetmask(nic.getNetmask());
to.setMac(nic.getMacAddress());
if (config.getDns() != null) {
String[] tokens = config.getDns().split(",");
to.setDns1(tokens[0]);
if (tokens.length > 2) {
to.setDns2(tokens[1]);
}
if (config.getDns1() != null) {
to.setDns1(config.getDns1());
}
if (config.getDns2() != null) {
to.setDns2(config.getDns2());
}
if (nic.getGateway() != null) {
to.setGateway(nic.getGateway());
@ -1790,8 +1893,10 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
}
@DB
protected Pair<NetworkGuru, NetworkConfigurationVO> implementNetworkConfiguration(long configId, DeployDestination dest) throws ConcurrentOperationException {
Transaction txn = Transaction.currentTxn();
protected Pair<NetworkGuru, NetworkConfigurationVO> implementNetworkConfiguration(long configId, DeployDestination dest, Account user) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientAddressCapacityException {
Transaction.currentTxn();
Pair<NetworkGuru, NetworkConfigurationVO> implemented = new Pair<NetworkGuru, NetworkConfigurationVO>(null, null);
NetworkConfigurationVO config = _networkConfigDao.acquire(configId);
if (config == null) {
throw new ConcurrentOperationException("Unable to acquire network configuration: " + configId);
@ -1800,21 +1905,43 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
try {
NetworkGuru guru = _networkGurus.get(config.getGuruName());
if (config.getState() == NetworkConfiguration.State.Implemented || config.getState() == NetworkConfiguration.State.Setup) {
return new Pair<NetworkGuru, NetworkConfigurationVO>(guru, config);
implemented.set(guru, config);
return implemented;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Asking " + guru + " to implement " + config);
}
NetworkConfiguration result = guru.implement(config, _networkOfferingDao.findById(config.getNetworkOfferingId()), dest);
NetworkOfferingVO offering = _networkOfferingDao.findById(config.getNetworkOfferingId());
NetworkConfiguration result = guru.implement(config, offering, dest);
config.setCidr(result.getCidr());
config.setBroadcastUri(result.getBroadcastUri());
config.setGateway(result.getGateway());
config.setDns(result.getDns());
config.setDns1(result.getDns1());
config.setDns2(result.getDns2());
config.setMode(result.getMode());
config.setState(NetworkConfiguration.State.Implemented);
_networkConfigDao.update(configId, config);
return new Pair<NetworkGuru, NetworkConfigurationVO>(guru, config);
for (NetworkElement element : _networkElements) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Asking " + element.getName() + " to implmenet " + config);
}
try {
element.implement(config, offering, dest, user);
} catch (InsufficientCapacityException e) {
throw new ResourceUnavailableException("Unable to start domain router for this VM", e);
}
}
implemented.set(guru, config);
return implemented;
} finally {
if (implemented.first() == null) {
s_logger.debug("Cleaning up because we're unable to implement network " + config);
}
_networkConfigDao.release(configId);
}
}
@ -1825,7 +1952,7 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
NicTO[] nicTos = new NicTO[nics.size()];
int i = 0;
for (NicVO nic : nics) {
Pair<NetworkGuru, NetworkConfigurationVO> implemented = implementNetworkConfiguration(nic.getNetworkConfigurationId(), dest);
Pair<NetworkGuru, NetworkConfigurationVO> implemented = implementNetworkConfiguration(nic.getNetworkConfigurationId(), dest, user);
NetworkGuru concierge = implemented.first();
NetworkConfigurationVO config = implemented.second();
NicProfile profile = null;
@ -1847,10 +1974,10 @@ public class NetworkManagerImpl implements NetworkManager, DomainRouterService {
nic.setAddressFormat(profile.getFormat());
_nicDao.update(nic.getId(), nic);
for (NetworkElement element : _networkElements) {
if (!element.prepare(config, profile, vmProfile, null, user)) {
s_logger.warn("Unable to prepare " + nic + " for element " + element.getName());
return null;
if (s_logger.isDebugEnabled()) {
s_logger.debug("Asking " + element.getName() + " to prepare for " + nic);
}
element.prepare(config, profile, vmProfile, null, dest, user);
}
}

View File

@ -3,6 +3,11 @@
*/
package com.cloud.network.configuration;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import javax.ejb.Local;
import com.cloud.dc.DataCenterVO;
@ -12,25 +17,36 @@ import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientVirtualNetworkCapcityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network.BroadcastDomainType;
import com.cloud.network.Network.Mode;
import com.cloud.network.Network.TrafficType;
import com.cloud.network.NetworkConfiguration;
import com.cloud.network.NetworkConfiguration.State;
import com.cloud.network.NetworkConfigurationVO;
import com.cloud.network.dao.NetworkConfigurationDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.resource.Resource.ReservationStrategy;
import com.cloud.user.Account;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.NicProfile;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.NicDao;
@Local(value=NetworkGuru.class)
public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
@Inject protected NetworkConfigurationDao _profileDao;
@Inject protected NetworkConfigurationDao _networkConfigDao;
@Inject protected DataCenterDao _dcDao;
@Inject protected VlanDao _vlanDao;
@Inject protected VlanDao _vlanDao;
@Inject protected NicDao _nicDao;
String _defaultGateway;
String _defaultCidr;
Random _rand = new Random(System.currentTimeMillis());
protected GuestNetworkGuru() {
super();
@ -52,43 +68,140 @@ public class GuestNetworkGuru extends AdapterBase implements NetworkGuru {
broadcastType = BroadcastDomainType.Native;
mode = Mode.Dhcp;
}
NetworkConfigurationVO profile = new NetworkConfigurationVO(offering.getTrafficType(), mode, broadcastType, offering.getId(), plan.getDataCenterId());
DataCenterVO dc = _dcDao.findById(plan.getDataCenterId());
return profile;
NetworkConfigurationVO config = new NetworkConfigurationVO(offering.getTrafficType(), mode, broadcastType, offering.getId(), plan.getDataCenterId());
if (userSpecified != null) {
if ((userSpecified.getCidr() == null && userSpecified.getGateway() != null) ||
(userSpecified.getCidr() != null && userSpecified.getGateway() == null)) {
throw new InvalidParameterValueException("cidr and gateway must be specified together.");
}
if (userSpecified.getCidr() != null) {
config.setCidr(userSpecified.getCidr());
config.setGateway(userSpecified.getGateway());
} else {
String guestNetworkCidr = dc.getGuestNetworkCidr();
String[] cidrTuple = guestNetworkCidr.split("\\/");
config.setGateway(NetUtils.getIpRangeStartIpFromCidr(cidrTuple[0], Long.parseLong(cidrTuple[1])));
config.setCidr(guestNetworkCidr);
config.setDns1(dc.getDns1());
config.setDns2(dc.getDns2());
}
if (userSpecified.getBroadcastUri() != null) {
config.setBroadcastUri(userSpecified.getBroadcastUri());
config.setState(State.Setup);
}
} else {
String guestNetworkCidr = dc.getGuestNetworkCidr();
String[] cidrTuple = guestNetworkCidr.split("\\/");
config.setGateway(NetUtils.getIpRangeStartIpFromCidr(cidrTuple[0], Long.parseLong(cidrTuple[1])));
config.setCidr(guestNetworkCidr);
config.setDns1(dc.getDns1());
config.setDns2(dc.getDns2());
}
return config;
}
@Override
public NetworkConfiguration implement(NetworkConfiguration config, NetworkOffering offering, DeployDestination destination) {
// TODO Auto-generated method stub
return null;
public NetworkConfiguration implement(NetworkConfiguration config, NetworkOffering offering, DeployDestination dest) {
assert (config.getState() == State.Allocated) : "Why implement are we implementing " + config;
long dcId = dest.getDataCenter().getId();
NetworkConfigurationVO implemented = new NetworkConfigurationVO(config.getTrafficType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), config.getDataCenterId());
if (config.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(dcId, config.getAccountId());
implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vnet));
} else {
implemented.setBroadcastUri(config.getBroadcastUri());
}
if (config.getGateway() != null) {
implemented.setGateway(config.getGateway());
}
if (config.getCidr() != null) {
implemented.setCidr(config.getCidr());
}
if (config.getDns1() != null) {
implemented.setDns1(config.getDns1());
}
if (config.getDns2() != null) {
implemented.setDns2(config.getDns2());
}
return implemented;
}
@Override
public NicProfile allocate(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException {
// TODO Auto-generated method stub
return null;
if (config.getTrafficType() != TrafficType.Guest) {
return null;
}
if (nic == null) {
nic = new NicProfile(ReservationStrategy.Start, null, null, null, null);
} else {
nic.setStrategy(ReservationStrategy.Create);
}
if (nic.getMacAddress() == null) {
nic.setMacAddress(_networkConfigDao.getNextAvailableMacAddress(config.getId()));
if (nic.getMacAddress() == null) {
throw new InsufficientAddressCapacityException("Unable to allocate more mac addresses");
}
}
return nic;
}
@DB
protected String acquireGuestIpAddress(NetworkConfiguration config) {
List<String> ips = _nicDao.listIpAddressInNetworkConfiguration(config.getId());
String[] cidr = config.getCidr().split("/");
Set<Long> allPossibleIps = NetUtils.getAllIpsFromCidr(cidr[0], Integer.parseInt(cidr[1]));
Set<Long> usedIps = new TreeSet<Long> ();
for (String ip : ips) {
usedIps.add(NetUtils.ip2Long(ip));
}
if (usedIps.size() != 0) {
allPossibleIps.removeAll(usedIps);
}
if (allPossibleIps.isEmpty()) {
return null;
}
Long[] array = allPossibleIps.toArray(new Long[allPossibleIps.size()]);
return NetUtils.long2Ip(array[_rand.nextInt() % array.length]);
}
@Override
public String reserve(NicProfile nic, NetworkConfiguration config, VirtualMachineProfile vm, DeployDestination dest) throws InsufficientVirtualNetworkCapcityException,
InsufficientAddressCapacityException {
// TODO Auto-generated method stub
return null;
assert (nic.getReservationStrategy() == ReservationStrategy.Start) : "What can I do for nics that are not allocated at start? ";
nic.setBroadcastUri(config.getBroadcastUri());
nic.setIsolationUri(config.getBroadcastUri());
nic.setGateway(config.getGateway());
nic.setIp4Address(acquireGuestIpAddress(config));
nic.setNetmask(NetUtils.cidr2Netmask(config.getCidr()));
nic.setDns1(config.getDns1());
nic.setDns2(config.getDns2());
return "ABCD";
}
@Override
public boolean release(String uniqueId) {
// TODO Auto-generated method stub
return false;
return true;
}
@Override
public void destroy(NetworkConfiguration config, NetworkOffering offering) {
// TODO Auto-generated method stub
config.getBroadcastUri();
}
}

View File

@ -33,4 +33,11 @@ public interface NetworkConfigurationDao extends GenericDao<NetworkConfiguration
SearchBuilder<NetworkAccountVO> createSearchBuilderForAccount();
List<NetworkConfigurationVO> getNetworkConfigurationsForOffering(long offeringId, long dataCenterId, long accountId);
List<NetworkConfigurationVO> getRelatedNetworkConfigurations(long related);
/**
* Retrieves the next available mac address in this network configuration.
* @param networkConfigId id
* @return mac address if there is one. null if not.
*/
String getNextAvailableMacAddress(long networkConfigId);
}

View File

@ -17,9 +17,13 @@
*/
package com.cloud.network.dao;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;
import javax.ejb.Local;
import javax.persistence.TableGenerator;
import com.cloud.network.Network.BroadcastDomainType;
import com.cloud.network.Network.Mode;
@ -33,7 +37,10 @@ import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SequenceFetcher;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
@Local(value=NetworkConfigurationDao.class) @DB(txn=false)
public class NetworkConfigurationDaoImpl extends GenericDaoBase<NetworkConfigurationVO, Long> implements NetworkConfigurationDao {
@ -44,6 +51,9 @@ public class NetworkConfigurationDaoImpl extends GenericDaoBase<NetworkConfigura
final SearchBuilder<NetworkConfigurationVO> RelatedConfigsSearch;
NetworkAccountDaoImpl _accountsDao = new NetworkAccountDaoImpl();
final TableGenerator _tgMacAddress;
Random _rand = new Random(System.currentTimeMillis());
long _prefix = 0x2;
protected NetworkConfigurationDaoImpl() {
super();
@ -79,6 +89,8 @@ public class NetworkConfigurationDaoImpl extends GenericDaoBase<NetworkConfigura
RelatedConfigsSearch = createSearchBuilder();
RelatedConfigsSearch.and("related", RelatedConfigsSearch.entity().getRelated(), SearchCriteria.Op.EQ);
RelatedConfigsSearch.done();
_tgMacAddress = _tgs.get("macAddress");
}
public List<NetworkConfigurationVO> findBy(TrafficType trafficType, Mode mode, BroadcastDomainType broadcastType, long networkOfferingId, long dataCenterId) {
@ -116,6 +128,13 @@ public class NetworkConfigurationDaoImpl extends GenericDaoBase<NetworkConfigura
txn.start();
config = super.persist(config);
addAccountToNetworkConfiguration(config.getId(), config.getAccountId(), true);
try {
PreparedStatement pstmt = txn.prepareAutoCloseStatement("INSERT INTO op_network_configurations (id) VALUES(?)");
pstmt.setLong(1, config.getId());
pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Problem inserting into the op_network_configurations");
}
txn.commit();
return config;
}
@ -150,4 +169,13 @@ public class NetworkConfigurationDaoImpl extends GenericDaoBase<NetworkConfigura
sc.setParameters("related", related);
return search(sc, null);
}
@Override
public String getNextAvailableMacAddress(long networkConfigId) {
SequenceFetcher fetch = SequenceFetcher.getInstance();
long seq = fetch.getNextSequence(Long.class, _tgMacAddress, networkConfigId);
seq = seq | _prefix | ((_rand.nextInt(Short.MAX_VALUE) << 16) & 0x00000000ffff0000l);
return NetUtils.long2Mac(seq);
}
}

View File

@ -17,19 +17,16 @@
*/
package com.cloud.network.element;
import java.util.List;
import javax.ejb.Local;
import org.apache.log4j.Logger;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.Network.TrafficType;
import com.cloud.network.NetworkConfiguration;
import com.cloud.network.NetworkConfiguration.State;
import com.cloud.network.NetworkConfigurationVO;
import com.cloud.network.NetworkManager;
import com.cloud.network.dao.NetworkConfigurationDao;
import com.cloud.network.router.DomainRouterManager;
@ -60,52 +57,25 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement {
@Inject DomainRouterDao _routerDao;
@Override
public Boolean implement(NetworkConfiguration config, NetworkOffering offering, Account user) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException {
public boolean implement(NetworkConfiguration guestConfig, NetworkOffering offering, DeployDestination dest, Account user) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException {
if (offering.getGuestIpType() != GuestIpType.Virtualized) {
s_logger.trace("Not handling guest ip type = " + offering.getGuestIpType());
return null;
}
List<NetworkConfigurationVO> configs = _networkConfigDao.getRelatedNetworkConfigurations(config.getRelated());
NetworkConfigurationVO publicConfig = null;
NetworkConfigurationVO guestConfig = null;
for (NetworkConfigurationVO c : configs) {
if (c.getState() != State.Implemented && c.getState() != State.Setup) {
s_logger.debug("Not all network is ready to be implemented yet.");
return true;
}
if (c.getTrafficType() == TrafficType.Public) {
publicConfig = c;
} else if (c.getTrafficType() == TrafficType.Guest) {
guestConfig = c;
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("The network configurations are different than what I expected: " + c);
}
return null;
}
}
if (publicConfig == null || guestConfig == null) {
s_logger.debug("Expected to find the network configuration for " + (publicConfig == null ? "public" : "") + (guestConfig == null ? " guest" : ""));
return null;
}
DomainRouterVO router;
router = _routerMgr.deploy(publicConfig, guestConfig, offering, user);
if (router == null) {
s_logger.debug("Unable to deploy the router for " + guestConfig);
return false;
}
DomainRouterVO router = _routerMgr.deploy(guestConfig, offering, dest, user);
if (router == null) {
throw new ResourceUnavailableException("Unable to deploy the router for " + guestConfig);
}
return true;
}
@Override
public Boolean prepare(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) throws ConcurrentOperationException {
public boolean prepare(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, DeployDestination dest, Account user) throws ConcurrentOperationException {
if (config.getTrafficType() != TrafficType.Guest || vm.getType() != Type.User) {
s_logger.trace("Domain Router only cares about guest network and User VMs");
return null;
return false;
}
UserVmVO userVm = _userVmDao.findById(vm.getId());
@ -114,10 +84,10 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement {
}
@Override
public Boolean release(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) {
public boolean release(NetworkConfiguration config, NicProfile nic, VirtualMachineProfile vm, NetworkOffering offering, Account user) {
if (config.getTrafficType() != TrafficType.Guest || vm.getType() != Type.User) {
s_logger.trace("Domain Router only cares about guest network and User VMs");
return null;
return false;
}
@ -125,10 +95,10 @@ public class DomainRouterElement extends AdapterBase implements NetworkElement {
}
@Override
public Boolean shutdown(NetworkConfiguration config, NetworkOffering offering, Account user) throws ConcurrentOperationException {
public boolean shutdown(NetworkConfiguration config, NetworkOffering offering, Account user) throws ConcurrentOperationException {
if (config.getTrafficType() != TrafficType.Guest) {
s_logger.trace("Domain Router only cares about guet network.");
return null;
return false;
}
DomainRouterVO router = _routerDao.findByNetworkConfiguration(config.getId());
if (router == null) {

View File

@ -27,6 +27,7 @@ import com.cloud.api.commands.UpgradeRouterCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.deploy.DeployDestination;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
@ -167,5 +168,5 @@ public interface DomainRouterManager extends Manager {
DomainRouterVO getRouter(long accountId, long zoneId);
DomainRouterVO getRouter(String publicIpAddress);
DomainRouterVO deploy(NetworkConfiguration publicConfig, NetworkConfiguration virtualConfig, NetworkOffering offering, Account owner) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException;
DomainRouterVO deploy(NetworkConfiguration guestConfig, NetworkOffering offering, DeployDestination dest, Account owner) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException;
}

View File

@ -119,6 +119,7 @@ import com.cloud.network.dao.NetworkRuleConfigDao;
import com.cloud.network.dao.SecurityGroupDao;
import com.cloud.network.dao.SecurityGroupVMMapDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.GuestIpType;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.ServiceOfferingVO;
@ -2000,47 +2001,58 @@ public class DomainRouterManagerImpl implements DomainRouterManager, VirtualMach
}
@Override @DB
public DomainRouterVO deploy(NetworkConfiguration publicConfig, NetworkConfiguration virtualConfig, NetworkOffering offering, Account owner) throws InsufficientCapacityException, StorageUnavailableException, ConcurrentOperationException, ResourceUnavailableException {
long dcId = virtualConfig.getDataCenterId();
public DomainRouterVO deploy(NetworkConfiguration guestConfig, NetworkOffering offering, DeployDestination dest, Account owner) throws InsufficientCapacityException, StorageUnavailableException, ConcurrentOperationException, ResourceUnavailableException {
long dcId = dest.getDataCenter().getId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Starting a router for network configurations: public=" + publicConfig + "; virtual=" + virtualConfig);
s_logger.debug("Starting a router for network configurations: virtual=" + guestConfig + " in " + dest);
}
assert publicConfig.getState() == NetworkConfiguration.State.Implemented : "Network is not yet fully implemented: " + publicConfig;
assert virtualConfig.getState() == NetworkConfiguration.State.Implemented : "Network is not yet fully implemented: " + virtualConfig;
assert guestConfig.getState() == NetworkConfiguration.State.Implemented : "Network is not yet fully implemented: " + guestConfig;
assert offering.getGuestIpType() == GuestIpType.Virtualized;
DataCenterDeployment plan = new DataCenterDeployment(dcId, 1);
Transaction txn = Transaction.currentTxn();
txn.start();
virtualConfig = _networkConfigurationDao.lock(virtualConfig.getId(), true);
if (virtualConfig == null) {
throw new ConcurrentOperationException("Unable to get the lock on " + virtualConfig);
guestConfig = _networkConfigurationDao.lock(guestConfig.getId(), true);
if (guestConfig == null) {
throw new ConcurrentOperationException("Unable to get the lock on " + guestConfig);
}
DomainRouterVO router = _routerDao.findByNetworkConfiguration(virtualConfig.getId());
DomainRouterVO router = _routerDao.findByNetworkConfiguration(guestConfig.getId());
if (router == null) {
long id = _routerDao.getNextInSequence(Long.class, "id");
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating the router " + id);
}
String sourceNatIp = _networkMgr.assignSourceNatIpAddress(owner, dest.getDataCenter());
List<NetworkOfferingVO> offerings = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemVmControlNetwork);
NetworkOfferingVO controlOffering = offerings.get(0);
NetworkConfigurationVO controlConfig = _networkMgr.setupNetworkConfiguration(_systemAcct, controlOffering, plan).get(0);
router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), _template.getId(), _template.getGuestOSId(), owner.getDomainId(), owner.getId(), virtualConfig.getId(), _offering.getOfferHA());
_routerDao.persist(router);
List<Pair<NetworkConfigurationVO, NicProfile>> networks = new ArrayList<Pair<NetworkConfigurationVO, NicProfile>>(3);
List<Pair<NetworkConfigurationVO, NicProfile>> networks = new ArrayList<Pair<NetworkConfigurationVO, NicProfile>>(3);
NetworkOfferingVO publicOffering = _networkMgr.getSystemAccountNetworkOfferings(NetworkOfferingVO.SystemVmPublicNetwork).get(0);
List<NetworkConfigurationVO> publicConfigs = _networkMgr.setupNetworkConfiguration(_systemAcct, publicOffering, plan);
NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
defaultNic.setIp4Address(sourceNatIp);
defaultNic.setDeviceId(2);
networks.add(new Pair<NetworkConfigurationVO, NicProfile>((NetworkConfigurationVO)publicConfig, defaultNic));
networks.add(new Pair<NetworkConfigurationVO, NicProfile>((NetworkConfigurationVO)virtualConfig, null));
networks.add(new Pair<NetworkConfigurationVO, NicProfile>(controlConfig, null));
networks.add(new Pair<NetworkConfigurationVO, NicProfile>(publicConfigs.get(0), defaultNic));
NicProfile gatewayNic = new NicProfile();
gatewayNic.setIp4Address(guestConfig.getGateway());
gatewayNic.setBroadcastUri(guestConfig.getBroadcastUri());
gatewayNic.setBroadcastType(guestConfig.getBroadcastDomainType());
gatewayNic.setIsolationUri(guestConfig.getBroadcastUri());
gatewayNic.setMode(guestConfig.getMode());
gatewayNic.setNetmask(NetUtils.getCidrSubNet(guestConfig.getCidr()));
networks.add(new Pair<NetworkConfigurationVO, NicProfile>((NetworkConfigurationVO)guestConfig, gatewayNic));
networks.add(new Pair<NetworkConfigurationVO, NicProfile>(controlConfig, null));
router = new DomainRouterVO(id, _offering.getId(), VirtualMachineName.getRouterName(id, _instance), _template.getId(), _template.getGuestOSId(), owner.getDomainId(), owner.getId(), guestConfig.getId(), _offering.getOfferHA());
router = _routerDao.persist(router);
_vmMgr.allocate(router, _template, _offering, networks, plan, owner);
}

View File

@ -564,6 +564,9 @@ public class AccountManagerImpl implements AccountManager {
@Override
public AccountVO getSystemAccount() {
if (_systemAccount == null) {
_systemAccount = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
}
return _systemAccount;
}

View File

@ -3917,16 +3917,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, VirtualM
s_logger.debug("Allocating in the DB for vm");
Transaction txn = Transaction.currentTxn();
txn.start();
vm = _vmDao.persist(vm);
List<NetworkConfigurationVO> configs = _networkMgr.setupNetworkConfiguration(owner, offering, plan);
List<Pair<NetworkConfigurationVO, NicProfile>> networks = new ArrayList<Pair<NetworkConfigurationVO, NicProfile>>();
for (NetworkConfigurationVO config : configs) {
networks.add(new Pair<NetworkConfigurationVO, NicProfile>(config, null));
}
Transaction txn = Transaction.currentTxn();
txn.start();
vm = _vmDao.persist(vm);
if (_itMgr.allocate(vm, template, offering, rootDiskOffering, dataDiskOfferings, networks, plan, owner) == null) {
return null;
}

View File

@ -10,5 +10,7 @@ import com.cloud.vm.NicVO;
public interface NicDao extends GenericDao<NicVO, Long> {
List<NicVO> listBy(long instanceId);
List<String> listIpAddressInNetworkConfiguration(long networkConfigId);
}

View File

@ -8,13 +8,16 @@ import java.util.List;
import javax.ejb.Local;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.vm.NicVO;
@Local(value=NicDao.class)
public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
private final SearchBuilder<NicVO> InstanceSearch;
private final GenericSearchBuilder<NicVO, String> IpSearch;
protected NicDaoImpl() {
super();
@ -22,6 +25,12 @@ public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
InstanceSearch = createSearchBuilder();
InstanceSearch.and("instance", InstanceSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
InstanceSearch.done();
IpSearch = createSearchBuilder(String.class);
IpSearch.select(null, Func.DISTINCT, IpSearch.entity().getIp4Address());
IpSearch.and("nc", IpSearch.entity().getNetworkConfigurationId(), SearchCriteria.Op.EQ);
IpSearch.and("address", IpSearch.entity().getIp4Address(), SearchCriteria.Op.NNULL);
IpSearch.done();
}
@Override
@ -31,4 +40,10 @@ public class NicDaoImpl extends GenericDaoBase<NicVO, Long> implements NicDao {
return listBy(sc);
}
@Override
public List<String> listIpAddressInNetworkConfiguration(long networkConfigId) {
SearchCriteria<String> sc = IpSearch.create();
sc.setParameters("nc", networkConfigId);
return customSearch(sc, null);
}
}

View File

@ -61,6 +61,7 @@ ALTER TABLE `cloud`.`storage_pool` ADD CONSTRAINT `fk_storage_pool__cluster_id`
ALTER TABLE `cloud`.`storage_pool_details` ADD CONSTRAINT `fk_storage_pool_details__pool_id` FOREIGN KEY `fk_storage_pool__pool_id`(`pool_id`) REFERENCES `storage_pool`(`id`) ON DELETE CASCADE;
ALTER TABLE `cloud`.`storage_pool_details` ADD INDEX `i_storage_pool_details__name__value`(`name`, `value`);
ALTER TABLE `cloud`.`op_network_configurations` ADD CONSTRAINT `fk_op_network_configurations__id` FOREIGN KEY `fk_op_network_configurations__id`(`id`) REFERENCES `network_configurations`(`id`) ON DELETE CASCADE;
ALTER TABLE `cloud`.`user` ADD INDEX `i_user__secret_key_removed`(`secret_key`, `removed`);
ALTER TABLE `cloud`.`user` ADD INDEX `i_user__removed`(`removed`);

View File

@ -91,6 +91,13 @@ CREATE TABLE `cloud`.`hypervsior_properties` (
`max_network_devices` int(10) NOT NULL COMMENT 'maximum number of network devices'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`op_network_configurations`(
`id` bigint unsigned NOT NULL UNIQUE KEY,
`mac_address_seq` bigint unsigned NOT NULL DEFAULT 1 COMMENT 'mac address',
PRIMARY KEY(`id`)
# CONSTRAINT `fk__op_network_configurations__id` FOREIGN KEY `fk_op_network_configurations__id`(`id`) REFERENCES `network_configurations`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`network_configurations` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` varchar(255) COMMENT 'name for this network',
@ -107,11 +114,15 @@ CREATE TABLE `cloud`.`network_configurations` (
`related` bigint unsigned NOT NULL COMMENT 'related to what other network configuration',
`domain_id` bigint unsigned NOT NULL COMMENT 'foreign key to domain id',
`account_id` bigint unsigned NOT NULL COMMENT 'owner of this network',
`mac_address_seq` bigint unsigned DEFAULT 1 COMMENT 'mac address seq number',
`dns` varchar(255) COMMENT 'comma separated DNS list',
`dns1` varchar(255) COMMENT 'comma separated DNS list',
`dns2` varchar(255) COMMENT 'comma separated DNS list',
`guru_data` varchar(1024) COMMENT 'data stored by the network guru that setup this network',
`set_fields` bigint unsigned NOT NULL DEFAULT 0 COMMENT 'which fields are set already',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `cloud`.`account_network_ref` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
`account_id` bigint unsigned NOT NULL COMMENT 'account id',
@ -613,7 +624,7 @@ CREATE TABLE `cloud`.`user_vm` (
CREATE TABLE `cloud`.`domain_router` (
`id` bigint unsigned UNIQUE NOT NULL COMMENT 'Primary Key',
`gateway` varchar(15) NOT NULL COMMENT 'ip address of the gateway to this domR',
`gateway` varchar(15) COMMENT 'ip address of the gateway to this domR',
`ram_size` int(10) unsigned NOT NULL DEFAULT 128 COMMENT 'memory to use in mb',
`dns1` varchar(15) COMMENT 'dns1',
`dns2` varchar(15) COMMENT 'dns2',
@ -621,15 +632,15 @@ CREATE TABLE `cloud`.`domain_router` (
`public_mac_address` varchar(17) COMMENT 'mac address of the public facing network card',
`public_ip_address` varchar(15) COMMENT 'public ip address used for source net',
`public_netmask` varchar(15) COMMENT 'netmask used for the domR',
`guest_mac_address` varchar(17) NOT NULL COMMENT 'mac address of the pod facing network card',
`guest_mac_address` varchar(17) COMMENT 'mac address of the pod facing network card',
`guest_dc_mac_address` varchar(17) COMMENT 'mac address of the data center facing network card',
`guest_netmask` varchar(15) NOT NULL COMMENT 'netmask used for the guest network',
`guest_ip_address` varchar(15) NOT NULL COMMENT ' ip address in the guest network',
`guest_netmask` varchar(15) COMMENT 'netmask used for the guest network',
`guest_ip_address` varchar(15) COMMENT ' ip address in the guest network',
`vnet` varchar(18) COMMENT 'vnet',
`dc_vlan` varchar(18) COMMENT 'vnet',
`vlan_db_id` bigint unsigned COMMENT 'Foreign key into vlan id table',
`vlan_id` varchar(255) COMMENT 'optional VLAN ID for DomainRouter that can be used in rundomr.sh',
`dhcp_ip_address` bigint unsigned NOT NULL DEFAULT 2 COMMENT 'next ip address for dhcp for this domR',
`dhcp_ip_address` bigint unsigned DEFAULT 2 COMMENT 'next ip address for dhcp for this domR',
`network_configuration_id` bigint unsigned NOT NULL DEFAULT 0 COMMENT 'network configuration that this domain router belongs to',
`role` varchar(64) NOT NULL COMMENT 'type of role played by this router',
PRIMARY KEY (`id`)

View File

@ -44,6 +44,11 @@ public class Pair<T, U> {
return t;
}
public void set(T t, U u) {
this.t = t;
this.u = u;
}
@Override
// Note: This means any two pairs with null for both values will match each
// other but what can I do? This is due to stupid type erasure.

View File

@ -31,7 +31,8 @@ public interface SerialVersionUID {
public static final long UUID = Base | 0x1;
public static final long CloudRuntimeException = Base | 0x2;
public static final long CloudStartupServlet = Base | 0x3;
public static final long CloudServiceImpl = Base | 0x4;
public static final long CloudServiceImpl = Base | 0x4;
public static final long AccountLimitException = Base | 0x5;
public static final long UnsupportedVersionException = Base | 0xb;
public static final long DataCenterIpAddressPK = Base | 0xc;
public static final long UnableToExecuteException = Base | 0xd;

View File

@ -348,6 +348,9 @@ public class ComponentLocator extends Thread implements ComponentLocatorMBean {
Info<Manager> info = entry.getValue();
s_logger.info("Injecting Manager: " + info.name);
inject(info.clazz, info.instance);
}
for (Map.Entry<String, Info<Manager>> entry : entries) {
Info<Manager> info = entry.getValue();
s_logger.info("Configuring Manager: " + info.name);
try {
info.instance.configure(info.name, info.params);

View File

@ -222,4 +222,6 @@ public interface GenericDao<T, ID extends Serializable> {
*/
boolean configure(String name, Map<String, Object> params) throws ConfigurationException;
<M> List<M> customSearch(SearchCriteria<M> sc, Filter filter);
}

View File

@ -427,6 +427,15 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
}
}
@Override @DB(txn=false)
public <M> List<M> customSearch(SearchCriteria<M> sc, final Filter filter) {
if (_removed != null) {
sc.addAnd(_removed.second().field.getName(), SearchCriteria.Op.NULL);
}
return searchIncludingRemoved(sc, filter);
}
@DB(txn=false)
protected void setField(Object entity, Field field, ResultSet rs, int index) throws SQLException {
try {
@ -731,6 +740,7 @@ public abstract class GenericDaoBase<T, ID extends Serializable> implements Gene
return _entityBeanType;
}
@DB(txn=false)
protected T findOneIncludingRemovedBy(final SearchCriteria<T> sc) {
Filter filter = new Filter(1);
List<T> results = searchIncludingRemoved(sc, filter, null, false);

View File

@ -96,6 +96,15 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
return this;
}
/**
* Specifies the field to select.
*
* @param fieldName The field name of the result object to put the value of the field selected. This can be null if you're selecting only one field and the result is not a complex object.
* @param func function to place.
* @param useless column to select. Call this with this.entity() method.
* @param params parameters to the function.
* @return a SearchBuilder to build more search parts.
*/
public GenericSearchBuilder<T, K> select(String fieldName, Func func, Object useless, Object... params) {
assert _entity != null : "SearchBuilder cannot be modified once it has been setup";
assert _specifiedAttrs.size() <= 1 : "You can't specify more than one field to search on";
@ -346,7 +355,7 @@ public class GenericSearchBuilder<T, K> implements MethodInterceptor {
}
if (op == Op.SC) {
sql.append(" (").append(((SearchCriteria)params[0]).getWhereClause()).append(") ");
sql.append(" (").append(((SearchCriteria<?>)params[0]).getWhereClause()).append(") ");
return;
}

View File

@ -19,6 +19,7 @@ package com.cloud.utils.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
@ -83,6 +84,7 @@ public class SequenceFetcher {
@Override @SuppressWarnings("unchecked")
public T call() throws Exception {
try {
PreparedStatement stmt = null;
StringBuilder sql = new StringBuilder("SELECT ");
sql.append(_tg.valueColumnName()).append(" FROM ").append(_tg.table());
sql.append(" WHERE ").append(_tg.pkColumnName()).append(" = ? FOR UPDATE");
@ -97,22 +99,23 @@ public class SequenceFetcher {
}
sql = new StringBuilder("UPDATE ");
sql.append(_tg.table()).append(" SET ").append(_tg.valueColumnName()).append("=").append(_tg.valueColumnName()).append("+?");
sql.append(_tg.table()).append(" SET ").append(_tg.valueColumnName()).append("=").append("?+?");
sql.append(" WHERE ").append(_tg.pkColumnName()).append("=?");
PreparedStatement updateStmt = txn.prepareStatement(sql.toString());
updateStmt.setInt(1, _tg.allocationSize());
updateStmt.setInt(2, _tg.allocationSize());
if (_key == null) {
updateStmt.setString(2, _tg.pkColumnValue());
updateStmt.setString(3, _tg.pkColumnValue());
} else {
updateStmt.setObject(2, _key);
updateStmt.setObject(3, _key);
}
ResultSet rs = null;
try {
txn.start();
rs = selectStmt.executeQuery();
stmt = selectStmt;
rs = stmt.executeQuery();
Object obj = null;
while (rs.next()) {
if (_clazz.isAssignableFrom(Long.class)) {
@ -129,10 +132,14 @@ public class SequenceFetcher {
return null;
}
int rows = updateStmt.executeUpdate();
updateStmt.setObject(1, obj);
stmt = updateStmt;
int rows = stmt.executeUpdate();
assert rows == 1 : "Come on....how exactly did we update this many rows " + rows + " for " + updateStmt.toString();
txn.commit();
return (T)obj;
} catch (SQLException e) {
s_logger.warn("Caught this exception when running: " + (stmt != null ? stmt.toString() : ""), e);
} finally {
if (rs != null) {
rs.close();
@ -142,7 +149,7 @@ public class SequenceFetcher {
txn.close();
}
} catch (Exception e) {
s_logger.warn("Caught this exception when running", e);
s_logger.warn("Caught this exception when running.", e);
}
return null;
}

View File

@ -103,6 +103,11 @@ public class SqlGenerator {
for (Field field : fields) {
field.setAccessible(true);
TableGenerator tg = field.getAnnotation(TableGenerator.class);
if (tg != null) {
_generators.put(field.getName(), tg);
}
if (!DbUtil.isPersistable(field)) {
continue;
}
@ -123,11 +128,6 @@ public class SqlGenerator {
continue;
}
TableGenerator tg = field.getAnnotation(TableGenerator.class);
if (tg != null) {
_generators.put(field.getName(), tg);
}
Attribute attr = new Attribute(clazz, overrides, field, tableName, embedded, isId);
if (attr.isId()) {

View File

@ -36,4 +36,8 @@ public class CloudRuntimeException extends RuntimeException {
public CloudRuntimeException(String message, Throwable th) {
super(message, th);
}
protected CloudRuntimeException() {
super();
}
}

View File

@ -604,6 +604,11 @@ public class NetUtils {
return long2Ip(numericNetmask);
}
public static String cidr2Netmask(String cidr) {
String[] tokens = cidr.split("\\/");
return getCidrNetmask(Integer.parseInt(tokens[1]));
}
public static long getCidrSize(String netmask) {
long ip = ip2Long(netmask);
int count = 0;