CS-15217: Security: Malicious user is able to get the size of the cloud by enumerating IDs

Description:

	Removing more DB IDs from exception messages.
This commit is contained in:
Vijayendra Bhamidipati 2012-07-25 18:39:48 -04:00
parent f6041de179
commit a0fa53ecd8
23 changed files with 3262 additions and 3214 deletions

View File

@ -120,7 +120,7 @@ public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd {
public long getEntityOwnerId() {
LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getLbRuleId());
if (lb == null) {
throw new InvalidParameterValueException("Unable to find loadbalancer from lbRuleId=" + getLbRuleId());
throw new InvalidParameterValueException("Unable to find loadbalancer by lbRuleId", null);
}
return lb.getAccountId();
}

View File

@ -156,7 +156,7 @@ public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd {
for (String keyValue : keyValues) { // keyValue == "hostid=123"
String[] keyAndValue = keyValue.split("="); // keyValue = hostid, 123
if (keyAndValue.length != 2) {
throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue);
throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue, null);
}
String paramName = keyAndValue[0]; // hostid
String paramValue = keyAndValue[1]; // 123

View File

@ -92,7 +92,7 @@ public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResources
@Override
public void execute() {
if(id != null && (loadBalancerId != null || profileId != null || policyId != null))
throw new InvalidParameterValueException("When id is specified other parameters need not be specified");
throw new InvalidParameterValueException("When id is specified other parameters need not be specified", null);
List<? extends AutoScaleVmGroup> autoScaleGroups = _autoScaleService.listAutoScaleVmGroups(this);
ListResponse<AutoScaleVmGroupResponse> response = new ListResponse<AutoScaleVmGroupResponse>();

View File

@ -12,6 +12,7 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.baremetal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -44,6 +45,7 @@ import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceStateAdapter;
import com.cloud.resource.ServerResource;
import com.cloud.resource.UnableDeleteHostException;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
@ -58,192 +60,195 @@ import com.cloud.vm.dao.UserVmDao;
@Local(value = {ExternalDhcpManager.class})
public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceStateAdapter {
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class);
protected String _name;
@Inject DataCenterDao _dcDao;
@Inject HostDao _hostDao;
@Inject AgentManager _agentMgr;
@Inject HostPodDao _podDao;
@Inject UserVmDao _userVmDao;
@Inject ResourceManager _resourceMgr;
@Inject NicDao _nicDao;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
return true;
}
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalDhcpManagerImpl.class);
protected String _name;
@Inject DataCenterDao _dcDao;
@Inject HostDao _hostDao;
@Inject AgentManager _agentMgr;
@Inject HostPodDao _podDao;
@Inject UserVmDao _userVmDao;
@Inject ResourceManager _resourceMgr;
@Inject NicDao _nicDao;
@Override
public boolean start() {
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this);
return true;
}
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
protected String getDhcpServerGuid(String zoneId, String name, String ip) {
return zoneId + "-" + name + "-" + ip;
}
@Override @DB
public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Could not find pod with ID: " + podId);
}
List<HostVO> dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId);
if (dhcps.size() != 0) {
throw new InvalidParameterValueException("Already had a DHCP server in Pod: " + podId + " zone: " + zoneId);
}
String ipAddress = url;
String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress);
Map params = new HashMap<String, String>();
params.put("type", type);
params.put("zone", Long.toString(zoneId));
params.put("pod", podId.toString());
params.put("ip", ipAddress);
params.put("username", username);
params.put("password", password);
params.put("guid", guid);
params.put("pod", Long.toString(podId));
params.put("gateway", pod.getGateway());
String dns = zone.getDns1();
if (dns == null) {
dns = zone.getDns2();
}
params.put("dns", dns);
ServerResource resource = null;
try {
if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) {
resource = new DnsmasqResource();
resource.configure("Dnsmasq resource", params);
} else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) {
resource = new DhcpdResource();
resource.configure("Dhcpd resource", params);
} else {
throw new CloudRuntimeException("Unsupport DHCP server " + type);
}
} catch (Exception e) {
s_logger.debug(e);
throw new CloudRuntimeException(e.getMessage());
}
Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params);
if (dhcpServer == null) {
throw new CloudRuntimeException("Cannot add external Dhcp server as a host");
}
Transaction txn = Transaction.currentTxn();
@Override
public String getName() {
return _name;
}
protected String getDhcpServerGuid(String zoneId, String name, String ip) {
return zoneId + "-" + name + "-" + ip;
}
@Override @DB
public Host addDhcpServer(Long zoneId, Long podId, String type, String url, String username, String password) {
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Could not find pod by ID", null);
}
List<HostVO> dhcps = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.ExternalDhcp, null, podId, zoneId);
if (dhcps.size() != 0) {
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(pod, podId, "podId"));
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("Already had a DHCP server in Pod with specified podId in zone with specified zoneId", idList);
}
String ipAddress = url;
String guid = getDhcpServerGuid(Long.toString(zoneId) + "-" + Long.toString(podId), "ExternalDhcp", ipAddress);
Map params = new HashMap<String, String>();
params.put("type", type);
params.put("zone", Long.toString(zoneId));
params.put("pod", podId.toString());
params.put("ip", ipAddress);
params.put("username", username);
params.put("password", password);
params.put("guid", guid);
params.put("pod", Long.toString(podId));
params.put("gateway", pod.getGateway());
String dns = zone.getDns1();
if (dns == null) {
dns = zone.getDns2();
}
params.put("dns", dns);
ServerResource resource = null;
try {
if (type.equalsIgnoreCase(DhcpServerType.Dnsmasq.getName())) {
resource = new DnsmasqResource();
resource.configure("Dnsmasq resource", params);
} else if (type.equalsIgnoreCase(DhcpServerType.Dhcpd.getName())) {
resource = new DhcpdResource();
resource.configure("Dhcpd resource", params);
} else {
throw new CloudRuntimeException("Unsupport DHCP server " + type);
}
} catch (Exception e) {
s_logger.debug(e);
throw new CloudRuntimeException(e.getMessage());
}
Host dhcpServer = _resourceMgr.addHost(zoneId, resource, Host.Type.ExternalDhcp, params);
if (dhcpServer == null) {
throw new CloudRuntimeException("Cannot add external Dhcp server as a host");
}
Transaction txn = Transaction.currentTxn();
txn.start();
pod.setExternalDhcp(true);
_podDao.update(pod.getId(), pod);
txn.commit();
return dhcpServer;
}
@Override
public DhcpServerResponse getApiResponse(Host dhcpServer) {
DhcpServerResponse response = new DhcpServerResponse();
response.setId(dhcpServer.getId());
return response;
}
private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) {
Long vmId = nic.getVmId();
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) {
s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry");
return;
}
List<HostVO> servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn());
if (servers.size() != 1) {
throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn()
+ " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size());
}
HostVO pxeServer = servers.get(0);
cmd.setNextServer(pxeServer.getPrivateIpAddress());
s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId());
}
@Override
public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> profile, DeployDestination dest,
ReservationContext context) throws ResourceUnavailableException {
Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn();
Long podId = profile.getVirtualMachine().getPodIdToDeployIn();
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId);
if (hosts.size() == 0) {
throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId);
}
if (hosts.size() > 1) {
throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId);
}
HostVO h = hosts.get(0);
String dns = nic.getDns1();
if (dns == null) {
dns = nic.getDns2();
}
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway());
String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName());
//prepareBareMetalDhcpEntry(nic, dhcpCommand);
try {
Answer ans = _agentMgr.send(h.getId(), dhcpCommand);
if (ans.getResult()) {
s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()));
return true;
} else {
s_logger.debug(errMsg + " " + ans.getDetails());
throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId);
}
} catch (Exception e) {
s_logger.debug(errMsg, e);
throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId);
}
}
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
return dhcpServer;
}
@Override
@Override
public DhcpServerResponse getApiResponse(Host dhcpServer) {
DhcpServerResponse response = new DhcpServerResponse();
response.setId(dhcpServer.getId());
return response;
}
private void prepareBareMetalDhcpEntry(NicProfile nic, DhcpEntryCommand cmd) {
Long vmId = nic.getVmId();
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null || vm.getHypervisorType() != HypervisorType.BareMetal) {
s_logger.debug("VM " + vmId + " is not baremetal machine, skip preparing baremetal DHCP entry");
return;
}
List<HostVO> servers = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.PxeServer, null, vm.getPodIdToDeployIn(), vm.getDataCenterIdToDeployIn());
if (servers.size() != 1) {
throw new CloudRuntimeException("Wrong number of PXE server found in zone " + vm.getDataCenterIdToDeployIn()
+ " Pod " + vm.getPodIdToDeployIn() + ", number is " + servers.size());
}
HostVO pxeServer = servers.get(0);
cmd.setNextServer(pxeServer.getPrivateIpAddress());
s_logger.debug("Set next-server to " + pxeServer.getPrivateIpAddress() + " for VM " + vm.getId());
}
@Override
public boolean addVirtualMachineIntoNetwork(Network network, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> profile, DeployDestination dest,
ReservationContext context) throws ResourceUnavailableException {
Long zoneId = profile.getVirtualMachine().getDataCenterIdToDeployIn();
Long podId = profile.getVirtualMachine().getPodIdToDeployIn();
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Type.ExternalDhcp, null, podId, zoneId);
if (hosts.size() == 0) {
throw new CloudRuntimeException("No external Dhcp found in zone " + zoneId + " pod " + podId);
}
if (hosts.size() > 1) {
throw new CloudRuntimeException("Something wrong, more than 1 external Dhcp found in zone " + zoneId + " pod " + podId);
}
HostVO h = hosts.get(0);
String dns = nic.getDns1();
if (dns == null) {
dns = nic.getDns2();
}
DhcpEntryCommand dhcpCommand = new DhcpEntryCommand(nic.getMacAddress(), nic.getIp4Address(), profile.getVirtualMachine().getHostName(), dns, nic.getGateway());
String errMsg = String.format("Set dhcp entry on external DHCP %1$s failed(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName());
//prepareBareMetalDhcpEntry(nic, dhcpCommand);
try {
Answer ans = _agentMgr.send(h.getId(), dhcpCommand);
if (ans.getResult()) {
s_logger.debug(String.format("Set dhcp entry on external DHCP %1$s successfully(ip=%2$s, mac=%3$s, vmname=%4$s)",
h.getPrivateIpAddress(), nic.getIp4Address(), nic.getMacAddress(), profile.getVirtualMachine().getHostName()));
return true;
} else {
s_logger.debug(errMsg + " " + ans.getDetails());
throw new ResourceUnavailableException(errMsg, DataCenter.class, zoneId);
}
} catch (Exception e) {
s_logger.debug(errMsg, e);
throw new ResourceUnavailableException(errMsg + e.getMessage(), DataCenter.class, zoneId);
}
}
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
}
@Override
public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
List<String> hostTags) {
if (!(startup[0] instanceof StartupExternalDhcpCommand)) {
return null;
}
host.setType(Host.Type.ExternalDhcp);
return host;
}
@Override
@Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
// TODO Auto-generated method stub
return null;
// TODO Auto-generated method stub
return null;
}
}

View File

