Refactored associateIPAddress and updateHost commands.

This commit is contained in:
alena 2010-08-30 15:22:42 -07:00
parent 48944aedec
commit 53892037c4
11 changed files with 476 additions and 651 deletions

View File

@ -27,6 +27,7 @@ import com.cloud.api.commands.AddHostCmd;
import com.cloud.api.commands.AddHostOrStorageCmd;
import com.cloud.api.commands.DeleteHostCmd;
import com.cloud.api.commands.ReconnectHostCmd;
import com.cloud.api.commands.UpdateHostCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.PodCluster;
@ -161,10 +162,9 @@ public interface AgentManager extends Manager {
/**
* Updates a host
* @param hostId
* @param guestOSCategoryId
* @param cmd
*/
void updateHost(long hostId, long guestOSCategoryId);
void updateHost(UpdateHostCmd cmd) throws InvalidParameterValueException;
/**
* Deletes a host

View File

@ -75,6 +75,7 @@ import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AddHostOrStorageCmd;
import com.cloud.api.commands.DeleteHostCmd;
import com.cloud.api.commands.ReconnectHostCmd;
import com.cloud.api.commands.UpdateHostCmd;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.dao.ConfigurationDao;
@ -1687,19 +1688,38 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory {
}
}
public void updateHost(long hostId, long guestOSCategoryId) {
GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
Map<String, String> hostDetails = _hostDetailsDao.findDetails(hostId);
public void updateHost(UpdateHostCmd cmd) throws InvalidParameterValueException{
Long hostId = cmd.getId();
Long guestOSCategoryId = cmd.getOsCategoryId();
if (guestOSCategory != null) {
// Save a new entry for guest.os.category.id
hostDetails.put("guest.os.category.id", String.valueOf(guestOSCategory.getId()));
} else {
// Delete any existing entry for guest.os.category.id
hostDetails.remove("guest.os.category.id");
if (guestOSCategoryId != null) {
// Verify that the host exists
HostVO host = _hostDao.findById(hostId);
if (host == null) {
throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist");
}
// Verify that the guest OS Category exists
if (guestOSCategoryId > 0) {
if (_guestOSCategoryDao.findById(guestOSCategoryId) == null) {
throw new InvalidParameterValueException("Please specify a valid guest OS category.");
}
}
GuestOSCategoryVO guestOSCategory = _guestOSCategoryDao.findById(guestOSCategoryId);
Map<String, String> hostDetails = _hostDetailsDao.findDetails(hostId);
if (guestOSCategory != null) {
// Save a new entry for guest.os.category.id
hostDetails.put("guest.os.category.id", String.valueOf(guestOSCategory.getId()));
} else {
// Delete any existing entry for guest.os.category.id
hostDetails.remove("guest.os.category.id");
}
_hostDetailsDao.persist(hostId, hostDetails);
}
_hostDetailsDao.persist(hostId, hostDetails);
}
protected void updateHost(final HostVO host, final StartupCommand startup, final Host.Type type, final long msId) throws IllegalArgumentException {

View File

@ -25,10 +25,9 @@ import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
@Implementation(method="associateIpAddress", manager=Manager.ManagementServer)
@Implementation(method="associateIP", manager=Manager.NetworkManager)
public class AssociateIPAddrCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName());
private static final String s_name = "associateipaddressresponse";
/////////////////////////////////////////////////////
@ -180,5 +179,11 @@ public class AssociateIPAddrCmd extends BaseCmd {
}
return embeddedObject;
}
*/
*/
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -18,38 +18,17 @@
package com.cloud.api.commands;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.async.executor.HostResultObject;
import com.cloud.host.Host;
import com.cloud.host.HostStats;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.offering.ServiceOffering;
import com.cloud.storage.GuestOSCategoryVO;
import com.cloud.utils.Pair;
import com.cloud.utils.fsm.StateMachine;
import com.cloud.vm.UserVmVO;
@Implementation(method="updateHost", manager=Manager.AgentManager)
public class UpdateHostCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateHostCmd.class.getName());
private static final String s_name = "updatehostresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.OS_CATEGORY_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -81,148 +60,150 @@ public class UpdateHostCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
public static String getResultObjectName() {
return "updatehost";
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long id = (Long)params.get(BaseCmd.Properties.ID.getName());
Long guestOSCategoryId = (Long)params.get(BaseCmd.Properties.OS_CATEGORY_ID.getName());
if (guestOSCategoryId == null) {
guestOSCategoryId = new Long(-1);
}
// Verify that the host exists
HostVO host = getManagementServer().getHostBy(id);
if (host == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Host with id " + id.toString() + " doesn't exist");
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
try {
getManagementServer().updateHost(id, guestOSCategoryId);
} catch (Exception ex) {
s_logger.error("Failed to update host: ", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host: " + ex.getMessage());
}
final StateMachine<Status, Event> sm = new StateMachine<Status, Event>();
returnValues.add(new Pair<String,Object> (BaseCmd.Properties.SUCCESS.getName(), "true"));
returnValues.add(new Pair<String,Object> (getResultObjectName(),composeResultObject(host,sm)));
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long id = (Long)params.get(BaseCmd.Properties.ID.getName());
// Long guestOSCategoryId = (Long)params.get(BaseCmd.Properties.OS_CATEGORY_ID.getName());
//
// if (guestOSCategoryId == null) {
// guestOSCategoryId = new Long(-1);
// }
//
// // Verify that the host exists
// HostVO host = getManagementServer().getHostBy(id);
// if (host == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Host with id " + id.toString() + " doesn't exist");
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// try {
// getManagementServer().updateHost(id, guestOSCategoryId);
// } catch (Exception ex) {
// s_logger.error("Failed to update host: ", ex);
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host: " + ex.getMessage());
// }
// final StateMachine<Status, Event> sm = new StateMachine<Status, Event>();
// returnValues.add(new Pair<String,Object> (BaseCmd.Properties.SUCCESS.getName(), "true"));
// returnValues.add(new Pair<String,Object> (getResultObjectName(),composeResultObject(host,sm)));
// return returnValues;
// }
//
// private HostResultObject composeResultObject(HostVO hostVO, StateMachine<Status, Event> sm)
// {
// HostResultObject hostRO = new HostResultObject();
//
// hostRO.setName(hostVO.getName());
// hostRO.setState(hostVO.getStatus().toString());
//
// if(hostVO.getDisconnectedOn() != null)
// hostRO.setDisconnected(hostVO.getDisconnectedOn());
//
//
// if (hostVO.getType() != null) {
// hostRO.setType(hostVO.getType().toString());
// }
//
// GuestOSCategoryVO guestOSCategory = getManagementServer().getHostGuestOSCategory(hostVO.getId());
// if (guestOSCategory != null) {
// hostRO.setOsCategoryId(guestOSCategory.getId());
// hostRO.setOsCategoryName(guestOSCategory.getName());
// }
//
//
// hostRO.setIpAddress(hostVO.getPrivateIpAddress());
// hostRO.setZoneId(hostVO.getDataCenterId());
// hostRO.setZoneName(getManagementServer().getDataCenterBy(hostVO.getDataCenterId()).getName());
//
// if (hostVO.getPodId() != null && getManagementServer().findHostPodById(hostVO.getPodId()) != null) {
// hostRO.setPodId(hostVO.getPodId());
// hostRO.setPodName((getManagementServer().findHostPodById(hostVO.getPodId())).getName());
// }
//
// hostRO.setVersion(hostVO.getVersion().toString());
//
// if (hostVO.getHypervisorType() != null) {
// hostRO.setHypervisorType(hostVO.getHypervisorType().toString());
// }
//
// if ((hostVO.getCpus() != null) && (hostVO.getSpeed() != null) && !(hostVO.getType().toString().equals("Storage")))
// {
//
// hostRO.setCpuNumber(hostVO.getCpus());
// hostRO.setCpuSpeed(hostVO.getSpeed());
// // calculate cpu allocated by vm
// int cpu = 0;
// String cpuAlloc = null;
// DecimalFormat decimalFormat = new DecimalFormat("#.##");
// List<UserVmVO> instances = getManagementServer().listUserVMsByHostId(hostVO.getId());
// for (UserVmVO vm : instances) {
// ServiceOffering so = getManagementServer().findServiceOfferingById(vm.getServiceOfferingId());
// cpu += so.getCpu() * so.getSpeed();
// }
// cpuAlloc = decimalFormat.format(((float) cpu / (float) (hostVO.getCpus() * hostVO.getSpeed())) * 100f) + "%";
// hostRO.setCpuAllocated(cpuAlloc);
//
// // calculate cpu utilized
// String cpuUsed = null;
// HostStats hostStats = getManagementServer().getHostStatistics(hostVO.getId());
// if (hostStats != null) {
// float cpuUtil = (float) hostStats.getCpuUtilization();
// cpuUsed = decimalFormat.format(cpuUtil) + "%";
// hostRO.setCpuUsed(cpuUsed);
//
// long avgLoad = (long)hostStats.getAverageLoad();
// hostRO.setAverageLoad(avgLoad);
//
// long networkKbsRead = (long)hostStats.getNetworkReadKBs();
// hostRO.setNetworkKbsRead(networkKbsRead);
//
// long networkKbsWrite = (long)hostStats.getNetworkWriteKBs();
// hostRO.setNetworkKbsWrite(networkKbsWrite);
//
// }
// }
//
// if ( hostVO.getType() == Host.Type.Routing) {
// Long memory = hostVO.getTotalMemory();
// hostRO.setTotalMemory(memory);
// // calculate memory allocated by systemVM and userVm
// long mem = getManagementServer().getMemoryUsagebyHost(hostVO.getId());
// hostRO.setMemoryAllocated(mem);
//
// // calculate memory utilized, we don't provide memory over commit
// hostRO.setMemoryUsed(mem);
// }
// if (hostVO.getType().toString().equals("Storage")) {
// hostRO.setDiskSizeTotal(hostVO.getTotalSize());
// hostRO.setDiskSizeAllocated(0);
// }
// hostRO.setCaps(hostVO.getCapabilities());
// hostRO.setLastPinged(hostVO.getLastPinged());
// if (hostVO.getManagementServerId() != null) {
// hostRO.setManagementServerId(hostVO.getManagementServerId());
// }
//
// if (hostVO.getCreated() != null) {
// hostRO.setCreated(hostVO.getCreated());
// }
// if (hostVO.getRemoved() != null) {
// hostRO.setRemoved(hostVO.getRemoved());
// }
//
// Set<Event> possibleEvents = hostVO.getStatus().getPossibleEvents();
// hostRO.setEvents(possibleEvents);
//
// return hostRO;
//
// }
private HostResultObject composeResultObject(HostVO hostVO, StateMachine<Status, Event> sm)
{
HostResultObject hostRO = new HostResultObject();
hostRO.setName(hostVO.getName());
hostRO.setState(hostVO.getStatus().toString());
if(hostVO.getDisconnectedOn() != null)
hostRO.setDisconnected(hostVO.getDisconnectedOn());
if (hostVO.getType() != null) {
hostRO.setType(hostVO.getType().toString());
}
GuestOSCategoryVO guestOSCategory = getManagementServer().getHostGuestOSCategory(hostVO.getId());
if (guestOSCategory != null) {
hostRO.setOsCategoryId(guestOSCategory.getId());
hostRO.setOsCategoryName(guestOSCategory.getName());
}
hostRO.setIpAddress(hostVO.getPrivateIpAddress());
hostRO.setZoneId(hostVO.getDataCenterId());
hostRO.setZoneName(getManagementServer().getDataCenterBy(hostVO.getDataCenterId()).getName());
if (hostVO.getPodId() != null && getManagementServer().findHostPodById(hostVO.getPodId()) != null) {
hostRO.setPodId(hostVO.getPodId());
hostRO.setPodName((getManagementServer().findHostPodById(hostVO.getPodId())).getName());
}
hostRO.setVersion(hostVO.getVersion().toString());
if (hostVO.getHypervisorType() != null) {
hostRO.setHypervisorType(hostVO.getHypervisorType().toString());
}
if ((hostVO.getCpus() != null) && (hostVO.getSpeed() != null) && !(hostVO.getType().toString().equals("Storage")))
{
hostRO.setCpuNumber(hostVO.getCpus());
hostRO.setCpuSpeed(hostVO.getSpeed());
// calculate cpu allocated by vm
int cpu = 0;
String cpuAlloc = null;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
List<UserVmVO> instances = getManagementServer().listUserVMsByHostId(hostVO.getId());
for (UserVmVO vm : instances) {
ServiceOffering so = getManagementServer().findServiceOfferingById(vm.getServiceOfferingId());
cpu += so.getCpu() * so.getSpeed();
}
cpuAlloc = decimalFormat.format(((float) cpu / (float) (hostVO.getCpus() * hostVO.getSpeed())) * 100f) + "%";
hostRO.setCpuAllocated(cpuAlloc);
// calculate cpu utilized
String cpuUsed = null;
HostStats hostStats = getManagementServer().getHostStatistics(hostVO.getId());
if (hostStats != null) {
float cpuUtil = (float) hostStats.getCpuUtilization();
cpuUsed = decimalFormat.format(cpuUtil) + "%";
hostRO.setCpuUsed(cpuUsed);
long avgLoad = (long)hostStats.getAverageLoad();
hostRO.setAverageLoad(avgLoad);
long networkKbsRead = (long)hostStats.getNetworkReadKBs();
hostRO.setNetworkKbsRead(networkKbsRead);
long networkKbsWrite = (long)hostStats.getNetworkWriteKBs();
hostRO.setNetworkKbsWrite(networkKbsWrite);
}
}
if ( hostVO.getType() == Host.Type.Routing) {
Long memory = hostVO.getTotalMemory();
hostRO.setTotalMemory(memory);
// calculate memory allocated by systemVM and userVm
long mem = getManagementServer().getMemoryUsagebyHost(hostVO.getId());
hostRO.setMemoryAllocated(mem);
// calculate memory utilized, we don't provide memory over commit
hostRO.setMemoryUsed(mem);
}
if (hostVO.getType().toString().equals("Storage")) {
hostRO.setDiskSizeTotal(hostVO.getTotalSize());
hostRO.setDiskSizeAllocated(0);
}
hostRO.setCaps(hostVO.getCapabilities());
hostRO.setLastPinged(hostVO.getLastPinged());
if (hostVO.getManagementServerId() != null) {
hostRO.setManagementServerId(hostVO.getManagementServerId());
}
if (hostVO.getCreated() != null) {
hostRO.setCreated(hostVO.getCreated());
}
if (hostVO.getRemoved() != null) {
hostRO.setRemoved(hostVO.getRemoved());
}
Set<Event> possibleEvents = hostVO.getStatus().getPossibleEvents();
hostRO.setEvents(possibleEvents);
return hostRO;
}
@Override
public String getResponse() {
// TODO Implement getResponse method
return null;
}
}

View File

@ -1,137 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.async.executor;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.network.IPAddressVO;
import com.cloud.serializer.GsonHelper;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.vm.DomainRouterVO;
import com.google.gson.Gson;
public class AssociateIpAddressExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(AssociateIpAddressExecutor.class.getName());
public boolean execute() {
Gson gson = GsonHelper.getBuilder().create();
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
ManagementServer managementServer = asyncMgr.getExecutorContext().getManagementServer();
AssociateIpAddressParam param = gson.fromJson(job.getCmdInfo(), AssociateIpAddressParam.class);
if(getSyncSource() == null) {
DomainRouterVO router = asyncMgr.getExecutorContext().getRouterDao().findBy(param.getAccountId(), param.getZoneId());
if(router == null) {
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.NET_INVALID_PARAM_ERROR, "Unable to find router with given zone " + param.getZoneId() + " and account " + param.getAccountId());
} else {
asyncMgr.syncAsyncJobExecution(job.getId(), "Router", router.getId());
}
return true;
} else {
try {
String ipAddress = managementServer.associateIpAddress(param.getUserId(), param.getAccountId(),
param.getDomainId(), param.getZoneId());
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0,
composeResultObject(managementServer, param, ipAddress));
} catch (ResourceAllocationException e) {
if(s_logger.isDebugEnabled())
s_logger.debug("Unable to associate ip address : " + e.getMessage());
if (e.getResourceType().equals("vm"))
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.VM_ALLOCATION_ERROR, e.getMessage());
else if (e.getResourceType().equals("ip"))
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.IP_ALLOCATION_ERROR, e.getMessage());
} catch (InsufficientAddressCapacityException e) {
if(s_logger.isDebugEnabled())
s_logger.debug("Unable to associate ip address : " + e.getMessage());
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.NET_IP_ASSOC_ERROR, e.getMessage());
} catch (InvalidParameterValueException e) {
if(s_logger.isDebugEnabled())
s_logger.debug("Unable to associate ip address : " + e.getMessage());
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.NET_INVALID_PARAM_ERROR, e.getMessage());
} catch (InternalErrorException e) {
if(s_logger.isDebugEnabled())
s_logger.debug("Unable to associate ip address : " + e.getMessage());
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, e.getMessage());
} catch(Exception e) {
s_logger.warn("Unable to associate ip address : " + e.getMessage(), e);
asyncMgr.completeAsyncJob(getJob().getId(),
AsyncJobResult.STATUS_FAILED, BaseCmd.INTERNAL_ERROR, e.getMessage());
}
}
return true;
}
private AssociateIpAddressResultObject composeResultObject(ManagementServer managementServer,
AssociateIpAddressParam param, String newIpAddr) {
AssociateIpAddressResultObject resultObject = new AssociateIpAddressResultObject();
resultObject.setIpAddress(newIpAddr);
List<IPAddressVO> ipAddresses = managementServer.listPublicIpAddressesBy(param.getAccountId(), true, null, null);
IPAddressVO ipAddress = null;
for (Iterator<IPAddressVO> iter = ipAddresses.iterator(); iter.hasNext();) {
IPAddressVO current = iter.next();
if (current.getAddress().equals(newIpAddr)) {
ipAddress = current;
break;
}
}
if(ipAddress != null) {
if(ipAddress.getAllocated() != null)
resultObject.setAllocated(ipAddress.getAllocated());
resultObject.setZoneId(ipAddress.getDataCenterId());
resultObject.setZoneName(managementServer.findDataCenterById(ipAddress.getDataCenterId()).getName());
resultObject.setSourceNat(ipAddress.isSourceNat());
resultObject.setVlanDbId(ipAddress.getVlanDbId());
resultObject.setVlanId(managementServer.findVlanById(ipAddress.getVlanDbId()).getVlanId());
Account account = getAsyncJobMgr().getExecutorContext().getManagementServer().findAccountById(param.getAccountId());
if(account != null)
resultObject.setAcountName(account.getAccountName());
else
resultObject.setAcountName("");
}
return resultObject;
}
}

View File

@ -1,68 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.async.executor;
public class AssociateIpAddressParam {
private long userId;
private long accountId;
private long domainId;
private long zoneId;
public AssociateIpAddressParam() {
}
public AssociateIpAddressParam(long userId, long accountId, long domainId, long zoneId) {
this.userId = userId;
this.accountId = accountId;
this.domainId = domainId;
this.zoneId = zoneId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
public long getDomainId() {
return domainId;
}
public void setDomainId(long domainId) {
this.domainId = domainId;
}
public long getZoneId() {
return zoneId;
}
public void setZoneId(long zoneId) {
this.zoneId = zoneId;
}
}

View File

@ -1,113 +0,0 @@
/**
* Copyright (C) 2010 Cloud.com, Inc. All rights reserved.
*
* This software is licensed under the GNU General Public License v3 or later.
*
* It is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.cloud.async.executor;
import java.util.Date;
import com.cloud.serializer.Param;
public class AssociateIpAddressResultObject {
@Param(name="ipaddress")
private String ipAddress;
@Param(name="zoneid")
private long zoneId;
@Param(name="zonename")
private String zoneName;
@Param(name="issourcenat")
private boolean sourceNat;
@Param(name="allocated")
private Date allocated;
@Param(name="account")
private String acountName;
@Param(name="vlanId")
private String vlanId;
@Param(name="vlanDbId")
private long vlanDbId;
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public long getZoneId() {
return zoneId;
}
public void setZoneId(long zoneId) {
this.zoneId = zoneId;
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
public boolean isSourceNat() {
return sourceNat;
}
public void setSourceNat(boolean sourceNat) {
this.sourceNat = sourceNat;
}
public Date getAllocated() {
return allocated;
}
public void setAllocated(Date allocated) {
this.allocated = allocated;
}
public String getAcountName() {
return acountName;
}
public void setAcountName(String acountName) {
this.acountName = acountName;
}
public long getVlanDbId() {
return vlanDbId;
}
public void setVlanDbId(long vlanDbId) {
this.vlanDbId = vlanDbId;
}
public String getVlanId() {
return vlanId;
}
public void setVlanId(String vlanId) {
this.vlanId = vlanId;
}
}

View File

@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.AssociateIPAddrCmd;
import com.cloud.api.commands.CreateIPForwardingRuleCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.DeletePortForwardingServiceRuleCmd;
@ -30,6 +31,7 @@ import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
@ -191,6 +193,13 @@ public interface NetworkManager extends Manager {
*/
boolean associateIP(DomainRouterVO router, List<String> ipAddrList, boolean add) throws ResourceAllocationException;
/**
* Associates a public IP address for a router.
* @param cmd
* @return
*/
String associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, InternalErrorException, InvalidParameterValueException;
boolean updateFirewallRule(FirewallRuleVO fwRule, String oldPrivateIP, String oldPrivatePort);
// boolean executeAssignToLoadBalancer(AssignToLoadBalancerExecutor executor, LoadBalancerParam param);

View File

@ -59,6 +59,7 @@ import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.AssociateIPAddrCmd;
import com.cloud.api.commands.CreateIPForwardingRuleCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.DeletePortForwardingServiceRuleCmd;
@ -92,6 +93,7 @@ import com.cloud.event.EventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
@ -1385,6 +1387,150 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
return true;
}
@Override
public String associateIP(AssociateIPAddrCmd cmd) throws ResourceAllocationException, InsufficientAddressCapacityException, InvalidParameterValueException, InternalErrorException {
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Long zoneId = cmd.getZoneId();
Account account = (Account)UserContext.current().getAccountObject();
Long userId = UserContext.current().getUserId();
Long accountId = null;
if ((account == null) || isAdmin(account.getType())) {
if (domainId != null) {
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid domain id (" + domainId + ") given, unable to associate IP address.");
}
if (accountName != null) {
Account userAccount = _accountDao.findActiveAccount(accountName, domainId);
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to find account " + accountName + " in domain " + domainId);
}
}
} else if (account != null) {
// the admin is acquiring an IP address
accountId = account.getId();
domainId = account.getDomainId();
} else {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account information is not specified.");
}
} else {
accountId = account.getId();
domainId = account.getDomainId();
}
if (userId == null) {
userId = Long.valueOf(1);
}
Transaction txn = Transaction.currentTxn();
AccountVO accountToLock = null;
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called for user " + userId + " account " + accountId);
}
accountToLock = _accountDao.acquire(accountId);
if (accountToLock == null) {
s_logger.warn("Unable to lock account: " + accountId);
throw new InternalErrorException("Unable to acquire account lock");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address lock acquired");
}
// Check that the maximum number of public IPs for the given
// accountId will not be exceeded
if (_accountMgr.resourceLimitExceeded(accountToLock, ResourceType.public_ip)) {
ResourceAllocationException rae = new ResourceAllocationException("Maximum number of public IP addresses for account: " + accountToLock.getAccountName()
+ " has been exceeded.");
rae.setResourceType("ip");
throw rae;
}
DomainRouterVO router = _routerDao.findBy(accountId, zoneId);
if (router == null) {
throw new InvalidParameterValueException("No router found for account: " + accountToLock.getAccountName() + ".");
}
txn.start();
String ipAddress = null;
Pair<String, VlanVO> ipAndVlan = _vlanDao.assignIpAddress(zoneId, accountId, domainId, VlanType.VirtualNetwork, false);
if (ipAndVlan == null) {
throw new InsufficientAddressCapacityException("Unable to find available public IP addresses");
} else {
ipAddress = ipAndVlan.first();
_accountMgr.incrementResourceCount(accountId, ResourceType.public_ip);
}
boolean success = true;
String errorMsg = "";
List<String> ipAddrs = new ArrayList<String>();
ipAddrs.add(ipAddress);
if (router.getState() == State.Running) {
success = associateIP(router, ipAddrs, true);
if (!success) {
errorMsg = "Unable to assign public IP address.";
}
}
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(accountId);
event.setType(EventTypes.EVENT_NET_IP_ASSIGN);
event.setParameters("address=" + ipAddress + "\nsourceNat=" + false + "\ndcId=" + zoneId);
if (!success) {
_ipAddressDao.unassignIpAddress(ipAddress);
ipAddress = null;
_accountMgr.decrementResourceCount(accountId, ResourceType.public_ip);
event.setLevel(EventVO.LEVEL_ERROR);
event.setDescription(errorMsg);
_eventDao.persist(event);
txn.commit();
throw new InternalErrorException(errorMsg);
} else {
event.setDescription("Assigned a public IP address: " + ipAddress);
_eventDao.persist(event);
}
txn.commit();
return ipAddress;
} catch (ResourceAllocationException rae) {
s_logger.error("Associate IP threw a ResourceAllocationException.", rae);
throw rae;
} catch (InsufficientAddressCapacityException iace) {
s_logger.error("Associate IP threw an InsufficientAddressCapacityException.", iace);
throw iace;
} catch (InvalidParameterValueException ipve) {
s_logger.error("Associate IP threw an InvalidParameterValueException.", ipve);
throw ipve;
} catch (InternalErrorException iee) {
s_logger.error("Associate IP threw an InternalErrorException.", iee);
throw iee;
} catch (Throwable t) {
s_logger.error("Associate IP address threw an exception.", t);
throw new InternalErrorException("Associate IP address exception");
} finally {
if (account != null) {
_accountDao.release(accountId);
s_logger.debug("Associate IP address lock released");
}
}
}
@Override
public boolean updateFirewallRule(final FirewallRuleVO rule, String oldPrivateIP, String oldPrivatePort) {

View File

@ -404,8 +404,8 @@ public interface ManagementServer {
* @throws InvalidParameterValueException if no router for that user exists in the zone specified
* @throws InternalErrorException if the new address could not be sent down to the router
*/
String associateIpAddress(long userId, long accountId, long domainId, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, InvalidParameterValueException, InternalErrorException;
long associateIpAddressAsync(long userId, long accountId, long domainId, long zoneId);
// String associateIpAddress(long userId, long accountId, long domainId, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException, InvalidParameterValueException, InternalErrorException;
// long associateIpAddressAsync(long userId, long accountId, long domainId, long zoneId);
/**
@ -416,7 +416,7 @@ public interface ManagementServer {
* @return success
*/
// boolean disassociateIpAddress(DisassociateIPAddrCmd cmd) throws PermissionDeniedException;
long disassociateIpAddressAsync(long userId, long accountId, String ipAddress);
// long disassociateIpAddressAsync(long userId, long accountId, String ipAddress);
/**
* Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated IP addresses.
@ -808,12 +808,6 @@ public interface ManagementServer {
*/
HostVO getHostBy(long hostId);
/**
* Updates a host
* @param hostId
* @param guestOSCategoryId
*/
void updateHost(long hostId, long guestOSCategoryId) throws InvalidParameterValueException;
// /**
// * Deletes a host

View File

@ -96,7 +96,6 @@ import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.async.dao.AsyncJobDao;
import com.cloud.async.executor.AssociateIpAddressParam;
import com.cloud.async.executor.AttachISOParam;
import com.cloud.async.executor.CopyTemplateParam;
import com.cloud.async.executor.CreateOrUpdateRuleParam;
@ -1484,128 +1483,128 @@ public class ManagementServerImpl implements ManagementServer {
return null;
}
@Override
@DB
public String associateIpAddress(long userId, long accountId, long domainId, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException,
InvalidParameterValueException, InternalErrorException {
Transaction txn = Transaction.currentTxn();
AccountVO account = null;
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address called for user " + userId + " account " + accountId);
}
account = _accountDao.acquire(accountId);
// @Override
// @DB
// public String associateIpAddress(long userId, long accountId, long domainId, long zoneId) throws ResourceAllocationException, InsufficientAddressCapacityException,
// InvalidParameterValueException, InternalErrorException {
// Transaction txn = Transaction.currentTxn();
// AccountVO account = null;
// try {
// if (s_logger.isDebugEnabled()) {
// s_logger.debug("Associate IP address called for user " + userId + " account " + accountId);
// }
// account = _accountDao.acquire(accountId);
//
// if (account == null) {
// s_logger.warn("Unable to lock account: " + accountId);
// throw new InternalErrorException("Unable to acquire account lock");
// }
//
// if (s_logger.isDebugEnabled()) {
// s_logger.debug("Associate IP address lock acquired");
// }
//
// // Check that the maximum number of public IPs for the given
// // accountId will not be exceeded
// if (_accountMgr.resourceLimitExceeded(account, ResourceType.public_ip)) {
// ResourceAllocationException rae = new ResourceAllocationException("Maximum number of public IP addresses for account: " + account.getAccountName()
// + " has been exceeded.");
// rae.setResourceType("ip");
// throw rae;
// }
//
// DomainRouterVO router = _routerDao.findBy(accountId, zoneId);
// if (router == null) {
// throw new InvalidParameterValueException("No router found for account: " + account.getAccountName() + ".");
// }
//
// txn.start();
//
// String ipAddress = null;
// Pair<String, VlanVO> ipAndVlan = _vlanDao.assignIpAddress(zoneId, accountId, domainId, VlanType.VirtualNetwork, false);
//
// if (ipAndVlan == null) {
// throw new InsufficientAddressCapacityException("Unable to find available public IP addresses");
// } else {
// ipAddress = ipAndVlan.first();
// _accountMgr.incrementResourceCount(accountId, ResourceType.public_ip);
// }
//
// boolean success = true;
// String errorMsg = "";
//
// List<String> ipAddrs = new ArrayList<String>();
// ipAddrs.add(ipAddress);
//
// if (router.getState() == State.Running) {
// success = _networkMgr.associateIP(router, ipAddrs, true);
// if (!success) {
// errorMsg = "Unable to assign public IP address.";
// }
// }
//
// EventVO event = new EventVO();
// event.setUserId(userId);
// event.setAccountId(accountId);
// event.setType(EventTypes.EVENT_NET_IP_ASSIGN);
// event.setParameters("address=" + ipAddress + "\nsourceNat=" + false + "\ndcId=" + zoneId);
//
// if (!success) {
// _publicIpAddressDao.unassignIpAddress(ipAddress);
// ipAddress = null;
// _accountMgr.decrementResourceCount(accountId, ResourceType.public_ip);
//
// event.setLevel(EventVO.LEVEL_ERROR);
// event.setDescription(errorMsg);
// _eventDao.persist(event);
// txn.commit();
//
// throw new InternalErrorException(errorMsg);
// } else {
// event.setDescription("Assigned a public IP address: " + ipAddress);
// _eventDao.persist(event);
// }
//
// txn.commit();
// return ipAddress;
//
// } catch (ResourceAllocationException rae) {
// s_logger.error("Associate IP threw a ResourceAllocationException.", rae);
// throw rae;
// } catch (InsufficientAddressCapacityException iace) {
// s_logger.error("Associate IP threw an InsufficientAddressCapacityException.", iace);
// throw iace;
// } catch (InvalidParameterValueException ipve) {
// s_logger.error("Associate IP threw an InvalidParameterValueException.", ipve);
// throw ipve;
// } catch (InternalErrorException iee) {
// s_logger.error("Associate IP threw an InternalErrorException.", iee);
// throw iee;
// } catch (Throwable t) {
// s_logger.error("Associate IP address threw an exception.", t);
// throw new InternalErrorException("Associate IP address exception");
// } finally {
// if (account != null) {
// _accountDao.release(accountId);
// s_logger.debug("Associate IP address lock released");
// }
// }
// }
if (account == null) {
s_logger.warn("Unable to lock account: " + accountId);
throw new InternalErrorException("Unable to acquire account lock");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Associate IP address lock acquired");
}
// Check that the maximum number of public IPs for the given
// accountId will not be exceeded
if (_accountMgr.resourceLimitExceeded(account, ResourceType.public_ip)) {
ResourceAllocationException rae = new ResourceAllocationException("Maximum number of public IP addresses for account: " + account.getAccountName()
+ " has been exceeded.");
rae.setResourceType("ip");
throw rae;
}
DomainRouterVO router = _routerDao.findBy(accountId, zoneId);
if (router == null) {
throw new InvalidParameterValueException("No router found for account: " + account.getAccountName() + ".");
}
txn.start();
String ipAddress = null;
Pair<String, VlanVO> ipAndVlan = _vlanDao.assignIpAddress(zoneId, accountId, domainId, VlanType.VirtualNetwork, false);
if (ipAndVlan == null) {
throw new InsufficientAddressCapacityException("Unable to find available public IP addresses");
} else {
ipAddress = ipAndVlan.first();
_accountMgr.incrementResourceCount(accountId, ResourceType.public_ip);
}
boolean success = true;
String errorMsg = "";
List<String> ipAddrs = new ArrayList<String>();
ipAddrs.add(ipAddress);
if (router.getState() == State.Running) {
success = _networkMgr.associateIP(router, ipAddrs, true);
if (!success) {
errorMsg = "Unable to assign public IP address.";
}
}
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(accountId);
event.setType(EventTypes.EVENT_NET_IP_ASSIGN);
event.setParameters("address=" + ipAddress + "\nsourceNat=" + false + "\ndcId=" + zoneId);
if (!success) {
_publicIpAddressDao.unassignIpAddress(ipAddress);
ipAddress = null;
_accountMgr.decrementResourceCount(accountId, ResourceType.public_ip);
event.setLevel(EventVO.LEVEL_ERROR);
event.setDescription(errorMsg);
_eventDao.persist(event);
txn.commit();
throw new InternalErrorException(errorMsg);
} else {
event.setDescription("Assigned a public IP address: " + ipAddress);
_eventDao.persist(event);
}
txn.commit();
return ipAddress;
} catch (ResourceAllocationException rae) {
s_logger.error("Associate IP threw a ResourceAllocationException.", rae);
throw rae;
} catch (InsufficientAddressCapacityException iace) {
s_logger.error("Associate IP threw an InsufficientAddressCapacityException.", iace);
throw iace;
} catch (InvalidParameterValueException ipve) {
s_logger.error("Associate IP threw an InvalidParameterValueException.", ipve);
throw ipve;
} catch (InternalErrorException iee) {
s_logger.error("Associate IP threw an InternalErrorException.", iee);
throw iee;
} catch (Throwable t) {
s_logger.error("Associate IP address threw an exception.", t);
throw new InternalErrorException("Associate IP address exception");
} finally {
if (account != null) {
_accountDao.release(accountId);
s_logger.debug("Associate IP address lock released");
}
}
}
@Override
public long associateIpAddressAsync(long userId, long accountId, long domainId, long zoneId) {
AssociateIpAddressParam param = new AssociateIpAddressParam(userId, accountId, domainId, zoneId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(accountId);
job.setCmd("AssociateIpAddress");
job.setCmdInfo(gson.toJson(param));
job.setCmdOriginator(AssociateIPAddrCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long associateIpAddressAsync(long userId, long accountId, long domainId, long zoneId) {
// AssociateIpAddressParam param = new AssociateIpAddressParam(userId, accountId, domainId, zoneId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(accountId);
// job.setCmd("AssociateIpAddress");
// job.setCmdInfo(gson.toJson(param));
// job.setCmdOriginator(AssociateIPAddrCmd.getResultObjectName());
//
// return _asyncMgr.submitAsyncJob(job, true);
// }
// @Override
// @DB
@ -1699,19 +1698,19 @@ public class ManagementServerImpl implements ManagementServer {
// }
// }
@Override
public long disassociateIpAddressAsync(long userId, long accountId, String ipAddress) {
DisassociateIpAddressParam param = new DisassociateIpAddressParam(userId, accountId, ipAddress);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(accountId);
job.setCmd("DisassociateIpAddress");
job.setCmdInfo(gson.toJson(param));
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long disassociateIpAddressAsync(long userId, long accountId, String ipAddress) {
// DisassociateIpAddressParam param = new DisassociateIpAddressParam(userId, accountId, ipAddress);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(accountId);
// job.setCmd("DisassociateIpAddress");
// job.setCmdInfo(gson.toJson(param));
//
// return _asyncMgr.submitAsyncJob(job, true);
// }
@Override
public VolumeVO createVolume(long userId, long accountId, String name, long zoneId, long diskOfferingId, long startEventId, long size) throws InternalErrorException {
@ -2831,17 +2830,6 @@ public class ManagementServerImpl implements ManagementServer {
public HostVO getHostBy(long hostId) {
return _hostDao.findById(hostId);
}
public void updateHost(long hostId, long guestOSCategoryId) throws InvalidParameterValueException {
// Verify that the guest OS Category exists
if (guestOSCategoryId > 0) {
if (_guestOSCategoryDao.findById(guestOSCategoryId) == null) {
throw new InvalidParameterValueException("Please specify a valid guest OS category.");
}
}
_agentMgr.updateHost(hostId, guestOSCategoryId);
}
// public boolean deleteHost(long hostId) {
// return _agentMgr.deleteHost(hostId);