@ -224,7 +224,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
RulesManager _rulesMgr;
@Inject
IPAddressDao _ipAddressDao;
private ConsoleProxyListener _listener;
private ServiceOfferingVO _serviceOffering;
@ -257,7 +257,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
private Map<Long, ZoneHostInfo> _zoneHostInfoMap; // map <zone id, info about running host in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneProxyCountMap; // map <zone id, info about proxy VMs count in zone>
private Map<Long, ConsoleProxyLoadInfo> _zoneVmCountMap; // map <zone id, info about running VMs count in zone>
private String _hashKey;
private final GlobalLock _allocProxyLock = GlobalLock.getInternLock(getAllocProxyLockName());
@ -879,26 +879,26 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
}
if(!cmd.isReauthenticating()) {
String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
}
if (!ticket.equals(ticketInUrl)) {
Date now = new Date();
// considering of minute round-up
String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket);
}
if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + ","
+ minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
}
String ticket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId());
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 1 minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + ticket);
}
if (!ticket.equals(ticketInUrl)) {
Date now = new Date();
// considering of minute round-up
String minuteEarlyTicket = ConsoleProxyServlet.genAccessTicket(cmd.getHost(), cmd.getPort(), cmd.getSid(), cmd.getVmId(), new Date(now.getTime() - 60 * 1000));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Console authentication. Ticket in 2-minute boundary for " + cmd.getHost() + ":" + cmd.getPort() + "-" + cmd.getVmId() + " is " + minuteEarlyTicket);
}
if (!minuteEarlyTicket.equals(ticketInUrl)) {
s_logger.error("Access ticket expired or has been modified. vmId: " + cmd.getVmId() + "ticket in URL: " + ticketInUrl + ", tickets to check against: " + ticket + ","
+ minuteEarlyTicket);
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
}
}
if (cmd.getVmId() != null && cmd.getVmId().isEmpty()) {
@ -935,38 +935,38 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
s_logger.warn("sid " + sid + " in url does not match stored sid " + vm.getVncPassword());
return new ConsoleAccessAuthenticationAnswer(cmd, false);
}
if(cmd.isReauthenticating()) {
ConsoleAccessAuthenticationAnswer authenticationAnswer = new ConsoleAccessAuthenticationAnswer(cmd, true);
authenticationAnswer.setReauthenticating(true);
s_logger.info("Re-authentication request, ask host " + vm.getHostId() + " for new console info");
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new
GetVncPortCommand(vm.getId(), vm.getInstanceName()));
GetVncPortAnswer answer = (GetVncPortAnswer) _agentMgr.easySend(vm.getHostId(), new
GetVncPortCommand(vm.getId(), vm.getInstanceName()));
if (answer != null && answer.getResult()) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
Ternary<String, String, String> parsedHostInfo = ConsoleProxyServlet.parseHostInfo(answer.getAddress());
if(parsedHostInfo.second() != null && parsedHostInfo.third() != null) {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", tunnel url: " + parsedHostInfo.second()
+ ", tunnel session: " + parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else {
+ ", tunnel session: " + parsedHostInfo.third());
authenticationAnswer.setTunnelUrl(parsedHostInfo.second());
authenticationAnswer.setTunnelSession(parsedHostInfo.third());
} else {
s_logger.info("Re-authentication result. vm: " + vm.getId() + ", host address: " + parsedHostInfo.first()
+ ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort());
}
+ ", port: " + answer.getPort());
authenticationAnswer.setHost(parsedHostInfo.first());
authenticationAnswer.setPort(answer.getPort());
}
} else {
s_logger.warn("Re-authentication request failed");
authenticationAnswer.setSuccess(false);
authenticationAnswer.setSuccess(false);
}
return authenticationAnswer;
}
@ -1383,7 +1383,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
result = result && _hostDao.remove(host.getId());
}
}
return result;
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to expunge " + proxy, e);
@ -1497,7 +1497,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
_itMgr.registerGuru(VirtualMachine.Type.ConsoleProxy, this);
boolean useLocalStorage = Boolean.parseBoolean(configs.get(Config.SystemVMUseLocalStorage.key()));
//check if there is a default service offering configured
String cpvmSrvcOffIdStr = configs.get(Config.ConsoleProxyServiceOffering.key());
if (cpvmSrvcOffIdStr != null) {
@ -1538,7 +1538,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
// verify parameters
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyId);
if (proxy == null) {
throw new InvalidParameterValueException("unable to find a console proxy with id " + proxyId);
throw new InvalidParameterValueException("unable to find a console proxy by id", null);
}
return destroyProxy(proxyId);
@ -1981,7 +1981,7 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
sc.addAnd(sc.getEntity().getName(), Op.EQ, name);
return sc.find();
}
public String getHashKey() {
// although we may have race conditioning here, database transaction serialization should
// give us the same key
@ -2007,15 +2007,15 @@ public class ConsoleProxyManagerImpl implements ConsoleProxyManager, ConsoleProx
throw new UnsupportedOperationException("Unplug nic is not supported for vm of type " + vm.getType());
}
@Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
}
@Override
public void prepareStop(VirtualMachineProfile<ConsoleProxyVO> profile) {
}
@Override
public boolean recreateNeeded(
VirtualMachineProfile<ConsoleProxyVO> profile, long hostId,
Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean recreateNeeded(
VirtualMachineProfile<ConsoleProxyVO> profile, long hostId,
Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,41 +12,38 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.agent.api.StartupCommand;
import com.cloud.api.ApiConstants;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.ClusterVSMMapVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.ClusterVSMMapDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.DetailVO;
import com.cloud.exception.ResourceInUseException;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.vmware.manager.VmwareManager;
import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
import com.cloud.network.dao.PortProfileDao;
import com.cloud.resource.ResourceManager;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.network.dao.CiscoNexusVSMDeviceDao;
import com.cloud.network.dao.PortProfileDao;
import com.cloud.exception.ResourceInUseException;
import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper;
public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
@Inject
@Inject
CiscoNexusVSMDeviceDao _ciscoNexusVSMDeviceDao;
@Inject
ClusterDao _clusterDao;
@ -54,8 +51,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
ClusterVSMMapDao _clusterVSMDao;
@Inject
ResourceManager _resourceMgr;
@Inject
VmwareManager _vmwareMgr;
@Inject
VmwareManager _vmwareMgr;
@Inject
ClusterDetailsDao _clusterDetailsDao;
@Inject
@ -63,126 +60,129 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
@Inject
PortProfileDao _ppDao;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalLoadBalancerDeviceManagerImpl.class);
@DB
//public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, ServerResource resource, String vsmName) {
public CiscoNexusVSMDeviceVO addCiscoNexusVSM(long clusterId, String ipaddress, String username, String password, String vCenterIpaddr, String vCenterDcName) {
// In this function, we associate this VSM with each host
// in the clusterId specified.
// In this function, we associate this VSM with each host
// in the clusterId specified.
// First check if the cluster is of type vmware. If not,
// throw an exception. VSMs are tightly integrated with vmware clusters.
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null) {
throw new InvalidParameterValueException("Cluster with specified ID not found!");
}
if (cluster.getHypervisorType() != HypervisorType.VMware) {
InvalidParameterValueException ex = new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster");
throw ex;
}
// First check if the cluster is of type vmware. If not,
// throw an exception. VSMs are tightly integrated with vmware clusters.
// Next, check if the cluster already has a VSM associated with it.
// If so, throw an exception disallowing this operation. The user must first
// delete the current VSM and then only attempt to add the new one.
if (_clusterVSMDao.findByClusterId(clusterId) != null) {
// We can't have two VSMs for the same cluster. Throw exception.
throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.");
}
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null) {
throw new InvalidParameterValueException("Cluster could not be found by id", null);
}
if (cluster.getHypervisorType() != HypervisorType.VMware) {
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(cluster, clusterId, "clusterId"));
throw new InvalidParameterValueException("Cluster with specified id is not a VMWare hypervisor cluster", idList);
}
// TODO: Confirm whether we should be checking for VSM reachability here.
// Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to
// the VSM.
//NetconfHelper (String ip, String username, String password)
// Next, check if the cluster already has a VSM associated with it.
// If so, throw an exception disallowing this operation. The user must first
// delete the current VSM and then only attempt to add the new one.
NetconfHelper netconfClient;
try {
netconfClient = new NetconfHelper(ipaddress, username, password);
} catch(CloudRuntimeException e) {
String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (_clusterVSMDao.findByClusterId(clusterId) != null) {
// We can't have two VSMs for the same cluster. Throw exception.
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(cluster, clusterId, "clusterId"));
throw new InvalidParameterValueException("Cluster with specified id already has a VSM tied to it. Please remove that first and retry the operation.", idList);
}
// Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows.
netconfClient.disconnect();
// TODO: Confirm whether we should be checking for VSM reachability here.
// Now, go ahead and associate the cluster with this VSM.
// First, check if VSM already exists in the table "virtual_supervisor_module".
// If it's not there already, create it.
// If it's there already, return success.
// TODO - Right now, we only check if the ipaddress matches for both requests.
// We must really check whether every field of the VSM matches. Anyway, the
// advantage of our approach for now is that existing infrastructure using
// the existing VSM won't be affected if the new request to add the VSM
// assumed different information on the VSM (mgmt vlan, username, password etc).
CiscoNexusVSMDeviceVO VSMObj;
try {
VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress);
} catch (Exception e) {
throw new CloudRuntimeException(e.getMessage());
}
// Next, check if this VSM is reachable. Use the XML-RPC VSM API Java bindings to talk to
// the VSM.
//NetconfHelper (String ip, String username, String password)
NetconfHelper netconfClient;
try {
netconfClient = new NetconfHelper(ipaddress, username, password);
} catch(CloudRuntimeException e) {
String msg = "Failed to connect to Nexus VSM " + ipaddress + " with credentials of user " + username;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
// Disconnect from the VSM. A VSM has a default of 8 maximum parallel connections that it allows.
netconfClient.disconnect();
// Now, go ahead and associate the cluster with this VSM.
// First, check if VSM already exists in the table "virtual_supervisor_module".
// If it's not there already, create it.
// If it's there already, return success.
// TODO - Right now, we only check if the ipaddress matches for both requests.
// We must really check whether every field of the VSM matches. Anyway, the
// advantage of our approach for now is that existing infrastructure using
// the existing VSM won't be affected if the new request to add the VSM
// assumed different information on the VSM (mgmt vlan, username, password etc).
CiscoNexusVSMDeviceVO VSMObj;
try {
VSMObj = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress);
} catch (Exception e) {
throw new CloudRuntimeException(e.getMessage());
}
if (VSMObj == null) {
// Create the VSM record. For now, we aren't using the vsmName field.
VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(VSMObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id.
long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId();
ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_clusterVSMDao.persist(connectorObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Now, get a list of all the ESXi servers in this cluster.
// This is effectively a select * from host where cluster_id=clusterId;
// All ESXi servers are stored in the host table, and their resource
// type is vmwareresource.
if (VSMObj == null) {
// Create the VSM record. For now, we aren't using the vsmName field.
VSMObj = new CiscoNexusVSMDeviceVO(ipaddress, username, password);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(VSMObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// At this stage, we have a VSM record for sure. Connect the VSM to the cluster Id.
long vsmId = _ciscoNexusVSMDeviceDao.getVSMbyIpaddress(ipaddress).getId();
ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsmId);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_clusterVSMDao.persist(connectorObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Now, get a list of all the ESXi servers in this cluster.
// This is effectively a select * from host where cluster_id=clusterId;
// All ESXi servers are stored in the host table, and their resource
// type is vmwareresource.
//List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
//TODO: Activate the code below if we make the Nexus VSM a separate resource.
// Iterate through each of the hosts in this list. Each host has a host id.
// Given this host id, we can reconfigure the in-memory resource representing
// the host via the agent manager. Thus we inject VSM related information
// into each host's resource. Also, we first configure each resource's
// entries in the database to contain this VSM information before the injection.
//for (HostVO host : hosts) {
// Create a host details VO object and write it out for this hostid.
//Long hostid = new Long(vsmId);
//DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString());
//Transaction tx = Transaction.currentTxn();
//try {
//tx.start();
//_hostDetailDao.persist(vsmDetail);
//tx.commit();
//} catch (Exception e) {
//tx.rollback();
//throw new CloudRuntimeException(e.getMessage());
//}
// Create a host details VO object and write it out for this hostid.
//Long hostid = new Long(vsmId);
//DetailVO vsmDetail = new DetailVO(host.getId(), "vsmId", hostid.toString());
//Transaction tx = Transaction.currentTxn();
//try {
//tx.start();
//_hostDetailDao.persist(vsmDetail);
//tx.commit();
//} catch (Exception e) {
//tx.rollback();
//throw new CloudRuntimeException(e.getMessage());
//}
//}
// Reconfigure the resource.
//Map hostDetails = new HashMap<String, String>();
@ -191,40 +191,40 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
//hostDetails.put(ApiConstants.USERNAME, username);
//hostDetails.put(ApiConstants.PASSWORD, password);
//_agentMrg.send(host.getId(), )
return VSMObj;
}
@DB
public boolean deleteCiscoNexusVSM(long vsmId) throws ResourceInUseException {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
// This entry is already not present. Return success.
return true;
// This entry is already not present. Return success.
return true;
}
// First, check whether this VSM is part of any non-empty cluster.
// Search ClusterVSMMap's table for a list of clusters using this vsmId.
List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsmId);
if (clusterList != null) {
for (ClusterVSMMapVO record : clusterList) {
// If this cluster id has any hosts in it, fail this operation.
Long clusterId = record.getClusterId();
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
for (Host host: hosts) {
if (host.getType() == Host.Type.Routing) {
s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
}
}
}
}
for (ClusterVSMMapVO record : clusterList) {
// If this cluster id has any hosts in it, fail this operation.
Long clusterId = record.getClusterId();
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
for (Host host: hosts) {
if (host.getType() == Host.Type.Routing) {
s_logger.info("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
throw new ResourceInUseException("Non-empty cluster with id" + clusterId + "still has a host that uses this VSM. Please empty the cluster first");
}
}
}
}
}
// Iterate through the cluster list again, this time, delete the VSM.
Transaction txn = Transaction.currentTxn();
try {
@ -237,8 +237,8 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
// to notify any resources or remove host details.
txn.commit();
} catch (Exception e) {
s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete VSM");
s_logger.info("Caught exception when trying to delete VSM record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete VSM");
}
return true;
}
@ -247,67 +247,67 @@ public abstract class CiscoNexusVSMDeviceManagerImpl extends AdapterBase {
public CiscoNexusVSMDeviceVO enableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified");
throw new InvalidParameterValueException("Invalid vsm Id specified", null);
}
// Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled) {
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
return cisconexusvsm;
}
@DB
public CiscoNexusVSMDeviceVO disableCiscoNexusVSM(long vsmId) {
CiscoNexusVSMDeviceVO cisconexusvsm = _ciscoNexusVSMDeviceDao.findById(vsmId);
if (cisconexusvsm == null) {
throw new InvalidParameterValueException("Invalid vsm Id specified");
throw new InvalidParameterValueException("Invalid vsm Id specified", null);
}
// Else, check if this db record shows that this VSM is enabled or not.
if (cisconexusvsm.getvsmDeviceState() == CiscoNexusVSMDeviceVO.VSMDeviceState.Enabled) {
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
// it's currently disabled. So change it to enabled and write it out to the db.
cisconexusvsm.setVsmDeviceState(CiscoNexusVSMDeviceVO.VSMDeviceState.Disabled);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_ciscoNexusVSMDeviceDao.persist(cisconexusvsm);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
}
return cisconexusvsm;
}
@DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyVSMId(long vsmId) {
return _ciscoNexusVSMDeviceDao.findById(vsmId);
return _ciscoNexusVSMDeviceDao.findById(vsmId);
}
@DB
public CiscoNexusVSMDeviceVO getCiscoVSMbyClusId(long clusterId) {
ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId);
if (mapVO == null) {
s_logger.info("Couldn't find a VSM associated with the specified cluster Id");
return null;
}
// Else, pull out the VSM associated with the VSM id in mapVO.
CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId());
return result;
ClusterVSMMapVO mapVO = _clusterVSMDao.findByClusterId(clusterId);
if (mapVO == null) {
s_logger.info("Couldn't find a VSM associated with the specified cluster Id");
return null;
}
// Else, pull out the VSM associated with the VSM id in mapVO.
CiscoNexusVSMDeviceVO result = _ciscoNexusVSMDeviceDao.findById(mapVO.getVsmId());
return result;
}
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;

View File

@ -26,7 +26,6 @@ import com.cloud.agent.AgentManager;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupExternalFirewallCommand;
import com.cloud.agent.api.StartupExternalLoadBalancerCommand;
import com.cloud.agent.api.routing.IpAssocCommand;
import com.cloud.agent.api.routing.NetworkElementCommand;
import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand;
@ -55,10 +54,7 @@ import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao;
import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState;
import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice;
import com.cloud.network.Network.Capability;
import com.cloud.network.Network.Service;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.ExternalFirewallDeviceDao;
import com.cloud.network.dao.IPAddressDao;
@ -151,12 +147,12 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null) ) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter.");
" server resource, zone id/physical network id) is not specified or a valid parameter.", null);
}
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
zoneId = pNetwork.getDataCenterId();
@ -174,7 +170,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
uri = new URI(url);
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -205,7 +201,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
txn.start();
boolean dedicatedUse = (configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.FIREWALL_DEVICE_DEDICATED)) : false;
long capacity = NumbersUtil.parseLong((String)configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0);
long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.FIREWALL_DEVICE_CAPACITY), 0);
if (capacity == 0) {
capacity = _defaultFwCapacity;
}
@ -229,7 +225,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
public boolean deleteExternalFirewall(Long hostId) {
HostVO externalFirewall = _hostDao.findById(hostId);
if (externalFirewall == null) {
throw new InvalidParameterValueException("Could not find an external firewall with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an external firewall by ID", null);
}
try {
@ -252,11 +248,11 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
if ((pNetwork == null) || (fwNetworkDevice == null)) {
throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid.");
throw new InvalidParameterValueException("Atleast one of ther required parameter physical networkId, device name is missing or invalid.", null);
}
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(), fwNetworkDevice.getNetworkServiceProvder());
@ -270,7 +266,8 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
}
return firewallHosts;
}
@Override
public ExternalFirewallDeviceVO getExternalFirewallForNetwork(Network network) {
NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId());
if (fwDeviceForNetwork != null) {
@ -366,17 +363,17 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
if (fwDeviceVO == null) {
s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." +
" Either network implement failed half way through or already network shutdown is completed.");
" Either network implement failed half way through or already network shutdown is completed.");
return true;
}
externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
}
Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId());
NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
boolean sharedSourceNat = offering.getSharedSourceNat();
IPAddressVO sourceNatIp = null;
if (!sharedSourceNat) {
// Get the source NAT IP address for this account
@ -385,7 +382,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (sourceNatIps.size() != 1) {
String errorMsg = "External firewall was unable to find the source NAT IP address for account "
+ account.getAccountName();
+ account.getAccountName();
s_logger.error(errorMsg);
return true;
} else {
@ -431,18 +428,18 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
// Insert a new NIC for this guest network to reserve the gateway address
savePlaceholderNic(network, network.getGateway());
}
// Delete any mappings used for inline external load balancers in this network
List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(network.getId());
for (NicVO nic : nicsInNetwork) {
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId());
if (mapping != null) {
_nicDao.expunge(mapping.getNicId());
_inlineLoadBalancerNicMapDao.expunge(mapping.getId());
}
}
String action = add ? "implemented" : "shut down";
s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag);
@ -527,39 +524,39 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (externalFirewall == null) {
return false;
}
// Create/delete VPN
IpAddress ip = _networkMgr.getIp(vpn.getServerAddressId());
// Mask the IP range with the network's VLAN tag
String[] ipRange = vpn.getIpRange().split("-");
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
int vlanTag = Integer.parseInt(network.getBroadcastUri().getHost());
int offset = getVlanOffset(network.getPhysicalNetworkId(), vlanTag);
int cidrSize = getGloballyConfiguredCidrSize();
for (int i = 0; i < 2; i++) {
ipRange[i] = NetUtils.long2Ip((NetUtils.ip2Long(ipRange[i]) & 0xff000000) | (offset << (32 - cidrSize)));
}
String maskedIpRange = ipRange[0] + "-" + ipRange[1];
RemoteAccessVpnCfgCommand createVpnCmd = new RemoteAccessVpnCfgCommand(create, ip.getAddress().addr(), vpn.getLocalIp(), maskedIpRange, vpn.getIpsecPresharedKey());
createVpnCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId()));
createVpnCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(externalFirewall.getId(), createVpnCmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "External firewall was unable to create a remote access VPN in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
}
// Add/delete users
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
return manageRemoteAccessVpnUsers(network, vpn, vpnUsers);
}
public boolean manageRemoteAccessVpnUsers(Network network, RemoteAccessVpn vpn, List<? extends VpnUser> vpnUsers) throws ResourceUnavailableException {
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
@ -567,31 +564,31 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
if (externalFirewall == null) {
return false;
}
List<VpnUser> addUsers = new ArrayList<VpnUser>();
List<VpnUser> removeUsers = new ArrayList<VpnUser>();
for (VpnUser user : vpnUsers) {
if (user.getState() == VpnUser.State.Add ||
user.getState() == VpnUser.State.Active) {
user.getState() == VpnUser.State.Active) {
addUsers.add(user);
} else if (user.getState() == VpnUser.State.Revoke) {
removeUsers.add(user);
}
}
VpnUsersCfgCommand addUsersCmd = new VpnUsersCfgCommand(addUsers, removeUsers);
addUsersCmd.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, String.valueOf(network.getAccountId()));
addUsersCmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(externalFirewall.getId(), addUsersCmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
String details = (answer != null) ? answer.getDetails() : "details unavailable";
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String msg = "External firewall was unable to add remote access users in zone " + zone.getName() + " due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId());
}
return true;
}
@ -608,7 +605,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
int lowestVlanTag = Integer.valueOf(vlanRange[0]);
return vlanTag - lowestVlanTag;
}
private NicVO savePlaceholderNic(Network network, String ipAddress) {
NicVO nic = new NicVO(null, null, network.getId(), null);
nic.setIp4Address(ipAddress);
@ -616,7 +613,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl
nic.setState(State.Reserved);
return _nicDao.persist(nic);
}
public int getGloballyConfiguredCidrSize() {
try {
String globalVlanBits = _configDao.getValue(Config.GuestVlanBits.key());

View File

@ -76,7 +76,6 @@ import com.cloud.network.dao.PhysicalNetworkDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderDao;
import com.cloud.network.dao.PhysicalNetworkServiceProviderVO;
import com.cloud.network.lb.LoadBalancingRule;
import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup;
import com.cloud.network.lb.LoadBalancingRule.LbDestination;
import com.cloud.network.resource.CreateLoadBalancerApplianceAnswer;
import com.cloud.network.resource.DestroyLoadBalancerApplianceAnswer;
@ -184,12 +183,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
if ((ntwkDevice == null) || (url == null) || (username == null) || (resource == null) || (password == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameters (url, username, password," +
" server resource, zone id/physical network id) is not specified or a valid parameter.");
" server resource, zone id/physical network id) is not specified or a valid parameter.", null);
}
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
zoneId = pNetwork.getDataCenterId();
@ -207,7 +206,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
uri = new URI(url);
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -236,7 +235,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false;
boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false;
long capacity = NumbersUtil.parseLong((String) configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0);
if (capacity == 0) {
capacity = _defaultLbCapacity;
}
@ -264,7 +263,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
public boolean deleteExternalLoadBalancer(long hostId) {
HostVO externalLoadBalancer = _hostDao.findById(hostId);
if (externalLoadBalancer == null) {
throw new InvalidParameterValueException("Could not find an external load balancer with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an external load balancer by ID", null);
}
DetailVO lbHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.LOAD_BALANCER_DEVICE_ID);
@ -314,7 +313,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
pNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if ((pNetwork == null) || (lbNetworkDevice == null)) {
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.");
throw new InvalidParameterValueException("Atleast one of the required parameter physical networkId, device name is invalid.", null);
}
PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(pNetwork.getId(),

View File

@ -537,12 +537,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
return ipToReturn;
}
@Override
public PublicIp assignVpnGatewayIpAddress(long dcId, Account owner, long vpcId) throws InsufficientAddressCapacityException, ConcurrentOperationException {
return assignDedicateIpAddress(owner, null, vpcId, dcId, false);
}
@DB
public PublicIp assignDedicateIpAddress(Account owner, Long guestNtwkId, Long vpcId, long dcId, boolean isSourceNat)
@ -1143,7 +1143,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
public IPAddressVO associateIPToGuestNetwork(long ipId, long networkId, boolean releaseOnFailure)
throws ResourceAllocationException, ResourceUnavailableException,
InsufficientAddressCapacityException, ConcurrentOperationException {
InsufficientAddressCapacityException, ConcurrentOperationException {
Account caller = UserContext.current().getCaller();
Account owner = null;
@ -1467,7 +1467,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
offering.setState(NetworkOffering.State.Enabled);
_networkOfferingDao.update(offering.getId(), offering);
}
if (_networkOfferingDao.findByUniqueName(NetworkOffering.DefaultIsolatedNetworkOfferingForVpcNetworksNoLB) == null) {
//remove LB service
defaultVPCOffProviders.remove(Service.Lb);
@ -2282,7 +2282,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
@Override
public void releaseNic(VirtualMachineProfile<? extends VMInstanceVO> vmProfile, Nic nic)
throws ConcurrentOperationException, ResourceUnavailableException {
NicVO nicVO = _nicDao.findById(nic.getId());
releaseNic(vmProfile, nicVO);
}
@ -2356,7 +2356,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (broadcastUri != null) {
nic = _nicDao.findByNetworkIdInstanceIdAndBroadcastUri(networkId, vm.getId(), broadcastUri);
} else {
nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
nic = _nicDao.findByInstanceIdAndNetworkId(networkId, vm.getId());
}
NetworkVO network = _networksDao.findById(networkId);
Integer networkRate = getNetworkRate(network.getId(), vm.getId());
@ -3189,7 +3189,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
Filter searchFilter = new Filter(NetworkVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
if (forVpc != null) {
if (forVpc) {
sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
@ -4259,14 +4259,14 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
long physicalNetworkId = findPhysicalNetworkId(zoneId, requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
// Validate physical network
PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
throw new InvalidParameterValueException("Unable to find physical network by id, with tag: " +requiredOfferings.get(0).getTags(), null);
}
s_logger.debug("Creating network for account " + owner + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of createVlanIpRange process");
guestNetwork = createGuestNetwork(requiredOfferings.get(0).getId(), owner.getAccountName() + "-network"
@ -5300,7 +5300,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
txn.start();
// Create the new physical network in the database
long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRange, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
@ -6953,7 +6953,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (networkId == null) {
networkId = userIp.getAssociatedWithNetworkId();
}
NetworkVO network = _networksDao.findById(networkId);
NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
if (offering.getGuestType() != GuestType.Isolated) {
@ -7211,7 +7211,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (network.getVpcId() != null) {
throw new InvalidParameterValueException("Can't assign ip to the network directly when network belongs" +
" to VPC.Specify vpcId to associate ip address to VPC", null);
" to VPC.Specify vpcId to associate ip address to VPC", null);
}
return associateIPToGuestNetwork(ipId, networkId, true);
}
@ -7243,11 +7243,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
if (ipUsedInVpc(ip)) {
return;
}
if (ip == null || ip.getVpcId() == null) {
return;
}
s_logger.debug("Releasing VPC ip address " + ip + " from vpc network id=" + networkId);
long vpcId = ip.getVpcId();
@ -7388,41 +7388,41 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
return true;
}
@Override
public NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context,
VirtualMachineProfileImpl<VMInstanceVO> vmProfile, boolean prepare)
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException,
ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException {
VirtualMachine vm = vmProfile.getVirtualMachine();
NetworkVO networkVO = _networksDao.findById(network.getId());
DataCenter dc = _configMgr.getZone(network.getDataCenterId());
Host host = _hostDao.findById(vm.getHostId());
DeployDestination dest = new DeployDestination(dc, null, null, host);
NicProfile nic = getNicProfileForVm(network, requested, vm);
//1) allocate nic (if needed)
if (nic == null) {
int deviceId = _nicDao.countNics(vm.getId());
nic = allocateNic(requested, network, false,
deviceId, vmProfile).first();
if (nic == null) {
throw new CloudRuntimeException("Failed to allocate nic for vm " + vm + " in network " + network);
}
s_logger.debug("Nic is allocated successfully for vm " + vm + " in network " + network);
}
//2) prepare nic
if (prepare) {
nic = prepareNic(vmProfile, dest, context, nic.getId(), networkVO);
s_logger.debug("Nic is prepared successfully for vm " + vm + " in network " + network);
}
return nic;
}
@ -7445,5 +7445,5 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag
}
return nic;
}
}

View File

@ -101,7 +101,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
@Inject HostDetailsDao _detailsDao;
@Inject AccountManager _accountMgr;
@Inject NetworkDao _networksDao = null;
@Inject ResourceManager _resourceMgr;
@Inject ResourceManager _resourceMgr;
ScheduledExecutorService _executor;
int _networkStatsInterval;
String _TSinclZones;
@ -116,7 +116,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
DataCenterVO zone = _dcDao.findById(zoneId);
String zoneName;
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
} else {
zoneName = zone.getName();
}
@ -124,7 +124,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
List<HostVO> trafficMonitorsInZone = _resourceMgr.listAllHostsInOneZoneByType(Host.Type.TrafficMonitor, zoneId);
if (trafficMonitorsInZone.size() != 0) {
throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName);
throw new InvalidParameterValueException("Already added an traffic monitor in zone: " + zoneName, null);
}
URI uri;
@ -132,7 +132,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
uri = new URI(cmd.getUrl());
} catch (Exception e) {
s_logger.debug(e);
throw new InvalidParameterValueException(e.getMessage());
throw new InvalidParameterValueException(e.getMessage(), null);
}
String ipAddress = uri.getHost();
@ -161,13 +161,13 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
hostDetails.put("url", cmd.getUrl());
hostDetails.put("last_collection", ""+System.currentTimeMillis());
if(cmd.getInclZones() != null){
hostDetails.put("inclZones", cmd.getInclZones());
hostDetails.put("inclZones", cmd.getInclZones());
}
if(cmd.getExclZones() != null){
hostDetails.put("exclZones", cmd.getExclZones());
hostDetails.put("exclZones", cmd.getExclZones());
}
Host trafficMonitor = _resourceMgr.addHost(zoneId, resource, Host.Type.TrafficMonitor, hostDetails);
return trafficMonitor;
}
@ -182,12 +182,12 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
User caller = _accountMgr.getActiveUser(UserContext.current().getCallerUserId());
HostVO trafficMonitor = _hostDao.findById(hostId);
if (trafficMonitor == null) {
throw new InvalidParameterValueException("Could not find an traffic monitor with ID: " + hostId);
throw new InvalidParameterValueException("Could not find an traffic monitor by ID", null);
}
try {
if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) {
return true;
try {
if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) {
return true;
} else {
return false;
}
@ -225,7 +225,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
networkJoin.and("guestType", networkJoin.entity().getGuestType(), Op.EQ);
AllocatedIpSearch.join("network", networkJoin, AllocatedIpSearch.entity().getSourceNetworkId(), networkJoin.entity().getId(), JoinBuilder.JoinType.INNER);
AllocatedIpSearch.done();
_networkStatsInterval = NumbersUtil.parseInt(_configDao.getValue(Config.DirectNetworkStatsInterval.key()), 86400);
_TSinclZones = _configDao.getValue(Config.TrafficSentinelIncludeZones.key());
_TSexclZones = _configDao.getValue(Config.TrafficSentinelExcludeZones.key());
@ -241,7 +241,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
@Override
public boolean stop() {
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
_resourceMgr.unregisterResourceStateAdapter(this.getClass().getSimpleName());
return true;
}
@ -262,7 +262,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
private int _interval;
private long mgmtSrvrId = MacAddress.getMacAddress().toLong();
private final long mgmtSrvrId = MacAddress.getMacAddress().toLong();
protected DirectNetworkStatsListener(int interval) {
_interval = interval;
@ -324,7 +324,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
rightNow.add(Calendar.HOUR_OF_DAY, -2);
Date now = rightNow.getTime();
if(lastCollection.after(now)){
s_logger.debug("Current time is less than 2 hours after last collection time : " + lastCollection.toString() + ". Skipping direct network usage collection");
return false;
@ -376,7 +376,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
}
List<UserStatisticsVO> collectedStats = new ArrayList<UserStatisticsVO>();
//Get usage for Ips which were assigned for the entire duration
if(fullDurationIpUsage.size() > 0){
DirectNetworkUsageCommand cmd = new DirectNetworkUsageCommand(IpList, lastCollection, now, _TSinclZones, _TSexclZones);
@ -441,8 +441,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
}
if(collectedStats.size() == 0){
s_logger.debug("No new direct network stats. No need to persist");
return false;
s_logger.debug("No new direct network stats. No need to persist");
return false;
}
//Persist all the stats and last_collection time in a single transaction
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
@ -496,9 +496,9 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
s_logger.debug("Sending RecurringNetworkUsageCommand to " + agentId);
RecurringNetworkUsageCommand watch = new RecurringNetworkUsageCommand(_interval);
try {
_agentMgr.send(agentId, new Commands(watch), this);
_agentMgr.send(agentId, new Commands(watch), this);
} catch (AgentUnavailableException e) {
s_logger.debug("Can not process connect for host " + agentId, e);
s_logger.debug("Can not process connect for host " + agentId, e);
}
}
return;
@ -516,34 +516,34 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta
protected DirectNetworkStatsListener() {
}
}
@Override
@Override
public HostVO createHostVOForConnectedAgent(HostVO host, StartupCommand[] cmd) {
// TODO Auto-generated method stub
return null;
// TODO Auto-generated method stub
return null;
}
@Override
@Override
public HostVO createHostVOForDirectConnectAgent(HostVO host, StartupCommand[] startup, ServerResource resource, Map<String, String> details,
List<String> hostTags) {
if (!(startup[0] instanceof StartupTrafficMonitorCommand)) {
return null;
}
host.setType(Host.Type.TrafficMonitor);
return host;
}
@Override
@Override
public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException {
if(host.getType() != Host.Type.TrafficMonitor){
return null;
}
return new DeleteHostAnswer(true);
if(host.getType() != Host.Type.TrafficMonitor){
return null;
}
return new DeleteHostAnswer(true);
}
}

View File

@ -15,107 +15,107 @@ package com.cloud.network;
import org.apache.log4j.Logger;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.network.PortProfileVO.BindingType;
import com.cloud.network.PortProfileVO.PortType;
import com.cloud.network.dao.PortProfileDaoImpl;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
public class PortProfileManagerImpl {
private PortProfileDaoImpl _portProfileDao;
private final PortProfileDaoImpl _portProfileDao;
private static final org.apache.log4j.Logger s_logger = Logger.getLogger(PortProfileManagerImpl.class);
public PortProfileManagerImpl() {
_portProfileDao = new PortProfileDaoImpl();
_portProfileDao = new PortProfileDaoImpl();
}
@DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) {
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
if (_portProfileDao.findByName(portProfName) != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists");
}
// Check if the VSM id is a valid one.
// TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so,
// fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId?
// Else, go ahead and create the port profile.
PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType);
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
if (_portProfileDao.findByName(portProfName) != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null);
}
// Check if the VSM id is a valid one.
// Return the PortProfileVO object created.
// TODO: Should we also check whether a port profile for the specified vlanId already exists, and if so,
// fail this function? Do we want to enforce such a 1:1 mapping b/w port profile and vlanId?
// Else, go ahead and create the port profile.
PortProfileVO portProfileObj = new PortProfileVO(portProfName, vsmId, vlanId, pType, bType);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Return the PortProfileVO object created.
return portProfileObj;
}
@DB
public PortProfileVO addPortProfile(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) {
// In this function, we create a port profile record in the port_profile table.
// First, check if a port profile with the given name already exists. If it does, throw an exception.
PortProfileVO portProfileObj;
portProfileObj = _portProfileDao.findByName(portProfName);
if (portProfileObj != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists");
}
// In this function, we create a port profile record in the port_profile table.
// Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the
// range passed to this function. If so, throw an exception.
if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) {
s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's");
throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's");
}
// Else, go ahead and create the port profile.
portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType);
// First, check if a port profile with the given name already exists. If it does, throw an exception.
PortProfileVO portProfileObj;
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
portProfileObj = _portProfileDao.findByName(portProfName);
// Return the PortProfileVO object created.
if (portProfileObj != null) {
s_logger.info("Port Profile with specified name: " + portProfName + " already exists");
throw new InvalidParameterValueException("Port Profile with specified name: " + portProfName + " already exists", null);
}
// Next, check if there is any existing port profile that uses a VLAN ID range that clashes with the
// range passed to this function. If so, throw an exception.
if (_portProfileDao.doesVlanRangeClash(lowVlanId, highVlanId) == true) {
s_logger.info("Port Profile's vlanId range clashes with an existing Port Profile's");
throw new InvalidParameterValueException("Port Profile's vlanId range clashes with an existing Port Profile's", null);
}
// Else, go ahead and create the port profile.
portProfileObj = new PortProfileVO(portProfName, vsmId, lowVlanId, highVlanId, pType, bType);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
_portProfileDao.persist(portProfileObj);
txn.commit();
} catch (Exception e) {
txn.rollback();
throw new CloudRuntimeException(e.getMessage());
}
// Return the PortProfileVO object created.
return portProfileObj;
}
@DB
public boolean deletePortProfile(long portProfileId) {
PortProfileVO ppObj = _portProfileDao.findById(portProfileId);
if (ppObj == null) {
// This entry is already not present. Return success.
return true;
// This entry is already not present. Return success.
return true;
}
//Else, remove it.
// TODO: Should we be putting any checks here before removing
// the port profile record from the db?
Transaction txn = Transaction.currentTxn();
try {
txn.start();
@ -123,8 +123,8 @@ public class PortProfileManagerImpl {
_portProfileDao.remove(portProfileId);
txn.commit();
} catch (Exception e) {
s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete Port Profile");
s_logger.info("Caught exception when trying to delete Port Profile record.." + e.getMessage());
throw new CloudRuntimeException("Failed to delete Port Profile");
}
return true;
}

View File

@ -26,6 +26,7 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.cloud.exception.InvalidParameterValueException;
/**
@ -36,56 +37,56 @@ import com.cloud.exception.InvalidParameterValueException;
@Entity
@Table(name="port_profile")
public class PortProfileVO {
// We need to know what properties a VSM has. Put them here.
// We need to know what properties a VSM has. Put them here.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name="uuid")
private String uuid;
private final String uuid;
@Column(name = "port_profile_name")
private String portProfileName;
@Column(name = "port_mode")
private PortMode portMode;
@Column(name = "vsm_id")
private long vsmId;
@Column(name = "trunk_low_vlan_id")
private int lowVlanId;
@Column(name = "trunk_high_vlan_id")
private int highVlanId;
@Column(name = "access_vlan_id")
private int accessVlanId;
@Column(name = "port_type")
private PortType portType;
@Column(name = "port_binding")
private BindingType portBinding;
public enum BindingType {
Static,
Ephemeral
Static,
Ephemeral
}
public enum PortType {
Ethernet,
vEthernet
Ethernet,
vEthernet
}
// This tells us whether the port trunks multiple VLANs
// or carries traffic of a single VLAN.
public enum PortMode {
Access,
Trunk
Access,
Trunk
}
// Accessor methods
@ -98,79 +99,79 @@ public class PortProfileVO {
}
public String getPortProfileName() {
return portProfileName;
return portProfileName;
}
public PortMode getPortMode() {
return portMode;
return portMode;
}
public long getVsmId() {
return vsmId;
return vsmId;
}
public int getLowVlanId() {
return lowVlanId;
return lowVlanId;
}
public int getHighVlanId() {
return highVlanId;
return highVlanId;
}
public int getAccessVlanId() {
return accessVlanId;
return accessVlanId;
}
public PortType getPortType() {
return portType;
return portType;
}
public BindingType getPortBinding() {
return portBinding;
return portBinding;
}
// Setter methods
public void setPortProfileName(String name) {
portProfileName = name;
portProfileName = name;
}
public void setPortMode(PortMode mode) {
portMode = mode;
portMode = mode;
}
public void setVsmId(long id) {
vsmId = id;
vsmId = id;
}
public void setLowVlanId(int vlanId) {
lowVlanId = vlanId;
lowVlanId = vlanId;
}
public void setHighVlanId(int vlanId) {
highVlanId = vlanId;
highVlanId = vlanId;
}
public void setAccessVlanId(int vlanId) {
accessVlanId = vlanId;
accessVlanId = vlanId;
}
public void setPortType(PortType type) {
portType = type;
portType = type;
}
public void setPortBinding(BindingType bindingType) {
portBinding = bindingType;
portBinding = bindingType;
}
// Constructor methods.
public PortProfileVO(String portProfName, long vsmId, int vlanId, PortType pType, BindingType bType) {
// Set the relevant portprofile properties here.
// When supplied with a single vlanId, we set this portprofile as an access port profile.
this.setPortMode(PortMode.Access);
// Set the relevant portprofile properties here.
// When supplied with a single vlanId, we set this portprofile as an access port profile.
this.setPortMode(PortMode.Access);
this.uuid = UUID.randomUUID().toString();
this.setPortProfileName(portProfName);
this.setVsmId(vsmId);
@ -178,16 +179,16 @@ public class PortProfileVO {
this.setPortType(pType);
this.setPortBinding(bType);
}
public PortProfileVO(String portProfName, long vsmId, int lowVlanId, int highVlanId, PortType pType, BindingType bType) {
// Set the relevant portprofile properties here.
// When supplied with a vlan range, we set this portprofile as a trunk port profile.
if (lowVlanId >= highVlanId) {
throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id");
}
this.setPortMode(PortMode.Trunk);
// Set the relevant portprofile properties here.
// When supplied with a vlan range, we set this portprofile as a trunk port profile.
if (lowVlanId >= highVlanId) {
throw new InvalidParameterValueException("Low Vlan Id cannot be greater than or equal to high Vlan Id", null);
}
this.setPortMode(PortMode.Trunk);
this.uuid = UUID.randomUUID().toString();
this.setPortProfileName(portProfName);
this.setVsmId(vsmId);
@ -196,7 +197,7 @@ public class PortProfileVO {
this.setPortType(pType);
this.setPortBinding(bType);
}
public PortProfileVO() {
this.uuid = UUID.randomUUID().toString();
}

View File

@ -12,370 +12,366 @@
// Automatically generated by addcopyright.py at 04/03/2012
package com.cloud.network;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;
import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.listStorageNetworkIpRangeCmd;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpAddressVO;
import com.cloud.dc.StorageNetworkIpRangeVO;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.StorageNetworkIpAddressDao;
import com.cloud.dc.dao.StorageNetworkIpRangeDao;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.host.HostVO;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.SecondaryStorageVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;
import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;
import com.cloud.api.commands.listStorageNetworkIpRangeCmd;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.StorageNetworkIpAddressVO;
import com.cloud.dc.StorageNetworkIpRange;
import com.cloud.dc.StorageNetworkIpRangeVO;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.StorageNetworkIpAddressDao;
import com.cloud.dc.dao.StorageNetworkIpRangeDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.SearchCriteria2;
import com.cloud.utils.db.SearchCriteriaService;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.vm.SecondaryStorageVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.SecondaryStorageVmDao;
@Local(value = {StorageNetworkManager.class, StorageNetworkService.class})
public class StorageNetworkManagerImpl implements StorageNetworkManager, StorageNetworkService {
private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class);
String _name;
@Inject
StorageNetworkIpAddressDao _sNwIpDao;
@Inject
StorageNetworkIpRangeDao _sNwIpRangeDao;
private static final Logger s_logger = Logger.getLogger(StorageNetworkManagerImpl.class);
String _name;
@Inject
StorageNetworkIpAddressDao _sNwIpDao;
@Inject
StorageNetworkIpRangeDao _sNwIpRangeDao;
@Inject
NetworkDao _networkDao;
@Inject
HostPodDao _podDao;
@Inject
SecondaryStorageVmDao _ssvmDao;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Inject
HostPodDao _podDao;
@Inject
SecondaryStorageVmDao _ssvmDao;
@Override
public boolean start() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean start() {
// TODO Auto-generated method stub
return true;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean stop() {
// TODO Auto-generated method stub
return true;
}
private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) {
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
String[] IpRange = pod.getDescription().split("-");
if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) {
return;
}
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1]);
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
private void checkOverlapPrivateIpRange(long podId, String startIp, String endIp) {
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
}
private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) {
List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO range : curRanges) {
if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp());
}
}
}
private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException {
String[] IpRange = pod.getDescription().split("-");
if ((IpRange[0] == null || IpRange[1] == null) || (!NetUtils.isValidIp(IpRange[0]) || !NetUtils.isValidIp(IpRange[1]))) {
return;
}
if (NetUtils.ipRangesOverlap(startIp, endIp, IpRange[0], IpRange[1])) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + IpRange[0] + ":" + IpRange[1], null);
}
}
private void checkOverlapStorageIpRange(long podId, String startIp, String endIp) {
List<StorageNetworkIpRangeVO> curRanges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO range : curRanges) {
if (NetUtils.ipRangesOverlap(startIp, endIp, range.getStartIp(), range.getEndIp())) {
throw new InvalidParameterValueException("The Storage network Start IP and endIP address range overlap with private IP :" + range.getStartIp() + " - " + range.getEndIp(), null);
}
}
}
private void createStorageIpEntires(Transaction txn, long rangeId, String startIp, String endIp, long zoneId) throws SQLException {
long startIPLong = NetUtils.ip2Long(startIp);
long endIPLong = NetUtils.ip2Long(endIp);
String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
PreparedStatement stmt = null;
Connection conn = txn.getConnection();
String insertSql = "INSERT INTO `cloud`.`op_dc_storage_network_ip_address` (range_id, ip_address, mac_address, taken) VALUES (?, ?, (select mac_address from `cloud`.`data_center` where id=?), ?)";
String updateSql = "UPDATE `cloud`.`data_center` set mac_address = mac_address+1 where id=?";
PreparedStatement stmt = null;
Connection conn = txn.getConnection();
while (startIPLong <= endIPLong) {
stmt = conn.prepareStatement(insertSql);
stmt.setLong(1, rangeId);
stmt.setString(2, NetUtils.long2Ip(startIPLong++));
stmt.setLong(3, zoneId);
stmt.setNull(4, java.sql.Types.DATE);
stmt = conn.prepareStatement(insertSql);
stmt.setLong(1, rangeId);
stmt.setString(2, NetUtils.long2Ip(startIPLong++));
stmt.setLong(3, zoneId);
stmt.setNull(4, java.sql.Types.DATE);
stmt.executeUpdate();
stmt.close();
stmt = txn.prepareStatement(updateSql);
stmt.setLong(1, zoneId);
stmt.executeUpdate();
stmt.close();
}
}
@Override
@DB
}
@Override
@DB
public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) {
Integer vlan = cmd.getVlan();
Long rangeId = cmd.getId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
String netmask = cmd.getNetmask();
if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
}
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
}
if (startIp != null || endIp != null) {
long podId = range.getPodId();
startIp = startIp == null ? range.getStartIp() : startIp;
endIp = endIp == null ? range.getEndIp() : endIp;
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
}
Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(range.getId());
if (range == null) {
throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
}
StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
if (vlan != null) {
vo.setVlan(vlan);
}
if (startIp != null) {
vo.setStartIp(startIp);
}
if (endIp != null) {
vo.setEndIp(endIp);
}
if (netmask != null) {
vo.setNetmask(netmask);
}
_sNwIpRangeDao.update(rangeId, vo);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(range.getId());
}
}
txn.commit();
return _sNwIpRangeDao.findById(rangeId);
Integer vlan = cmd.getVlan();
Long rangeId = cmd.getId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
String netmask = cmd.getNetmask();
if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
}
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
}
if (startIp != null || endIp != null) {
long podId = range.getPodId();
startIp = startIp == null ? range.getStartIp() : startIp;
endIp = endIp == null ? range.getEndIp() : endIp;
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
}
Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(range.getId());
if (range == null) {
throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
}
StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
if (vlan != null) {
vo.setVlan(vlan);
}
if (startIp != null) {
vo.setStartIp(startIp);
}
if (endIp != null) {
vo.setEndIp(endIp);
}
if (netmask != null) {
vo.setNetmask(netmask);
}
_sNwIpRangeDao.update(rangeId, vo);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(range.getId());
}
}
txn.commit();
return _sNwIpRangeDao.findById(rangeId);
}
@Override
@DB
public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException {
Long podId = cmd.getPodId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
Integer vlan = cmd.getVlan();
String netmask = cmd.getNetmask();
if (endIp == null) {
endIp = startIp;
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
Long zoneId = pod.getDataCenterId();
List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage);
if (nws.size() == 0) {
throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId);
}
if (nws.size() > 1) {
throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found");
}
NetworkVO nw = nws.get(0);
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
@Override
@DB
public StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException {
Long podId = cmd.getPodId();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
Integer vlan = cmd.getVlan();
String netmask = cmd.getNetmask();
Transaction txn = Transaction.currentTxn();
StorageNetworkIpRangeVO range = null;
if (endIp == null) {
endIp = startIp;
}
txn.start();
range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay());
_sNwIpRangeDao.persist(range);
try {
createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId);
} catch (SQLException e) {
txn.rollback();
StringBuilder err = new StringBuilder();
err.append("Create storage network range failed.");
err.append("startIp=" + startIp);
err.append("endIp=" + endIp);
err.append("netmask=" + netmask);
err.append("zoneId=" + zoneId);
s_logger.debug(err.toString(), e);
throw e;
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new CloudRuntimeException("Invalid netmask:" + netmask);
}
txn.commit();
return range;
}
private String getInUseIpAddress(long rangeId) {
List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId);
StringBuilder res = new StringBuilder();
res.append("Below IP of range " + rangeId + " is still in use:");
for (String ip : ips) {
res.append(ip).append(",");
}
return res.toString();
}
@Override
@DB
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new CloudRuntimeException("Cannot find pod " + podId);
}
Long zoneId = pod.getDataCenterId();
List<NetworkVO> nws = _networkDao.listByZoneAndTrafficType(zoneId, TrafficType.Storage);
if (nws.size() == 0) {
throw new CloudRuntimeException("Cannot find storage network in zone " + zoneId);
}
if (nws.size() > 1) {
throw new CloudRuntimeException("Find more than one storage network in zone " + zoneId + "," + nws.size() + " found");
}
NetworkVO nw = nws.get(0);
checkOverlapPrivateIpRange(podId, startIp, endIp);
checkOverlapStorageIpRange(podId, startIp, endIp);
Transaction txn = Transaction.currentTxn();
StorageNetworkIpRangeVO range = null;
txn.start();
range = new StorageNetworkIpRangeVO(zoneId, podId, nw.getId(), startIp, endIp, vlan, netmask, cmd.getGateWay());
_sNwIpRangeDao.persist(range);
try {
createStorageIpEntires(txn, range.getId(), startIp, endIp, zoneId);
} catch (SQLException e) {
txn.rollback();
StringBuilder err = new StringBuilder();
err.append("Create storage network range failed.");
err.append("startIp=" + startIp);
err.append("endIp=" + endIp);
err.append("netmask=" + netmask);
err.append("zoneId=" + zoneId);
s_logger.debug(err.toString(), e);
throw e;
}
txn.commit();
return range;
}
private String getInUseIpAddress(long rangeId) {
List<String> ips = _sNwIpDao.listInUseIpByRangeId(rangeId);
StringBuilder res = new StringBuilder();
res.append("Below IP of range " + rangeId + " is still in use:");
for (String ip : ips) {
res.append(ip).append(",");
}
return res.toString();
}
@Override
@DB
public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) {
long rangeId = cmd.getId();
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
}
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException(getInUseIpAddress(rangeId));
}
long rangeId = cmd.getId();
StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
if (range == null) {
throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
}
final Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(rangeId);
if (range == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
/* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */
_sNwIpRangeDao.remove(rangeId);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(rangeId);
}
}
txn.commit();
}
@Override
if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
throw new CloudRuntimeException(getInUseIpAddress(rangeId));
}
final Transaction txn = Transaction.currentTxn();
txn.start();
try {
range = _sNwIpRangeDao.acquireInLockTable(rangeId);
if (range == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
/* entries in op_dc_storage_network_ip_address will be deleted automatically due to fk_storage_ip_address__range_id constraint key */
_sNwIpRangeDao.remove(rangeId);
} finally {
if (range != null) {
_sNwIpRangeDao.releaseFromLockTable(rangeId);
}
}
txn.commit();
}
@Override
public List<StorageNetworkIpRange> listIpRange(listStorageNetworkIpRangeCmd cmd) {
Long rangeId = cmd.getRangeId();
Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId();
List result = null;
if (rangeId != null) {
result = _sNwIpRangeDao.listByRangeId(rangeId);
} else if (podId != null) {
result = _sNwIpRangeDao.listByPodId(podId);
} else if (zoneId != null) {
result = _sNwIpRangeDao.listByDataCenterId(zoneId);
} else {
result = _sNwIpRangeDao.listAll();
}
return (List<StorageNetworkIpRange>)result;
}
Long rangeId = cmd.getRangeId();
Long podId = cmd.getPodId();
Long zoneId = cmd.getZoneId();
@Override
public void releaseIpAddress(String ip) {
_sNwIpDao.releaseIpAddress(ip);
}
@Override
List result = null;
if (rangeId != null) {
result = _sNwIpRangeDao.listByRangeId(rangeId);
} else if (podId != null) {
result = _sNwIpRangeDao.listByPodId(podId);
} else if (zoneId != null) {
result = _sNwIpRangeDao.listByDataCenterId(zoneId);
} else {
result = _sNwIpRangeDao.listAll();
}
return result;
}
@Override
public void releaseIpAddress(String ip) {
_sNwIpDao.releaseIpAddress(ip);
}
@Override
public StorageNetworkIpAddressVO acquireIpAddress(long podId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO r : ranges) {
try {
r = _sNwIpRangeDao.acquireInLockTable(r.getId());
if (r == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId());
if (ip != null) {
return ip;
}
} finally {
if (r != null) {
_sNwIpRangeDao.releaseFromLockTable(r.getId());
}
}
}
return null;
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByPodId(podId);
for (StorageNetworkIpRangeVO r : ranges) {
try {
r = _sNwIpRangeDao.acquireInLockTable(r.getId());
if (r == null) {
String msg = "Unable to acquire lock on storage network ip range id=" + r.getId() + ", delete failed";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
StorageNetworkIpAddressVO ip = _sNwIpDao.takeIpAddress(r.getId());
if (ip != null) {
return ip;
}
} finally {
if (r != null) {
_sNwIpRangeDao.releaseFromLockTable(r.getId());
}
}
}
return null;
}
@Override
@Override
public boolean isStorageIpRangeAvailable(long zoneId) {
SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class);
sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId);
List<StorageNetworkIpRangeVO> entries = sc.list();
return entries.size() > 0;
SearchCriteriaService<StorageNetworkIpRangeVO, StorageNetworkIpRangeVO> sc = SearchCriteria2.create(StorageNetworkIpRangeVO.class);
sc.addAnd(sc.getEntity().getDataCenterId(), Op.EQ, zoneId);
List<StorageNetworkIpRangeVO> entries = sc.list();
return entries.size() > 0;
}
@Override
@Override
public List<SecondaryStorageVmVO> getSSVMWithNoStorageNetwork(long zoneId) {
List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping);
return ssvms;
List<SecondaryStorageVmVO> ssvms = _ssvmDao.getSecStorageVmListInStates(null, zoneId, VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Stopping);
return ssvms;
}
@Override
@Override
public boolean isAnyStorageIpInUseInZone(long zoneId) {
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId);
for (StorageNetworkIpRangeVO r : ranges) {
if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) {
return true;
}
}
return false;
List<StorageNetworkIpRangeVO> ranges = _sNwIpRangeDao.listByDataCenterId(zoneId);
for (StorageNetworkIpRangeVO r : ranges) {
if (_sNwIpDao.countInUseIpByRangeId(r.getId()) > 0) {
return true;
}
}
return false;
}
}

View File

@ -76,6 +76,7 @@ import com.cloud.user.User;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
@ -172,7 +173,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
for (Counter counter : counters) {
if (!supportedCounters.contains(counter.getSource().name().toString())) {
throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource() + "' is not supported " +
"in the network where lb is configured");
"in the network where lb is configured");
}
}
}
@ -183,7 +184,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
VO vo = dao.findById(id);
if (vo == null) {
throw new InvalidParameterValueException("Unable to find " + paramName);
throw new InvalidParameterValueException("Unable to find " + paramName, null);
}
_accountMgr.checkAccess(caller, null, false, (ControlledEntity) vo);
@ -215,25 +216,25 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
int duration = policy.getDuration();
if (duration < interval) {
throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval);
throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval, null);
}
if (quietTime < interval) {
throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval);
throw new InvalidParameterValueException("quietTime : " + quietTime + " specified in a policy cannot be less than vm group's interval : " + interval, null);
}
if (quietTime != prevQuietTime) {
throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName);
throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName, null);
}
if (scaleUpPolicies) {
if (!isAutoScaleScaleUpPolicy(policy)) {
throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids");
throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids", null);
}
}
else {
if (isAutoScaleScaleUpPolicy(policy)) {
throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids");
throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids", null);
}
}
List<AutoScalePolicyConditionMapVO> policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null);
@ -255,16 +256,16 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
VirtualMachineTemplate template = _templateMgr.getTemplate(templateId);
// Make sure a valid template ID was specified
if (template == null) {
throw new InvalidParameterValueException("Unable to use the given template.");
throw new InvalidParameterValueException("Unable to use the given template.", null);
}
if (destroyVmGraceperiod < 0) {
throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.");
throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0.", null);
}
User user = _userDao.findById(autoscaleUserId);
if (user.getAccountId() != vmProfile.getAccountId()) {
throw new InvalidParameterValueException("AutoScale User id does not belong to the same account");
throw new InvalidParameterValueException("AutoScale User id does not belong to the same account", null);
}
String apiKey = user.getApiKey();
@ -272,15 +273,15 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
String csUrl = _configDao.getValue(Config.EndpointeUrl.key());
if(apiKey == null) {
throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it");
throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it", null);
}
if(secretKey == null) {
throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it");
throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it", null);
}
if(csUrl == null || csUrl.contains("localhost")) {
throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point");
throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point", null);
}
vmProfile = _autoScaleVmProfileDao.persist(vmProfile);
@ -303,12 +304,12 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
DataCenter zone = _configMgr.getZone(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find zone by id=" + zoneId);
throw new InvalidParameterValueException("Unable to find zone by id", null);
}
ServiceOffering serviceOffering = _configMgr.getServiceOffering(serviceOfferingId);
if (serviceOffering == null) {
throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId);
throw new InvalidParameterValueException("Unable to find service offering by id", null);
}
// validations
@ -368,7 +369,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
List<AutoScaleVmGroupVO> vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId);
for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) {
if (vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state");
throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state", null);
}
}
@ -384,7 +385,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
/* Check if entity is in database */
getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao);
if (_autoScaleVmGroupDao.isProfileInUse(id)) {
throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups");
throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups", null);
}
boolean success = _autoScaleVmProfileDao.remove(id);
if (success) {
@ -425,11 +426,11 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
int quietTime = autoScalePolicyVO.getQuietTime();
if (duration < 0) {
throw new InvalidParameterValueException("duration is an invalid value: " + duration);
throw new InvalidParameterValueException("duration is an invalid value: " + duration, null);
}
if (quietTime < 0) {
throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime);
throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime, null);
}
final Transaction txn = Transaction.currentTxn();
@ -452,13 +453,13 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
if (conditionIds.size() != conditions.size()) {
// TODO report the condition id which could not be found
throw new InvalidParameterValueException("Unable to find the condition specified");
throw new InvalidParameterValueException("Unable to find the condition specified", null);
}
ArrayList<Long> counterIds = new ArrayList<Long>();
for (ConditionVO condition : conditions) {
if (counterIds.contains(condition.getCounterid())) {
throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter");
throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter", null);
}
counterIds.add(condition.getCounterid());
}
@ -490,7 +491,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
action = action.toLowerCase();
if (!NetUtils.isValidAutoScaleAction(action)) {
throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported");
throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported", null);
}
AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, action);
@ -508,7 +509,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Policy", id, _autoScalePolicyDao);
if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) {
throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups");
throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups", null);
}
Transaction txn = Transaction.currentTxn();
@ -535,7 +536,9 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Account caller = UserContext.current().getCaller();
Account owner = _accountDao.findActiveAccount(accountName, domainId);
if (owner == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy("domain", domainId, "domainId"));
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId", idList);
}
_accountMgr.checkAccess(caller, null, false, owner);
}
@ -563,7 +566,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Account caller = UserContext.current().getCaller();
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean,
ListProjectResourcesCriteria>(domainId, isRecursive, null);
ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject,
listAll, false);
domainId = domainIdRecursiveListProject.first();
@ -661,13 +664,13 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state");
throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state", null);
}
if (vmGroupVO.getInterval() < policy.getDuration()) {
throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval");
throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval", null);
}
if (vmGroupVO.getInterval() < policy.getQuietTime()) {
throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval");
throw new InvalidParameterValueException("quietTime is less than the associated AutoScaleVmGroup's interval", null);
}
}
@ -692,11 +695,11 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId();
if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) {
throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted");
throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted", null);
}
if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) {
throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule");
throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule", null);
}
AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers,
@ -729,7 +732,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
}
// This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup.
throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported");
throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported", null);
}
@Override
@ -829,19 +832,19 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
List<Long> policyIds = new ArrayList<Long>();
if (minMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers);
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers, null);
}
if (maxMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers);
throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + minMembers, null);
}
if (minMembers > maxMembers) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")");
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")", null);
}
if (interval < 0) {
throw new InvalidParameterValueException("interval is an invalid value: " + interval);
throw new InvalidParameterValueException("interval is an invalid value: " + interval, null);
}
if (scaleUpPolicyIds != null) {
@ -906,7 +909,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao);
if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state");
throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state", null);
}
if (minMembers != null) {
@ -936,7 +939,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
boolean success = false;
if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) {
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.");
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled.", null);
}
try {
@ -963,7 +966,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao);
boolean success = false;
if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) {
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.");
throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be disabled.", null);
}
try {
@ -993,7 +996,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
try {
src = Counter.Source.valueOf(source);
} catch (Exception ex) {
throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter");
throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter", null);
}
CounterVO counter = null;
@ -1017,14 +1020,14 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
try {
op = Condition.Operator.valueOf(opr);
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.");
throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition.", null);
}
// TODO - Validate threshold
CounterVO counter = _counterDao.findById(cid);
if (counter == null) {
throw new InvalidParameterValueException("Unable to find counter");
throw new InvalidParameterValueException("Unable to find counter", null);
}
ConditionVO condition = null;
@ -1090,7 +1093,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
// Verify Counter id
CounterVO counter = _counterDao.findById(counterId);
if (counter == null) {
throw new InvalidParameterValueException("Unable to find Counter");
throw new InvalidParameterValueException("Unable to find Counter", null);
}
// Verify if it is used in any Condition
@ -1115,7 +1118,7 @@ public class AutoScaleManagerImpl<Type> implements AutoScaleService, Manager {
/* Check if entity is in database */
ConditionVO condition = getEntityInDatabase(UserContext.current().getCaller(), "Condition", conditionId, _conditionDao);
if (condition == null) {
throw new InvalidParameterValueException("Unable to find Condition");
throw new InvalidParameterValueException("Unable to find Condition", null);
}
// Verify if condition is used in any autoscale policy

View File

@ -73,8 +73,8 @@ import com.cloud.network.resource.F5BigIpResource;
import com.cloud.network.rules.LbStickinessMethod;
import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType;
import com.cloud.offering.NetworkOffering;
import com.cloud.resource.ServerResource;
import com.cloud.server.api.response.ExternalLoadBalancerResponse;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Inject;
import com.cloud.utils.exception.CloudRuntimeException;
@ -123,7 +123,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean implement(Network guestConfig, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException, ConcurrentOperationException,
InsufficientNetworkCapacityException {
InsufficientNetworkCapacityException {
if (!canHandle(guestConfig)) {
return false;
@ -138,7 +138,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean prepare(Network config, NicProfile nic, VirtualMachineProfile<? extends VirtualMachine> vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException,
InsufficientNetworkCapacityException, ResourceUnavailableException {
InsufficientNetworkCapacityException, ResourceUnavailableException {
return true;
}
@ -239,7 +239,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
@Override
public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException,
ResourceUnavailableException {
ResourceUnavailableException {
// TODO Auto-generated method stub
return true;
}
@ -265,18 +265,20 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
List<PhysicalNetworkVO> physicalNetworks = _physicalNetworkDao.listByZone(zoneId);
if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) {
throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: "
+ zoneId + " to add this device.");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("There are no physical networks or multiple physical networks " +
"configured in zone with specified zoneId to add this device.", idList);
}
pNetwork = physicalNetworks.get(0);
String deviceType = NetworkDevice.F5BigIpLoadBalancer.getName();
lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, (ServerResource) new F5BigIpResource());
lbDeviceVO = addExternalLoadBalancer(pNetwork.getId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceType, new F5BigIpResource());
if (lbDeviceVO != null) {
lbHost = _hostDao.findById(lbDeviceVO.getHostId());
@ -301,18 +303,21 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
if (zoneId != null) {
zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Could not find zone with ID: " + zoneId);
throw new InvalidParameterValueException("Could not find zone by ID", null);
}
List<PhysicalNetworkVO> physicalNetworks = _physicalNetworkDao.listByZone(zoneId);
if ((physicalNetworks == null) || (physicalNetworks.size() > 1)) {
throw new InvalidParameterValueException("There are no physical networks or multiple physical networks configured in zone with ID: "
+ zoneId + " to add this device.");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(zone, zoneId, "zoneId"));
throw new InvalidParameterValueException("There are no physical networks or multiple " +
"physical networks configured in zone with specified zoneId " +
"to add this device.", idList);
}
pNetwork = physicalNetworks.get(0);
return listExternalLoadBalancers(pNetwork.getId(), NetworkDevice.F5BigIpLoadBalancer.getName());
} else {
throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers");
throw new InvalidParameterValueException("Zone Id must be specified to list the external load balancers", null);
}
}
@ -326,10 +331,10 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
public ExternalLoadBalancerDeviceVO addF5LoadBalancer(AddF5LoadBalancerCmd cmd) {
String deviceName = cmd.getDeviceType();
if (!deviceName.equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("Invalid F5 load balancer device type");
throw new InvalidParameterValueException("Invalid F5 load balancer device type", null);
}
return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, (ServerResource) new F5BigIpResource());
return addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new F5BigIpResource());
}
@ -339,7 +344,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId);
throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null);
}
return deleteExternalLoadBalancer(lbDeviceVo.getHostId());
@ -352,7 +357,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if ((lbDeviceVo == null) || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("No F5 load balancer device found with ID: " + lbDeviceId);
throw new InvalidParameterValueException("Couldn't find F5 load balancer device by ID", null);
}
if (capacity != null) {
@ -381,13 +386,13 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
List<ExternalLoadBalancerDeviceVO> lbDevices = new ArrayList<ExternalLoadBalancerDeviceVO>();
if (physcialNetworkId == null && lbDeviceId == null) {
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified");
throw new InvalidParameterValueException("Either physical network Id or load balancer device Id must be specified", null);
}
if (lbDeviceId != null) {
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("Could not find F5 load balancer device with ID: " + lbDeviceId);
throw new InvalidParameterValueException("Could not find F5 load balancer device by ID", null);
}
lbDevices.add(lbDeviceVo);
return lbDevices;
@ -396,7 +401,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
if (physcialNetworkId != null) {
pNetwork = _physicalNetworkDao.findById(physcialNetworkId);
if (pNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physcialNetworkId);
throw new InvalidParameterValueException("Could not find phyical network by ID", null);
}
lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(physcialNetworkId, Provider.F5BigIp.getName());
return lbDevices;
@ -412,7 +417,7 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan
ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
if (lbDeviceVo == null || !lbDeviceVo.getDeviceName().equalsIgnoreCase(NetworkDevice.F5BigIpLoadBalancer.getName())) {
throw new InvalidParameterValueException("Could not find F5 load balancer device with ID " + lbDeviceId);
throw new InvalidParameterValueException("Could not find F5 load balancer device by ID ", null);
}
List<NetworkExternalLoadBalancerVO> networkLbMaps = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);

View File

@ -61,6 +61,7 @@ import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator;
@ -81,7 +82,7 @@ import com.cloud.utils.net.NetUtils;
public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manager {
private final static Logger s_logger = Logger.getLogger(RemoteAccessVpnManagerImpl.class);
String _name;
@Inject AccountDao _accountDao;
@Inject VpnUserDao _vpnUsersDao;
@Inject RemoteAccessVpnDao _remoteAccessVpnDao;
@ -95,7 +96,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
@Inject FirewallRulesDao _rulesDao;
@Inject FirewallManager _firewallMgr;
@Inject UsageEventDao _usageEventDao;
int _userLimit;
int _pskLength;
String _clientIpRange;
@ -110,26 +111,26 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
// make sure ip address exists
PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
if (ipAddr == null) {
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId, null);
}
_accountMgr.checkAccess(caller, null, true, ipAddr);
if (!ipAddr.readyToUse()) {
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress(), null);
}
IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
_networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
if (vpnVO != null) {
//if vpn is in Added state, return it to the api
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address", null);
}
// TODO: assumes one virtual network / domr per account per zone
@ -139,13 +140,15 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
return vpnVO;
}
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
throw new InvalidParameterValueException("A Remote Access VPN already exists for this account", null);
}
//Verify that vpn service is enabled for the network
Network network = _networkMgr.getNetwork(networkId);
if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(ipAddr, ipAddr.getAssociatedWithNetworkId(), "ipAddressId"));
throw new InvalidParameterValueException("Vpn service is not supported in network containing specified ipAddressId", idList);
}
if (ipRange == null) {
@ -153,13 +156,13 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
}
String[] range = ipRange.split("-");
if (range.length != 2) {
throw new InvalidParameterValueException("Invalid ip range");
throw new InvalidParameterValueException("Invalid ip range", null);
}
if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) {
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange, null);
}
if (!NetUtils.validIpRange(range[0], range[1])) {
throw new InvalidParameterValueException("Invalid ip range " + ipRange);
throw new InvalidParameterValueException("Invalid ip range " + ipRange, null);
}
Pair<String, Integer> cidr = NetUtils.getCidr(network.getCidr());
@ -169,7 +172,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-"
+ guestIpRange[1]);
+ guestIpRange[1], null);
}
// TODO: check sufficient range
// TODO: check overlap with private and public ip ranges in datacenter
@ -212,21 +215,21 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
@Override @DB
public void destroyRemoteAccessVpn(long ipId) throws ResourceUnavailableException {
Account caller = UserContext.current().getCaller();
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(ipId);
if (vpn == null) {
s_logger.debug("vpn id=" + ipId + " does not exists ");
return;
}
_accountMgr.checkAccess(caller, null, true, vpn);
Network network = _networkMgr.getNetwork(vpn.getNetworkId());
vpn.setState(RemoteAccessVpn.State.Removed);
_remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn);
List<? extends RemoteAccessVPNServiceProvider> elements = _networkMgr.getRemoteAccessVpnElements();
boolean success = false;
try {
@ -241,32 +244,32 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
//Cleanup corresponding ports
List<? extends FirewallRule> vpnFwRules = _rulesDao.listByIpAndPurpose(ipId, Purpose.Vpn);
Transaction txn = Transaction.currentTxn();
boolean applyFirewall = false;
List<FirewallRuleVO> fwRules = new ArrayList<FirewallRuleVO>();
//if related firewall rule is created for the first vpn port, it would be created for the 2 other ports as well, so need to cleanup the backend
if (_rulesDao.findByRelatedId(vpnFwRules.get(0).getId()) != null) {
applyFirewall = true;
}
if (applyFirewall) {
txn.start();
for (FirewallRule vpnFwRule : vpnFwRules) {
//don't apply on the backend yet; send all 3 rules in a banch
_firewallMgr.revokeRelatedFirewallRule(vpnFwRule.getId(), false);
fwRules.add(_rulesDao.findByRelatedId(vpnFwRule.getId()));
}
s_logger.debug("Marked " + fwRules.size() + " firewall rules as Revoked as a part of disable remote access vpn");
txn.commit();
//now apply vpn rules on the backend
s_logger.debug("Reapplying firewall rules for ip id=" + ipId + " as a part of disable remote access vpn");
success = _firewallMgr.applyFirewallRules(ipId, caller);
}
if (success) {
try {
txn.start();
@ -274,11 +277,11 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
// Stop billing of VPN users when VPN is removed. VPN_User_ADD events will be generated when VPN is created again
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for(VpnUserVO user : vpnUsers){
// VPN_USER_REMOVE event is already generated for users in Revoke state
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
// VPN_USER_REMOVE event is already generated for users in Revoke state
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_REMOVE, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
}
if (vpnFwRules != null) {
for (FirewallRule vpnFwRule : vpnFwRules) {
@ -303,30 +306,30 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (!username.matches("^[a-zA-Z0-9][a-zA-Z0-9@._-]{2,63}$")) {
throw new InvalidParameterValueException(
"Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'");
"Username has to be begin with an alphabet have 3-64 characters including alphabets, numbers and the set '@.-_'", null);
}
if (!password.matches("^[a-zA-Z0-9][a-zA-Z0-9@#+=._-]{2,31}$")) {
throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'");
throw new InvalidParameterValueException("Password has to be 3-32 characters including alphabets, numbers and the set '@#+=.-_'", null);
}
Transaction txn = Transaction.currentTxn();
txn.start();
Account owner = _accountDao.lockRow(vpnOwnerId, true);
if (owner == null) {
throw new InvalidParameterValueException("Unable to add vpn user: Another operation active");
throw new InvalidParameterValueException("Unable to add vpn user: Another operation active", null);
}
_accountMgr.checkAccess(caller, null, true, owner);
//don't allow duplicated user names for the same account
VpnUserVO vpnUser = _vpnUsersDao.findByAccountAndUsername(owner.getId(), username);
if (vpnUser != null) {
throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner);
throw new InvalidParameterValueException("VPN User with name " + username + " is already added for account " + owner, null);
}
long userCount = _vpnUsersDao.getVpnUserCount(owner.getId());
if (userCount >= _userLimit) {
throw new AccountLimitException("Cannot add more than " + _userLimit + " remote access vpn users");
}
VpnUser user = _vpnUsersDao.persist(new VpnUserVO(vpnOwnerId, owner.getDomainId(), username, password));
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
@ -340,7 +343,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username);
if (user == null) {
throw new InvalidParameterValueException("Could not find vpn user " + username);
throw new InvalidParameterValueException("Could not find vpn user " + username, null);
}
_accountMgr.checkAccess(caller, null, true, user);
Transaction txn = Transaction.currentTxn();
@ -367,12 +370,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId);
if (vpn == null) {
throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId);
throw new InvalidParameterValueException("Unable to find your vpn by id", null);
}
_accountMgr.checkAccess(caller, null, true, vpn);
Network network = _networkMgr.getNetwork(vpn.getNetworkId());
@ -383,7 +386,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
if (openFirewall) {
firewallOpened = _firewallMgr.applyFirewallRules(vpn.getServerAddressId(), caller);
}
if (firewallOpened) {
for (RemoteAccessVPNServiceProvider element : elements) {
if (element.startVpn(network, vpn)) {
@ -392,7 +395,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
}
}
}
return vpn;
} finally {
if (started) {
@ -400,14 +403,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
txn.start();
vpn.setState(RemoteAccessVpn.State.Running);
_remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn);
// Start billing of existing VPN users in ADD and Active state
List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId());
for(VpnUserVO user : vpnUsers){
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
if(user.getState() != VpnUser.State.Revoke){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername());
_usageEventDao.persist(usageEvent);
}
}
txn.commit();
}
@ -425,7 +428,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
List<RemoteAccessVpnVO> vpns = _remoteAccessVpnDao.findByAccount(vpnOwnerId);
List<VpnUserVO> users = _vpnUsersDao.listByAccount(vpnOwnerId);
//If user is in Active state, we still have to resend them therefore their status has to be Add
for (VpnUserVO user : users) {
if (user.getState() == State.Active) {
@ -433,7 +436,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
_vpnUsersDao.update(user.getId(), user);
}
}
List<? extends RemoteAccessVPNServiceProvider> elements = _networkMgr.getRemoteAccessVpnElements();
boolean success = true;
@ -461,7 +464,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply vpn users ", e);
success= false;
for (int i = 0; i < finals.length; i++) {
finals[i] = false;
}
@ -479,7 +482,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
_vpnUsersDao.remove(user.getId());
}
} else {
if (user.getState() == State.Add) {
if (user.getState() == State.Add) {
Transaction txn = Transaction.currentTxn();
txn.start();
_vpnUsersDao.remove(user.getId());
@ -498,7 +501,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
public List<VpnUserVO> searchForVpnUsers(ListVpnUsersCmd cmd) {
String username = cmd.getUsername();
Long id = cmd.getId();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
@ -511,14 +514,14 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ);
sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
SearchCriteria<VpnUserVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
//list only active users
sc.setParameters("state", State.Active);
@ -539,40 +542,40 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
Account caller = UserContext.current().getCaller();
Long ipAddressId = cmd.getPublicIpId();
List<Long> permittedAccounts = new ArrayList<Long>();
if (ipAddressId != null) {
PublicIpAddress publicIp = _networkMgr.getPublicIpAddress(ipAddressId);
if (publicIp == null) {
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.");
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.", null);
} else {
Long ipAddrAcctId = publicIp.getAccountId();
if (ipAddrAcctId == null) {
throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId
+ " is not associated with an account.");
+ " is not associated with an account.", null);
}
}
_accountMgr.checkAccess(caller, null, true, publicIp);
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<RemoteAccessVpnVO> sb = _remoteAccessVpnDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ);
sb.and("state", sb.entity().getState(), Op.EQ);
SearchCriteria<RemoteAccessVpnVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sc.setParameters("state", RemoteAccessVpn.State.Running);
if (ipAddressId != null) {
sc.setParameters("serverAddressId", ipAddressId);
}
@ -620,12 +623,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag
public String getName() {
return _name;
}
@Override
public List<? extends RemoteAccessVpn> listRemoteAccessVpns(long networkId) {
return _remoteAccessVpnDao.listByNetworkId(networkId);
}
@Override
public RemoteAccessVpn getRemoteAccessVpn(long vpnId) {
return _remoteAccessVpnDao.findById(vpnId);

View File

@ -48,6 +48,7 @@ import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.exception.CloudRuntimeException;
@ -66,9 +67,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
@Inject AccountDao _accountDao;
@Inject VpcManager _vpcMgr;
@Inject AccountManager _accountMgr;
String _name;
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
@ -99,14 +100,16 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
//Verify that caller can perform actions in behalf of vpc owner
_accountMgr.checkAccess(caller, null, false, owner);
Long vpcId = cmd.getVpcId();
Long vpcId = cmd.getVpcId();
VpcVO vpc = _vpcDao.findById(vpcId);
if (vpc == null) {
throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!");
throw new InvalidParameterValueException("Invalid VPC " + vpcId + " for site to site vpn gateway creation!", null);
}
Site2SiteVpnGatewayVO gws = _vpnGatewayDao.findByVpcId(vpcId);
if (gws != null) {
throw new InvalidParameterValueException("The VPN gateway of VPC " + vpcId + " already existed!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(vpc, vpcId, "vpcId"));
throw new InvalidParameterValueException("The VPN gateway of VPC with specified vpcId already exists!", idList);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -118,7 +121,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
if (ips.size() != 1) {
throw new CloudRuntimeException("Cannot found source nat ip of vpc " + vpcId);
}
Site2SiteVpnGatewayVO gw = new Site2SiteVpnGatewayVO(accountId, domainId, ips.get(0).getId(), vpcId);
_vpnGatewayDao.persist(gw);
return gw;
@ -136,23 +139,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
String name = cmd.getName();
String gatewayIp = cmd.getGatewayIp();
if (!NetUtils.isValidIp(gatewayIp)) {
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null);
}
if (name == null) {
name = "VPN-" + gatewayIp;
}
String guestCidrList = cmd.getGuestCidrList();
if (!NetUtils.validateGuestCidrList(guestCidrList)) {
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!");
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " is invalid guest cidr!", null);
}
String ipsecPsk = cmd.getIpsecPsk();
String ikePolicy = cmd.getIkePolicy();
String espPolicy = cmd.getEspPolicy();
if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) {
throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway IKE policy " + ikePolicy + " is invalid!", null);
}
if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) {
throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ESP policy " + espPolicy + " is invalid!", null);
}
Long lifetime = cmd.getLifetime();
if (lifetime == null) {
@ -160,13 +163,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
lifetime = (long) 86400;
}
if (lifetime > 86400) {
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!");
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null);
}
if (_customerGatewayDao.findByGatewayIp(gatewayIp) != null) {
throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!");
throw new InvalidParameterValueException("The customer gateway with ip " + gatewayIp + " already existed!", null);
}
if (_customerGatewayDao.findByName(name) != null) {
throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!");
throw new InvalidParameterValueException("The customer gateway with name " + name + " already existed!", null);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -191,20 +194,23 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long customerGatewayId = cmd.getCustomerGatewayId();
Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(customerGatewayId);
if (customerGateway == null) {
throw new InvalidParameterValueException("Unable to found specified Site to Site VPN customer gateway " + customerGatewayId + " !");
throw new InvalidParameterValueException("Unable to find specified Site to Site VPN customer gateway by id!", null);
}
_accountMgr.checkAccess(caller, null, false, customerGateway);
Long vpnGatewayId = cmd.getVpnGatewayId();
Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(vpnGatewayId);
if (vpnGateway == null) {
throw new InvalidParameterValueException("Unable to found specified Site to Site VPN gateway " + vpnGatewayId + " !");
throw new InvalidParameterValueException("Unable to find specified Site to Site VPN gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, vpnGateway);
if (_vpnConnectionDao.findByVpnGatewayIdAndCustomerGatewayId(vpnGatewayId, customerGatewayId) != null) {
throw new InvalidParameterValueException("The vpn connection with customer gateway id " + customerGatewayId + " or vpn gateway id "
+ vpnGatewayId + " already existed!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(vpnGateway, vpnGatewayId, "vpnGatewayId"));
idList.add(new IdentityProxy(customerGateway, customerGatewayId, "customerGatewayId"));
throw new InvalidParameterValueException("The vpn connection with specified customer gateway id or vpn gateway id " +
" already exists!", idList);
}
Long accountId = cmd.getEntityOwnerId();
Long domainId = cmd.getDomainId();
@ -221,7 +227,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
public Site2SiteVpnConnection startVpnConnection(long id) throws ResourceUnavailableException {
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn.getState() != State.Pending && conn.getState() != State.Disconnected) {
throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(pending or disconnected) to process!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "connectionId"));
throw new InvalidParameterValueException("Site to site VPN connection with specified connectionId not in correct state(pending or disconnected) to process!", idList);
}
conn.setState(State.Pending);
@ -258,13 +266,15 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteCustomerGateway customerGateway = _customerGatewayDao.findById(id);
if (customerGateway == null) {
throw new InvalidParameterValueException("Fail to find customer gateway with " + id + " !");
throw new InvalidParameterValueException("Fail to find customer gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, customerGateway);
List<Site2SiteVpnConnectionVO> vpnConnections = _vpnConnectionDao.listByCustomerGatewayId(id);
if (vpnConnections != null && vpnConnections.size() != 0) {
throw new InvalidParameterValueException("Unable to delete VPN customer gateway " + id + " because there is still related VPN connections!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(customerGateway, id, "customerGatewayId"));
throw new InvalidParameterValueException("Unable to delete VPN customer gateway with specified id because there is still related VPN connections!", idList);
}
_customerGatewayDao.remove(id);
return true;
@ -273,11 +283,13 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
protected void doDeleteVpnGateway(Site2SiteVpnGateway gw) {
List<Site2SiteVpnConnectionVO> conns = _vpnConnectionDao.listByVpnGatewayId(gw.getId());
if (conns != null && conns.size() != 0) {
throw new InvalidParameterValueException("Unable to delete VPN gateway " + gw.getId() + " because there is still related VPN connections!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(gw, gw.getId(), "vpnGatewayId"));
throw new InvalidParameterValueException("Unable to delete VPN gateway with specified id because there is still related VPN connections!", idList);
}
_vpnGatewayDao.remove(gw.getId());
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE, eventDescription = "deleting s2s vpn gateway", create=true)
public boolean deleteVpnGateway(DeleteVpnGatewayCmd cmd) {
@ -287,9 +299,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnGateway vpnGateway = _vpnGatewayDao.findById(id);
if (vpnGateway == null) {
throw new InvalidParameterValueException("Fail to find vpn gateway with " + id + " !");
throw new InvalidParameterValueException("Fail to find vpn gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, vpnGateway);
doDeleteVpnGateway(vpnGateway);
@ -305,7 +317,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteCustomerGatewayVO gw = _customerGatewayDao.findById(id);
if (gw == null) {
throw new InvalidParameterValueException("Find to find customer gateway with id " + id);
throw new InvalidParameterValueException("Find to find customer gateway by id", null);
}
_accountMgr.checkAccess(caller, null, false, gw);
@ -313,26 +325,28 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
if (conns != null) {
for (Site2SiteVpnConnection conn : conns) {
if (conn.getState() != State.Disconnected || conn.getState() != State.Error) {
throw new InvalidParameterValueException("Unable to update customer gateway because there is active VPN connection " + conn.getId());
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, conn.getId(), "vpnConnectionId"));
throw new InvalidParameterValueException("Unable to update customer gateway because there is an active VPN connection with specified vpn connection id", idList);
}
}
}
String gatewayIp = cmd.getGatewayIp();
if (!NetUtils.isValidIp(gatewayIp)) {
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ip " + gatewayIp + " is invalid!", null);
}
String guestCidrList = cmd.getGuestCidrList();
if (!NetUtils.validateGuestCidrList(guestCidrList)) {
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!");
throw new InvalidParameterValueException("The customer gateway guest cidr list " + guestCidrList + " contains invalid guest cidr!", null);
}
String ipsecPsk = cmd.getIpsecPsk();
String ikePolicy = cmd.getIkePolicy();
String espPolicy = cmd.getEspPolicy();
if (!NetUtils.isValidS2SVpnPolicy(ikePolicy)) {
throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway IKE policy" + ikePolicy + " is invalid!", null);
}
if (!NetUtils.isValidS2SVpnPolicy(espPolicy)) {
throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!");
throw new InvalidParameterValueException("The customer gateway ESP policy" + espPolicy + " is invalid!", null);
}
Long lifetime = cmd.getLifetime();
if (lifetime == null) {
@ -340,7 +354,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
lifetime = (long) 86400;
}
if (lifetime > 86400) {
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!");
throw new InvalidParameterValueException("The lifetime " + lifetime + " of vpn connection is invalid!", null);
}
gw.setGatewayIp(gatewayIp);
gw.setGuestCidrList(guestCidrList);
@ -361,9 +375,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn == null) {
throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to delete!");
throw new InvalidParameterValueException("Fail to find site to site VPN connection to delete!", null);
}
_accountMgr.checkAccess(caller, null, false, conn);
if (conn.getState() == State.Connected) {
@ -376,7 +390,9 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
private void stopVpnConnection(Long id) throws ResourceUnavailableException {
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn.getState() != State.Connected && conn.getState() != State.Error) {
throw new InvalidParameterValueException("Site to site VPN connection " + id + " not in correct state(connected) to process disconnect!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "vpnConnectionId"));
throw new InvalidParameterValueException("Site to site VPN connection with specified id is not in correct state(connected) to process disconnect!", idList);
}
List <? extends Site2SiteVpnServiceProvider> elements = _networkMgr.getSite2SiteVpnElements();
@ -403,12 +419,14 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
Long id = cmd.getId();
Site2SiteVpnConnectionVO conn = _vpnConnectionDao.findById(id);
if (conn == null) {
throw new InvalidParameterValueException("Fail to find site to site VPN connection " + id + " to reset!");
throw new InvalidParameterValueException("Fail to find site to site VPN connection to reset!", null);
}
_accountMgr.checkAccess(caller, null, false, conn);
if (conn.getState() == State.Pending) {
throw new InvalidParameterValueException("VPN connection " + id + " cannot be reseted when state is Pending!");
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(conn, id, "vpnConnectionId"));
throw new InvalidParameterValueException("VPN connection with specified id cannot be reseted when state is Pending!", idList);
}
if (conn.getState() == State.Connected || conn.getState() == State.Error) {
stopVpnConnection(id);
@ -434,7 +452,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
public List<Site2SiteVpnGateway> searchForVpnGateways(ListVpnGatewaysCmd cmd) {
Long id = cmd.getId();
Long vpcId = cmd.getVpcId();
List<Site2SiteVpnGateway> results = new ArrayList<Site2SiteVpnGateway>();
if (id != null) {
results.add(_vpnGatewayDao.findById(cmd.getId()));
@ -450,7 +468,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
public List<Site2SiteVpnConnection> searchForVpnConnections(ListVpnConnectionsCmd cmd) {
Long id = cmd.getId();
Long vpcId = cmd.getVpcId();
List<Site2SiteVpnConnection> results = new ArrayList<Site2SiteVpnConnection>();
if (id != null) {
results.add(_vpnConnectionDao.findById(cmd.getId()));
@ -480,7 +498,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager {
doDeleteVpnGateway(gw);
return true;
}
@Override
public void markDisconnectVpnConnByVpc(long vpcId) {
List<Site2SiteVpnConnectionVO> conns = _vpnConnectionDao.listByVpcId(vpcId);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -61,6 +61,7 @@ import com.cloud.user.AccountVO;
import com.cloud.user.ResourceLimitService;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
@ -371,7 +372,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
try {
resourceType = ResourceType.values()[type];
} catch (ArrayIndexOutOfBoundsException e) {
throw new InvalidParameterValueException("Please specify a valid resource type.");
throw new InvalidParameterValueException("Please specify a valid resource type.", null);
}
}
@ -482,7 +483,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
if (max == null) {
max = new Long(Resource.RESOURCE_UNLIMITED);
} else if (max.longValue() < Resource.RESOURCE_UNLIMITED) {
throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'.");
throw new InvalidParameterValueException("Please specify either '-1' for an infinite limit, or a limit that is at least '0'.", null);
}
// Map resource type
@ -494,7 +495,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
}
if (resourceType == null) {
throw new InvalidParameterValueException("Please specify valid resource type");
throw new InvalidParameterValueException("Please specify valid resource type", null);
}
}
@ -504,17 +505,17 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
if (accountId != null) {
Account account = _entityMgr.findById(Account.class, accountId);
if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Can't update system account");
throw new InvalidParameterValueException("Can't update system account", null);
}
//only Unlimited value is accepted if account is Root Admin
if (_accountMgr.isRootAdmin(account.getType()) && max.shortValue() != ResourceLimit.RESOURCE_UNLIMITED) {
throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts");
throw new InvalidParameterValueException("Only " + ResourceLimit.RESOURCE_UNLIMITED + " limit is supported for Root Admin accounts", null);
}
if ((caller.getAccountId() == accountId.longValue()) &&
(caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN ||
caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
(caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN ||
caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
// If the admin is trying to update his own account, disallow.
throw new PermissionDeniedException("Unable to update resource limit for his own account " + accountId + ", permission denied");
}
@ -546,8 +547,11 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
DomainVO parentDomain = _domainDao.findById(parentDomainId);
long parentMaximum = findCorrectResourceLimitForDomain(parentDomain, resourceType);
if ((parentMaximum >= 0) && (max.longValue() > parentMaximum)) {
throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + parentDomain.getId() + ") has maximum allowed resource limit " + parentMaximum + " for " + resourceType
+ ", please specify a value less that or equal to " + parentMaximum);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy(parentDomain, parentDomain.getId(), "domainId"));
throw new InvalidParameterValueException("Domain " + domain.getName() + " with specified domainId " +
"has maximum allowed resource limit " + parentMaximum + " for " + resourceType +
", please specify a value less that or equal to " + parentMaximum, idList);
}
}
ownerType = ResourceOwnerType.Domain;
@ -555,7 +559,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
if (ownerId == null) {
throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit");
throw new InvalidParameterValueException("AccountId or domainId have to be specified in order to update resource limit", null);
}
ResourceLimitVO limit = _resourceLimitDao.findByOwnerIdAndType(ownerId, ownerType, resourceType);
@ -584,13 +588,13 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
}
}
if (resourceType == null) {
throw new InvalidParameterValueException("Please specify valid resource type");
throw new InvalidParameterValueException("Please specify valid resource type", null);
}
}
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Please specify a valid domain ID.");
throw new InvalidParameterValueException("Please specify a valid domain ID.", null);
}
_accountMgr.checkAccess(callerAccount, domain);
@ -734,7 +738,7 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager {
} else if (type == Resource.ResourceType.network) {
newCount = _networkDao.countNetworksUserCanCreate(accountId);
} else {
throw new InvalidParameterValueException("Unsupported resource type " + type);
throw new InvalidParameterValueException("Unsupported resource type " + type, null);
}
_resourceCountDao.setResourceCount(accountId, ResourceOwnerType.Account, type, (newCount == null) ? 0 : newCount.longValue());

View File

@ -90,6 +90,7 @@ import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.IdentityProxy;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
@ -373,7 +374,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
txn = Transaction.currentTxn();
try {
@ -400,10 +401,10 @@ public class ConfigurationServerImpl implements ConfigurationServer {
// save default security group
if (tableName.equals("security_group")) {
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id) " +
"VALUES ('default', 'Default Security Group', 2, 1)";
"VALUES ('default', 'Default Security Group', 2, 1)";
} else {
insertSql = "INSERT INTO " + tableName + " (name, description, account_id, domain_id, account_name) " +
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
}
txn = Transaction.currentTxn();
@ -561,8 +562,8 @@ public class ConfigurationServerImpl implements ConfigurationServer {
try {
String rpassword = PasswordGenerator.generatePresharedKey(8);
String wSql = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) "
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
+ "VALUES ('Hidden','DEFAULT', 'management-server','system.vm.password', '" + rpassword
+ "','randmon password generated each management server starts for system vm')";
PreparedStatement stmt = txn.prepareAutoCloseStatement(wSql);
stmt.executeUpdate(wSql);
s_logger.info("Updated systemvm password in database");
@ -635,9 +636,9 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String publicKey = new String(arr2).trim();
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')";
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '" + DBEncryptionUtil.encrypt(privateKey) + "','Private key for the entire CloudStack')";
String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')";
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '" + DBEncryptionUtil.encrypt(publicKey) + "','Public key for the entire CloudStack')";
Transaction txn = Transaction.currentTxn();
try {
@ -749,7 +750,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String password = PasswordGenerator.generateRandomPassword(12);
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
Transaction txn = Transaction.currentTxn();
try {
@ -818,12 +819,12 @@ public class ConfigurationServerImpl implements ConfigurationServer {
String ipNums = _configDao.getValue("linkLocalIp.nums");
int nums = Integer.parseInt(ipNums);
if (nums > 16 || nums <= 0) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16");
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16", null);
}
/* local link ip address starts from 169.254.0.2 - 169.254.(nums) */
String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums);
if (linkLocalIpRanges == null) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16");
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16", null);
} else {
_zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
}
@ -977,7 +978,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1041,7 +1042,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultVpcNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service));
(defaultNetworkOfferingForVpcNetworks.getId(), service, defaultVpcNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1070,7 +1071,7 @@ public class ConfigurationServerImpl implements ConfigurationServer {
for (Service service : defaultVpcNetworkOfferingProvidersNoLB.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO
(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service));
(defaultNetworkOfferingForVpcNetworksNoLB.getId(), service, defaultVpcNetworkOfferingProvidersNoLB.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
@ -1173,12 +1174,15 @@ public class ConfigurationServerImpl implements ConfigurationServer {
}
if (networkOfferingId == null) {
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType, null);
}
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
List<IdentityProxy> idList = new ArrayList<IdentityProxy>();
idList.add(new IdentityProxy("data_center", zoneId, "zoneId"));
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType +
" in zone with specified zoneId", idList);
}
return networks.get(0).getId();
}

View File

@ -2196,7 +2196,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
// Validate physical network
PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
throw new InvalidParameterValueException("Unable to find physical network by id and tag: " +requiredOfferings.get(0).getTags(), null);
}
s_logger.debug("Creating network for account " + owner + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of deployVM process");
@ -2429,7 +2429,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
String instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
String uuidName = UUID.randomUUID().toString();
//verify hostname information
if (hostName == null) {
hostName = uuidName;
@ -2453,16 +2453,16 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
ntwkDomains.put(ntwkDomain, ntwkIds);
}
}
for (String ntwkDomain : ntwkDomains.keySet()) {
for (Long ntwkId : ntwkDomains.get(ntwkDomain)) {
//* get all vms hostNames in the network
//* get all vms hostNames in the network
List<String> hostNames = _vmInstanceDao.listDistinctHostNames(ntwkId);
//* verify that there are no duplicates
if (hostNames.contains(hostName)) {
throw new InvalidParameterValueException("The vm with hostName " + hostName
+ " already exists in the network domain: " + ntwkDomain + "; network="
+ _networkMgr.getNetwork(ntwkId));
+ _networkMgr.getNetwork(ntwkId), null);
}
}
}
@ -3259,7 +3259,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
return usesLocalStorage;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(Long vmId, Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
@ -3592,7 +3592,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: "+physicalNetworkId + " and tag: " +requiredOfferings.get(0).getTags());
}
s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" +
requiredOfferings.get(0).getId() + " as a part of deployVM process");
Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(),
@ -3745,9 +3745,9 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager
}
@Override
public boolean recreateNeeded(VirtualMachineProfile<UserVmVO> profile,
long hostId, Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
long hostId, Commands cmds, ReservationContext context) {
// TODO Auto-generated method stub
return false;
}
}