Merge branch '2.1.refactor' of ssh://git.cloud.com/var/lib/git/cloudstack-oss into 2.1.refactor

Conflicts:
	server/src/com/cloud/api/BaseCmd.java
	server/src/com/cloud/network/security/NetworkGroupManagerImpl.java
This commit is contained in:
alena 2010-08-18 11:36:05 -07:00
commit e2950eb5a1
41 changed files with 2438 additions and 2036 deletions

View File

@ -15,6 +15,7 @@ import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd.CommandType;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.network.NetworkManager;
import com.cloud.network.security.NetworkGroupManager;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.utils.DateUtil;
@ -30,6 +31,7 @@ public class ApiDispatcher {
private ConfigurationManager _configMgr;
private ManagementServer _mgmtServer;
private NetworkGroupManager _networkGroupMgr;
private NetworkManager _networkMgr;
private StorageManager _storageMgr;
private UserVmManager _userVmMgr;
@ -38,6 +40,7 @@ public class ApiDispatcher {
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_mgmtServer = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
_configMgr = locator.getManager(ConfigurationManager.class);
_networkGroupMgr = locator.getManager(NetworkGroupManager.class);
_networkMgr = locator.getManager(NetworkManager.class);
_storageMgr = locator.getManager(StorageManager.class);
_userVmMgr = locator.getManager(UserVmManager.class);
@ -86,6 +89,9 @@ public class ApiDispatcher {
case ConfigManager:
mgr = _configMgr;
break;
case NetworkGroupManager:
mgr = _networkGroupMgr;
break;
case NetworkManager:
mgr = _networkMgr;
break;
@ -115,7 +121,7 @@ public class ApiDispatcher {
}
}
@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", "rawtypes"})
private void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation) throws IllegalArgumentException, ParseException {
try {
field.setAccessible(true);

View File

@ -46,9 +46,9 @@ public abstract class BaseCmd {
public enum CommandType {
BOOLEAN, DATE, FLOAT, INTEGER, LIST, LONG, OBJECT, MAP, STRING, TZDATE
}
public enum Manager {
ConfigManager, ManagementServer, NetworkManager, StorageManager, UserVmManager, AgentManager
public enum Manager {
ConfigManager, ManagementServer, NetworkGroupManager, NetworkManager, StorageManager, UserVmManager, AccountManager, AgentManager
}
// FIXME: Extract these out into a separate file
@ -97,9 +97,20 @@ public abstract class BaseCmd {
public static final DateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final DateFormat _outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private Object _responseObject = null;
public abstract String getName();
public abstract String getResponse();
public Object getResponseObject() {
return _responseObject;
}
public void setResponseObject(Object responseObject) {
_responseObject = responseObject;
}
public String getDateString(Date date) {
if (date == null) {
return "";

View File

@ -0,0 +1,4 @@
package com.cloud.api;
public interface ResponseObject {
}

View File

@ -18,8 +18,6 @@
package com.cloud.api.commands;
import java.util.Date;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
@ -27,7 +25,7 @@ import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.serializer.Param;
import com.cloud.api.response.DiskOfferingResponse;
import com.cloud.serializer.SerializerHelper;
import com.cloud.storage.DiskOfferingVO;
@ -84,8 +82,6 @@ public class CreateDiskOfferingCmd extends BaseCmd {
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
private DiskOfferingVO responseObject = null;
@Override
public String getName() {
return s_name;
@ -94,6 +90,7 @@ public class CreateDiskOfferingCmd extends BaseCmd {
@Override
public String getResponse() {
DiskOfferingResponse response = new DiskOfferingResponse();
DiskOfferingVO responseObject = (DiskOfferingVO)getResponseObject();
if (responseObject != null) {
response.setId(responseObject.getId());
response.setCreated(responseObject.getCreated());
@ -109,99 +106,4 @@ public class CreateDiskOfferingCmd extends BaseCmd {
}
return SerializerHelper.toSerializedString(responseObject);
}
public void setResponseObject(DiskOfferingVO diskOffering) {
responseObject = diskOffering;
}
// helper class for the response object
private class DiskOfferingResponse {
@Param(name="id")
private Long id;
@Param(name="domainid")
private Long domainId;
@Param(name="domain")
private String domain;
@Param(name="name")
private String name;
@Param(name="displaytext")
private String displayText;
@Param(name="disksize")
private Long diskSize;
@Param(name="created")
private Date created;
@Param(name="tags")
private String tags;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getDomainId() {
return domainId;
}
public void setDomainId(Long domainId) {
this.domainId = domainId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
}
public Long getDiskSize() {
return diskSize;
}
public void setDiskSize(Long diskSize) {
this.diskSize = diskSize;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
}
}

View File

@ -18,30 +18,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.DomainResponse;
import com.cloud.domain.DomainVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="createDomain")
public class CreateDomainCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateDomainCmd.class.getName());
private static final String s_name = "createdomainresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PARENT_DOMAIN_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -75,62 +66,21 @@ public class CreateDomainCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
String name = (String)params.get(BaseCmd.Properties.NAME.getName());
Long parentDomainId = (Long)params.get(BaseCmd.Properties.PARENT_DOMAIN_ID.getName());
// If account is null, consider System as an owner for this action
if (account == null) {
account = getManagementServer().findAccountById(Long.valueOf(1L));
}
if (parentDomainId == null){
parentDomainId = DomainVO.ROOT_DOMAIN;
} else {
DomainVO parentDomain = null;
parentDomain = getManagementServer().findDomainIdById(parentDomainId);
if (parentDomain == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find parent domain " + parentDomainId);
}
}
if (!getManagementServer().isChildDomain(account.getDomainId(), parentDomainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Invalid parent domain " + parentDomainId + ", unable to create domain " + name);
}
DomainVO domain = null;
try {
domain = getManagementServer().createDomain(name, account.getId(), parentDomainId);
} catch (IllegalArgumentException illArgEx) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Failed to create domain " + name + " due to invalid name given.");
}
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to create domain " + name + ", invalid name given. The character '/' is not valid for domain names.");
} catch (Exception ex) {
s_logger.error("Exception creating domain", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create domain " + name + ": internal error.");
}
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
if (domain == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to create domain " + name + ": a domain with that name already exists.");
} else {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), domain.getId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), domain.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.LEVEL.getName(), domain.getLevel().toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PARENT_DOMAIN_ID.getName(), domain.getParent().toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PARENT_DOMAIN_NAME.getName(),
getManagementServer().findDomainIdById(domain.getParent()).getName()));
embeddedObject.add(new Pair<String, Object>("domain", new Object[] { returnValues } ));
}
return embeddedObject;
}
@Override
public String getResponse() {
DomainResponse response = new DomainResponse();
DomainVO responseObject = (DomainVO)getResponseObject();
if (responseObject != null) {
response.setId(responseObject.getId());
response.setDomainName(responseObject.getName());
response.setLevel(responseObject.getLevel());
response.setParentDomainId(responseObject.getParent());
// FIXME: domain name from id for parent domain
// response.setParentDomainName(responseObject.getParentDomainName());
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create domain");
}
return SerializerHelper.toSerializedString(responseObject);
}
}

View File

@ -18,38 +18,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.exception.NetworkRuleConflictException;
import com.cloud.api.response.FirewallRuleResponse;
import com.cloud.network.FirewallRuleVO;
import com.cloud.network.IPAddressVO;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.vm.UserVmVO;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="createPortForwardingRule", manager=Manager.NetworkManager)
public class CreateIPForwardingRuleCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateIPForwardingRuleCmd.class.getName());
private static final String s_name = "createportforwardingruleresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.IP_ADDRESS, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PRIVATE_PORT, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PROTOCOL, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PUBLIC_PORT, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.VIRTUAL_MACHINE_ID, Boolean.TRUE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -104,85 +87,20 @@ public class CreateIPForwardingRuleCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
String ipAddress = (String)params.get(BaseCmd.Properties.IP_ADDRESS.getName());
String publicPort = (String)params.get(BaseCmd.Properties.PUBLIC_PORT.getName());
String privatePort = (String)params.get(BaseCmd.Properties.PRIVATE_PORT.getName());
String protocol = (String)params.get(BaseCmd.Properties.PROTOCOL.getName());
Long vmId = (Long)params.get(BaseCmd.Properties.VIRTUAL_MACHINE_ID.getName());
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
IPAddressVO ipAddressVO = getManagementServer().findIPAddressById(ipAddress);
if (ipAddressVO == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find IP address " + ipAddress);
}
UserVmVO userVM = getManagementServer().findUserVMInstanceById(vmId);
if (userVM == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find virtual machine with id " + vmId);
}
if ((ipAddressVO.getAccountId() == null) || (ipAddressVO.getAccountId().longValue() != userVM.getAccountId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create port forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString());
}
if (ipAddressVO.getDataCenterId() != userVM.getDataCenterId()) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create port forwarding rule, IP address " + ipAddress + " owner is not in the same availability zone as virtual machine " + userVM.toString());
}
// if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
if (account != null) {
if (isAdmin(account.getType())) {
Account vmOwner = getManagementServer().findAccountById(userVM.getAccountId());
if (!getManagementServer().isChildDomain(account.getDomainId(), vmOwner.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + vmId + ", permission denied.");
}
} else if (account.getId().longValue() != userVM.getAccountId()) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + vmId + ", permission denied.");
}
}
FirewallRuleVO firewallRule = null;
try {
firewallRule = getManagementServer().createPortForwardingRule(userId.longValue(), ipAddressVO, userVM, publicPort, privatePort, protocol);
} catch (NetworkRuleConflictException ex) {
throw new ServerApiException(BaseCmd.NET_CONFLICT_IPFW_RULE_ERROR, "Network rule conflict creating a forwarding rule on address:port " + ipAddress + ":" + publicPort + " to virtual machine " + userVM.toString());
} catch (IllegalArgumentException argEx) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, argEx.getMessage());
}
if (firewallRule == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "The port forwarding rule from public port " + publicPort + " to private port " + privatePort + " for address " + ipAddress + " and virtual machine " + userVM.toString() + " already exists.");
}
List<Pair<String, Object>> groupsTags = new ArrayList<Pair<String, Object>>();
Object[] forwardingTag = new Object[1];
List<Pair<String, Object>> ruleData = new ArrayList<Pair<String, Object>>();
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), firewallRule.getId().toString()));
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.PUBLIC_PORT.getName(), firewallRule.getPublicPort()));
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.PRIVATE_PORT.getName(), firewallRule.getPrivatePort()));
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.PROTOCOL.getName(), firewallRule.getProtocol()));
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.VIRTUAL_MACHINE_NAME.getName(), userVM.getName()));
ruleData.add(new Pair<String, Object>(BaseCmd.Properties.VIRTUAL_MACHINE_ID.getName(), Long.toString(userVM.getId())));
forwardingTag[0] = ruleData;
Pair<String, Object> eventTag = new Pair<String, Object>("portforwardingrule", forwardingTag);
groupsTags.add(eventTag);
return groupsTags;
}
public String getResponse() {
FirewallRuleVO fwRule = (FirewallRuleVO)getResponseObject();
FirewallRuleResponse fwResponse = new FirewallRuleResponse();
fwResponse.setId(fwRule.getId());
fwResponse.setPrivatePort(fwRule.getPrivatePort());
fwResponse.setProtocol(fwRule.getProtocol());
fwResponse.setPublicPort(fwRule.getPublicPort());
// TODO: implement
// fwResponse.setVirtualMachineId(fwRule.getVirtualMachineId());
// fwResponse.setVirtualMachineName(fwRule.getVirtualMachineName());
return SerializerHelper.toSerializedString(fwResponse);
}
}

View File

@ -18,44 +18,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.network.IPAddressVO;
import com.cloud.api.response.LoadBalancerResponse;
import com.cloud.network.LoadBalancerVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="createLoadBalancerRule", manager=Manager.NetworkManager)
public class CreateLoadBalancerRuleCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName());
private static final String s_name = "createloadbalancerruleresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ALGORITHM, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DESCRIPTION, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PRIVATE_PORT, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PUBLIC_IP, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PUBLIC_PORT, Boolean.TRUE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -115,99 +92,25 @@ public class CreateLoadBalancerRuleCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
String name = (String)params.get(BaseCmd.Properties.NAME.getName());
String description = (String)params.get(BaseCmd.Properties.DESCRIPTION.getName());
String publicIP = (String)params.get(BaseCmd.Properties.PUBLIC_IP.getName());
String publicPort = (String)params.get(BaseCmd.Properties.PUBLIC_PORT.getName());
String privatePort = (String)params.get(BaseCmd.Properties.PRIVATE_PORT.getName());
String algorithm = (String)params.get(BaseCmd.Properties.ALGORITHM.getName());
public String getResponse() {
LoadBalancerVO responseObj = (LoadBalancerVO)getResponseObject();
UserVmDao _userVmDao;
ComponentLocator locator = ComponentLocator.getLocator("management-server");
_userVmDao = locator.getDao(UserVmDao.class);
if (userId == null) {
userId = Long.valueOf(1);
}
LoadBalancerResponse response = new LoadBalancerResponse();
response.setAlgorithm(responseObj.getAlgorithm());
response.setDescription(responseObj.getDescription());
response.setId(responseObj.getId());
response.setName(responseObj.getName());
response.setPrivatePort(responseObj.getPrivatePort());
response.setPublicIp(responseObj.getIpAddress());
response.setPublicPort(responseObj.getPublicPort());
response.setAccountName(responseObj.getAccountName());
response.setDomainId(responseObj.getDomainId());
// TODO: implement
// response.setDomainName(responseObj.getDomainName());
IPAddressVO ipAddr = getManagementServer().findIPAddressById(publicIP);
if (ipAddr == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create load balancer rule, invalid IP address " + publicIP);
}
VlanVO vlan = getManagementServer().findVlanById(ipAddr.getVlanDbId());
if (vlan != null) {
if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create load balancer rule for IP address " + publicIP + ", only VirtualNetwork type IP addresses can be used for load balancers.");
}
} // else ERROR?
// Verify input parameters
Account accountByIp = getManagementServer().findAccountByIpAddress(publicIP);
if(accountByIp == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create load balancer rule, cannot find account owner for ip " + publicIP);
}
Long accountId = accountByIp.getId();
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId().longValue() != accountId.longValue()) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create load balancer rule, account " + account.getAccountName() + " doesn't own ip address " + publicIP);
}
} else if (!getManagementServer().isChildDomain(account.getDomainId(), accountByIp.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create load balancer rule on IP address " + publicIP + ", permission denied.");
}
}
List<UserVmVO> userVmVO = _userVmDao.listByAccountId(accountId);
if(userVmVO.size()==0)
{
//this means there are no associated vm's to the user account, and hence, the load balancer cannot be created
throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "Unable to create load balancer rule, no vm for the user exists.");
}
LoadBalancerVO existingLB = getManagementServer().findLoadBalancer(accountId, name);
if (existingLB != null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create load balancer rule, an existing load balancer rule with name " + name + " already exisits.");
}
try {
LoadBalancerVO loadBalancer = getManagementServer().createLoadBalancer(userId, accountId, name, description, publicIP, publicPort, privatePort, algorithm);
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), loadBalancer.getId().toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), loadBalancer.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DESCRIPTION.getName(), loadBalancer.getDescription()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PUBLIC_IP.getName(), loadBalancer.getIpAddress()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PUBLIC_PORT.getName(), loadBalancer.getPublicPort()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PRIVATE_PORT.getName(), loadBalancer.getPrivatePort()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ALGORITHM.getName(), loadBalancer.getAlgorithm()));
Account accountTemp = getManagementServer().findAccountById(loadBalancer.getAccountId());
if (accountTemp != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ACCOUNT.getName(), accountTemp.getAccountName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), accountTemp.getDomainId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(accountTemp.getDomainId()).getName()));
}
embeddedObject.add(new Pair<String, Object>("loadbalancerrule", new Object[] { returnValues } ));
return embeddedObject;
} catch (InvalidParameterValueException paramError) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, paramError.getMessage());
} catch (PermissionDeniedException permissionError) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, permissionError.getMessage());
} catch (Exception ex) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
return SerializerHelper.toSerializedString(response);
}
}

View File

@ -18,34 +18,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.api.response.NetworkGroupResponse;
import com.cloud.network.security.NetworkGroupVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="createLoadBalancerRule", manager=Manager.NetworkGroupManager)
public class CreateNetworkGroupCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreateNetworkGroupCmd.class.getName());
private static final String s_name = "createnetworkgroupresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
//s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DESCRIPTION, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DOMAIN_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.TRUE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -92,79 +79,20 @@ public class CreateNetworkGroupCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long domainId = (Long)params.get(BaseCmd.Properties.DOMAIN_ID.getName());
//Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
String accountName = (String)params.get(BaseCmd.Properties.ACCOUNT.getName());
String name = (String)params.get(BaseCmd.Properties.NAME.getName());
String description = (String)params.get(BaseCmd.Properties.DESCRIPTION.getName());
Long accountId = null;
public String getResponse() {
NetworkGroupVO group = (NetworkGroupVO)getResponseObject();
if (account != null) {
if (isAdmin(account.getType())) {
if (domainId != null) {
if (!getManagementServer().isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create network group in domain " + domainId + ", permission denied.");
}
} else {
// the admin must be creating the network group
if (account != null) {
accountId = account.getId();
domainId = account.getDomainId();
accountName = account.getAccountName();
}
}
} else {
accountId = account.getId();
domainId = account.getDomainId();
accountName = account.getAccountName();
}
}
NetworkGroupResponse response = new NetworkGroupResponse();
response.setAccountName(group.getAccountName());
response.setDescription(group.getDescription());
response.setDomainId(group.getDomainId());
// TODO: implement
// response.setDomainName(group.getDomainName());
response.setId(group.getId());
response.setName(group.getName());
if (accountId == null) {
if ((accountName != null) && (domainId != null)) {
Account userAccount = getManagementServer().findActiveAccount(accountName, domainId);
if (userAccount != null) {
accountId = userAccount.getId();
accountName = userAccount.getAccountName();
} else {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "could not find account " + accountName + " in domain " + domainId);
}
}
}
if (accountId == null) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to create network group, no account specified.");
}
boolean isNameInUse = getManagementServer().isNetworkSecurityGroupNameInUse(domainId, accountId, name);
if (isNameInUse) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to create network group, a group with name " + name + " already exisits.");
}
NetworkGroupVO networkGroup = getManagementServer().createNetworkGroup(name, description, domainId, accountId, accountName);
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), networkGroup.getId().toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), networkGroup.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DESCRIPTION.getName(), networkGroup.getDescription()));
Account accountTemp = getManagementServer().findAccountById(networkGroup.getAccountId());
if (accountTemp != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ACCOUNT.getName(), accountTemp.getAccountName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), accountTemp.getDomainId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(accountTemp.getDomainId()).getName()));
}
embeddedObject.add(new Pair<String, Object>("networkgroup", new Object[] { returnValues } ));
return embeddedObject;
return SerializerHelper.toSerializedString(response);
}
}

View File

@ -18,36 +18,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.dc.DataCenterVO;
import com.cloud.api.response.PodResponse;
import com.cloud.dc.HostPodVO;
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="createPod", manager=Manager.ConfigManager)
public class CreatePodCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(CreatePodCmd.class.getName());
private static final String s_name = "createpodresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.CIDR, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.END_IP, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.GATEWAY, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.START_IP, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ZONE_ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -108,57 +93,22 @@ public class CreatePodCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
String podName = (String) params.get(BaseCmd.Properties.NAME.getName());
Long zoneId = (Long) params.get(BaseCmd.Properties.ZONE_ID.getName());
String gateway = (String) params.get(BaseCmd.Properties.GATEWAY.getName());
String cidr = (String) params.get(BaseCmd.Properties.CIDR.getName());
String startIp = (String) params.get(BaseCmd.Properties.START_IP.getName());
String endIp = (String) params.get(BaseCmd.Properties.END_IP.getName());
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
//verify input parameters
DataCenterVO zone = getManagementServer().findDataCenterById(zoneId);
if (zone == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find zone by id " + zoneId);
}
public String getResponse() {
HostPodVO pod = (HostPodVO)getResponseObject();
if (endIp != null && startIp == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "If an end IP is specified, a start IP must be specified.");
}
HostPodVO pod = null;
try {
pod = getManagementServer().createPod(userId, podName, zoneId, gateway, cidr, startIp, endIp);
} catch (Exception ex) {
s_logger.error("Exception creating pod", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
PodResponse response = new PodResponse();
response.setId(pod.getId());
response.setCidr(pod.getCidrAddress() + "/" + pod.getCidrSize());
// TODO: implement
// response.setEndIp(pod.getEndIp());
// response.setStartIp(pod.getStartIp());
// response.setZoneName(pod.getZoneName());
response.setGateway(pod.getGateway());
response.setName(pod.getName());
response.setZoneId(pod.getDataCenterId());
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
if (pod == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create pod; internal error.");
} else {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), pod.getId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), podName));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_ID.getName(), zoneId));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_NAME.getName(), zone.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.GATEWAY.getName(), pod.getGateway()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CIDR.getName(), cidr));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.START_IP.getName(), startIp));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.END_IP.getName(), endIp != null ? endIp : ""));
}
return returnValues;
return SerializerHelper.toSerializedString(response);
}
}

View File

@ -2,23 +2,17 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.api.Implementation;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="updateTemplatePermissions", manager=Manager.ManagementServer)
public class UpdateIsoPermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd {
protected String getResponseName() {
return "updateisopermissionsresponse";
}
protected String getMediaType() {
return "iso";
}
protected Logger getLogger() {
return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName());
}
protected boolean templateIsCorrectType(VMTemplateVO template) {
return template.getFormat().equals(ImageFormat.ISO);
}
}

View File

@ -18,36 +18,18 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.user.User;
import com.cloud.utils.Pair;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="editPod", manager=Manager.ConfigManager)
public class UpdatePodCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdatePodCmd.class.getName());
private static final String s_name = "updatepodresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.CIDR, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.END_IP, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.GATEWAY, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.START_IP, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -106,57 +88,60 @@ public class UpdatePodCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long podId = (Long) params.get(BaseCmd.Properties.ID.getName());
String podName = (String) params.get(BaseCmd.Properties.NAME.getName());
String gateway = (String) params.get(BaseCmd.Properties.GATEWAY.getName());
String cidr = (String) params.get(BaseCmd.Properties.CIDR.getName());
String startIp = (String) params.get(BaseCmd.Properties.START_IP.getName());
String endIp = (String) params.get(BaseCmd.Properties.END_IP.getName());
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
//verify parameters
HostPodVO pod = getManagementServer().findHostPodById(podId);
if (pod == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find pod by id " + podId);
}
long zoneId = pod.getDataCenterId();
DataCenterVO zone = getManagementServer().findDataCenterById(zoneId);
if (zone == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find zone by id " + zoneId);
}
if (endIp != null && startIp == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "If an end IP is specified, a start IP must be specified.");
}
HostPodVO updatedPod = null;
try {
updatedPod = getManagementServer().editPod(userId, podId, podName, gateway, cidr, startIp, endIp);
} catch (Exception ex) {
s_logger.error("Exception updating pod", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
}
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
if (updatedPod == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update pod; internal error.");
} else {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.SUCCESS.getName(), "true"));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISPLAY_TEXT.getName(), "Successfully updated pod."));
}
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long podId = (Long) params.get(BaseCmd.Properties.ID.getName());
// String podName = (String) params.get(BaseCmd.Properties.NAME.getName());
// String gateway = (String) params.get(BaseCmd.Properties.GATEWAY.getName());
// String cidr = (String) params.get(BaseCmd.Properties.CIDR.getName());
// String startIp = (String) params.get(BaseCmd.Properties.START_IP.getName());
// String endIp = (String) params.get(BaseCmd.Properties.END_IP.getName());
// Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
//
// if (userId == null) {
// userId = Long.valueOf(User.UID_SYSTEM);
// }
//
// //verify parameters
// HostPodVO pod = getManagementServer().findHostPodById(podId);
// if (pod == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find pod by id " + podId);
// }
//
// long zoneId = pod.getDataCenterId();
// DataCenterVO zone = getManagementServer().findDataCenterById(zoneId);
// if (zone == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find zone by id " + zoneId);
// }
//
// if (endIp != null && startIp == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "If an end IP is specified, a start IP must be specified.");
// }
//
// HostPodVO updatedPod = null;
// try {
// updatedPod = getManagementServer().editPod(userId, podId, podName, gateway, cidr, startIp, endIp);
// } catch (Exception ex) {
// s_logger.error("Exception updating pod", ex);
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage());
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
//
// if (updatedPod == null) {
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update pod; internal error.");
// } else {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.SUCCESS.getName(), "true"));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISPLAY_TEXT.getName(), "Successfully updated pod."));
// }
//
// return returnValues;
// }
}

View File

@ -25,8 +25,10 @@ import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.domain.DomainVO;
@ -35,20 +37,12 @@ import com.cloud.server.Criteria;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
@Implementation(method="updateResourceLimit", manager=Manager.AccountManager)
public class UpdateResourceLimitCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateResourceLimitCmd.class.getName());
private static final String s_name = "updateresourcelimitresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DOMAIN_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.MAX, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.RESOURCE_TYPE, Boolean.TRUE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -94,117 +88,119 @@ public class UpdateResourceLimitCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long domainId = (Long) params.get(BaseCmd.Properties.DOMAIN_ID.getName());
String accountName = (String) params.get(BaseCmd.Properties.ACCOUNT.getName());
Integer type = (Integer) params.get(BaseCmd.Properties.RESOURCE_TYPE.getName());
Long max = (Long) params.get(BaseCmd.Properties.MAX.getName());
Long accountId = null;
@Override
public String getResponse() {
// TODO look at the execute method to construct response
return null;
}
if (max == null) {
max = new Long(-1);
} else if (max < -1) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify either '-1' for an infinite limit, or a limit that is at least '0'.");
}
// Map resource type
ResourceType resourceType;
try {
resourceType = ResourceType.values()[type];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid resource type.");
}
/*
if (accountName==null && domainId != null && !domainId.equals(DomainVO.ROOT_DOMAIN)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Resource limits must be made for an account or the ROOT domain.");
}
*/
if (account != null) {
if (domainId != null) {
if (!getManagementServer().isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((accountName == null) ? "" : "account " + accountName + " in ") + "domain " + domainId + ", permission denied");
}
} else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
domainId = DomainVO.ROOT_DOMAIN; // for root admin, default to root domain if domain is not specified
}
if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
if ((domainId != null) && (accountName == null) && domainId.equals(account.getDomainId())) {
// if the admin is trying to update their own domain, disallow...
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((accountName == null) ? "" : "account " + accountName + " in ") + "domain " + domainId + ", permission denied");
}
// If there is an existing ROOT domain limit, make sure its max isn't being exceeded
Criteria c = new Criteria();
c.addCriteria(Criteria.DOMAINID, DomainVO.ROOT_DOMAIN);
c.addCriteria(Criteria.TYPE, resourceType);
List<ResourceLimitVO> currentRootDomainLimits = getManagementServer().searchForLimits(c);
ResourceLimitVO currentRootDomainLimit = (currentRootDomainLimits.size() == 0) ? null : currentRootDomainLimits.get(0);
if (currentRootDomainLimit != null) {
long currentRootDomainMax = currentRootDomainLimits.get(0).getMax();
if ((max == -1 && currentRootDomainMax != -1) || max > currentRootDomainMax) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "The current ROOT domain limit for resource type " + resourceType + " is " + currentRootDomainMax + " and cannot be exceeded.");
}
}
}
} else if (domainId == null) {
domainId = DomainVO.ROOT_DOMAIN; // for system commands, default to root domain if domain is not specified
}
if (domainId == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to update resource limit, unable to determine domain in which to update limit.");
} else if (accountName != null) {
Account userAccount = getManagementServer().findActiveAccount(accountName, domainId);
if (userAccount == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find account by name " + accountName + " in domain with id " + domainId);
}
accountId = userAccount.getId();
domainId = userAccount.getDomainId();
}
ResourceLimitVO limit = null;
try {
if (accountId != null) domainId = null;
limit = getManagementServer().updateResourceLimit(domainId, accountId, resourceType, max);
} catch (InvalidParameterValueException paramException) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, paramException.getMessage());
} catch (Exception ex) {
s_logger.error("Exception updating resource limit", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update limit due to exception: " + ex.getMessage());
}
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
if (limit == null)
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update resource limit. Please contact Cloud Support.");
else {
if (limit.getDomainId() != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), limit.getDomainId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(limit.getDomainId()).getName()));
}
if (limit.getAccountId() != null) {
Account accountTemp = getManagementServer().findAccountById(limit.getAccountId());
if (accountTemp != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ACCOUNT.getName(), accountTemp.getAccountName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), accountTemp.getDomainId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(accountTemp.getDomainId()).getName()));
}
}
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.RESOURCE_TYPE.getName(), limit.getType().ordinal()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.MAX.getName(), limit.getMax()));
embeddedObject.add(new Pair<String, Object>("resourcelimit", new Object[] { returnValues } ));
}
return embeddedObject;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
// Long domainId = (Long) params.get(BaseCmd.Properties.DOMAIN_ID.getName());
// String accountName = (String) params.get(BaseCmd.Properties.ACCOUNT.getName());
// Integer type = (Integer) params.get(BaseCmd.Properties.RESOURCE_TYPE.getName());
// Long max = (Long) params.get(BaseCmd.Properties.MAX.getName());
// Long accountId = null;
//
// if (max == null) {
// max = new Long(-1);
// } else if (max < -1) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify either '-1' for an infinite limit, or a limit that is at least '0'.");
// }
//
// // Map resource type
// ResourceType resourceType;
// try {
// resourceType = ResourceType.values()[type];
// } catch (ArrayIndexOutOfBoundsException e) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid resource type.");
// }
//
// /*
// if (accountName==null && domainId != null && !domainId.equals(DomainVO.ROOT_DOMAIN)) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Resource limits must be made for an account or the ROOT domain.");
// }
// */
//
// if (account != null) {
// if (domainId != null) {
// if (!getManagementServer().isChildDomain(account.getDomainId(), domainId)) {
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((accountName == null) ? "" : "account " + accountName + " in ") + "domain " + domainId + ", permission denied");
// }
// } else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
// domainId = DomainVO.ROOT_DOMAIN; // for root admin, default to root domain if domain is not specified
// }
//
// if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
// if ((domainId != null) && (accountName == null) && domainId.equals(account.getDomainId())) {
// // if the admin is trying to update their own domain, disallow...
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((accountName == null) ? "" : "account " + accountName + " in ") + "domain " + domainId + ", permission denied");
// }
//
// // If there is an existing ROOT domain limit, make sure its max isn't being exceeded
// Criteria c = new Criteria();
// c.addCriteria(Criteria.DOMAINID, DomainVO.ROOT_DOMAIN);
// c.addCriteria(Criteria.TYPE, resourceType);
// List<ResourceLimitVO> currentRootDomainLimits = getManagementServer().searchForLimits(c);
// ResourceLimitVO currentRootDomainLimit = (currentRootDomainLimits.size() == 0) ? null : currentRootDomainLimits.get(0);
// if (currentRootDomainLimit != null) {
// long currentRootDomainMax = currentRootDomainLimits.get(0).getMax();
// if ((max == -1 && currentRootDomainMax != -1) || max > currentRootDomainMax) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "The current ROOT domain limit for resource type " + resourceType + " is " + currentRootDomainMax + " and cannot be exceeded.");
// }
// }
// }
// } else if (domainId == null) {
// domainId = DomainVO.ROOT_DOMAIN; // for system commands, default to root domain if domain is not specified
// }
//
// if (domainId == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to update resource limit, unable to determine domain in which to update limit.");
// } else if (accountName != null) {
// Account userAccount = getManagementServer().findActiveAccount(accountName, domainId);
// if (userAccount == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find account by name " + accountName + " in domain with id " + domainId);
// }
// accountId = userAccount.getId();
// domainId = userAccount.getDomainId();
// }
//
// ResourceLimitVO limit = null;
// try {
// if (accountId != null) domainId = null;
// limit = getManagementServer().updateResourceLimit(domainId, accountId, resourceType, max);
// } catch (InvalidParameterValueException paramException) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, paramException.getMessage());
// } catch (Exception ex) {
// s_logger.error("Exception updating resource limit", ex);
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update limit due to exception: " + ex.getMessage());
// }
// List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
//
// if (limit == null)
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update resource limit. Please contact Cloud Support.");
// else {
//
// if (limit.getDomainId() != null) {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), limit.getDomainId()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(limit.getDomainId()).getName()));
// }
//
// if (limit.getAccountId() != null) {
// Account accountTemp = getManagementServer().findAccountById(limit.getAccountId());
// if (accountTemp != null) {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ACCOUNT.getName(), accountTemp.getAccountName()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), accountTemp.getDomainId()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(accountTemp.getDomainId()).getName()));
// }
// }
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.RESOURCE_TYPE.getName(), limit.getType().ordinal()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.MAX.getName(), limit.getMax()));
// embeddedObject.add(new Pair<String, Object>("resourcelimit", new Object[] { returnValues } ));
// }
// return embeddedObject;
// }
}

View File

@ -18,35 +18,18 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.offering.ServiceOffering.GuestIpType;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.user.User;
import com.cloud.utils.Pair;
public class UpdateServiceOfferingCmd extends BaseCmd{
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="updateServiceOffering", manager=Manager.ConfigManager)
public class UpdateServiceOfferingCmd extends BaseCmd
{
public static final Logger s_logger = Logger.getLogger(UpdateServiceOfferingCmd.class.getName());
private static final String s_name = "updateserviceofferingresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DISPLAY_TEXT, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.NAME, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.OFFER_HA, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.TAGS, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USE_VIRTUAL_NETWORK, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -105,57 +88,60 @@ public class UpdateServiceOfferingCmd extends BaseCmd{
@Override
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long offeringId = (Long)params.get(BaseCmd.Properties.ID.getName());
String name = (String)params.get(BaseCmd.Properties.NAME.getName());
String displayText = (String)params.get(BaseCmd.Properties.DISPLAY_TEXT.getName());
Boolean offerHA = (Boolean) params.get(BaseCmd.Properties.OFFER_HA.getName());
Boolean useVirtualNetwork = (Boolean) params.get(BaseCmd.Properties.USE_VIRTUAL_NETWORK.getName());
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
String tags = (String)params.get(BaseCmd.Properties.TAGS.getName());
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
// Verify input parameters
ServiceOfferingVO offering = getManagementServer().findServiceOfferingById(offeringId);
if (offering == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find service offering " + offeringId);
}
}
try {
offering = getManagementServer().updateServiceOffering(userId, offeringId, name, displayText, offerHA, useVirtualNetwork, tags);
} catch (Exception ex) {
s_logger.error("Exception updating service offering", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service offering " + offeringId + ": internal error.");
}
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
if (offering != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), offeringId.toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), offering.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISPLAY_TEXT.getName(), offering.getDisplayText()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CPU_NUMBER.getName(), Integer.valueOf(offering.getCpu()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CPU_SPEED.getName(), Integer.valueOf(offering.getSpeed()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.MEMORY.getName(), Integer.valueOf(offering.getRamSize()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CREATED.getName(), getDateString(offering.getCreated())));
String storageType = offering.getUseLocalStorage() ? "local" : "shared";
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.STORAGE_TYPE.getName(), storageType));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.OFFER_HA.getName(), offering.getOfferHA()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.USE_VIRTUAL_NETWORK.getName(), (offering.getGuestIpType().equals(GuestIpType.Virtualized))));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TAGS.getName(), offering.getTags()));
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service offering " + offeringId);
}
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long offeringId = (Long)params.get(BaseCmd.Properties.ID.getName());
// String name = (String)params.get(BaseCmd.Properties.NAME.getName());
// String displayText = (String)params.get(BaseCmd.Properties.DISPLAY_TEXT.getName());
// Boolean offerHA = (Boolean) params.get(BaseCmd.Properties.OFFER_HA.getName());
// Boolean useVirtualNetwork = (Boolean) params.get(BaseCmd.Properties.USE_VIRTUAL_NETWORK.getName());
// Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
// String tags = (String)params.get(BaseCmd.Properties.TAGS.getName());
//
// if (userId == null) {
// userId = Long.valueOf(User.UID_SYSTEM);
// }
//
// // Verify input parameters
// ServiceOfferingVO offering = getManagementServer().findServiceOfferingById(offeringId);
// if (offering == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find service offering " + offeringId);
// }
//
//
// try {
// offering = getManagementServer().updateServiceOffering(userId, offeringId, name, displayText, offerHA, useVirtualNetwork, tags);
// } catch (Exception ex) {
// s_logger.error("Exception updating service offering", ex);
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service offering " + offeringId + ": internal error.");
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// if (offering != null) {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), offeringId.toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), offering.getName()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISPLAY_TEXT.getName(), offering.getDisplayText()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CPU_NUMBER.getName(), Integer.valueOf(offering.getCpu()).toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CPU_SPEED.getName(), Integer.valueOf(offering.getSpeed()).toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.MEMORY.getName(), Integer.valueOf(offering.getRamSize()).toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CREATED.getName(), getDateString(offering.getCreated())));
// String storageType = offering.getUseLocalStorage() ? "local" : "shared";
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.STORAGE_TYPE.getName(), storageType));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.OFFER_HA.getName(), offering.getOfferHA()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.USE_VIRTUAL_NETWORK.getName(), (offering.getGuestIpType().equals(GuestIpType.Virtualized))));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TAGS.getName(), offering.getTags()));
// } else {
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update service offering " + offeringId);
// }
// return returnValues;
// }
}

View File

@ -18,30 +18,18 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.dc.ClusterVO;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.StorageStats;
import com.cloud.utils.Pair;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="updateStoragePool", manager=Manager.StorageManager)
public class UpdateStoragePoolCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateStoragePoolCmd.class.getName());
private static final String s_name = "updatestoragepoolresponse";
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.TAGS, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -73,68 +61,70 @@ public class UpdateStoragePoolCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("UpdateStoragePoolCmd Params @ " + params.toString());
}
Long poolId = (Long) params.get(BaseCmd.Properties.ID.getName());
String tags = (String) params.get(BaseCmd.Properties.TAGS.getName());
StoragePoolVO storagePool = null;
try {
storagePool = getManagementServer().updateStoragePool(poolId, tags);
} catch (IllegalArgumentException e) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage());
}
s_logger.debug("Successfully updated storagePool " + storagePool.toString() );
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), Long.toString(storagePool.getId())));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_ID.getName(), storagePool.getDataCenterId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_NAME.getName(), getManagementServer().getDataCenterBy(storagePool.getDataCenterId()).getName()));
if (storagePool.getPodId() != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.POD_ID.getName(), storagePool.getPodId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.POD_NAME.getName(), getManagementServer().getPodBy(storagePool.getPodId()).getName()));
}
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), storagePool.getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.IP_ADDRESS.getName(), storagePool.getHostAddress()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PATH.getName(), storagePool.getPath()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CREATED.getName(), getDateString(storagePool.getCreated())));
if (storagePool.getPoolType() != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TYPE.getName(), storagePool.getPoolType().toString()));
}
if (storagePool.getClusterId() != null) {
ClusterVO cluster = getManagementServer().findClusterById(storagePool.getClusterId());
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CLUSTER_ID.getName(), cluster.getId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CLUSTER_NAME.getName(), cluster.getName()));
}
StorageStats stats = getManagementServer().getStoragePoolStatistics(storagePool.getId());
long capacity = storagePool.getCapacityBytes();
long available = storagePool.getAvailableBytes() ;
long used = capacity - available;
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// if (s_logger.isDebugEnabled()) {
// s_logger.debug("UpdateStoragePoolCmd Params @ " + params.toString());
// }
//
// Long poolId = (Long) params.get(BaseCmd.Properties.ID.getName());
// String tags = (String) params.get(BaseCmd.Properties.TAGS.getName());
//
// StoragePoolVO storagePool = null;
// try {
// storagePool = getManagementServer().updateStoragePool(poolId, tags);
// } catch (IllegalArgumentException e) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, e.getMessage());
// }
//
// s_logger.debug("Successfully updated storagePool " + storagePool.toString() );
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ID.getName(), Long.toString(storagePool.getId())));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_ID.getName(), storagePool.getDataCenterId()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_NAME.getName(), getManagementServer().getDataCenterBy(storagePool.getDataCenterId()).getName()));
// if (storagePool.getPodId() != null) {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.POD_ID.getName(), storagePool.getPodId()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.POD_NAME.getName(), getManagementServer().getPodBy(storagePool.getPodId()).getName()));
// }
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.NAME.getName(), storagePool.getName()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.IP_ADDRESS.getName(), storagePool.getHostAddress()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.PATH.getName(), storagePool.getPath()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CREATED.getName(), getDateString(storagePool.getCreated())));
//
// if (storagePool.getPoolType() != null) {
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TYPE.getName(), storagePool.getPoolType().toString()));
// }
//
// if (storagePool.getClusterId() != null) {
// ClusterVO cluster = getManagementServer().findClusterById(storagePool.getClusterId());
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CLUSTER_ID.getName(), cluster.getId()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.CLUSTER_NAME.getName(), cluster.getName()));
// }
//
// StorageStats stats = getManagementServer().getStoragePoolStatistics(storagePool.getId());
// long capacity = storagePool.getCapacityBytes();
// long available = storagePool.getAvailableBytes() ;
// long used = capacity - available;
//
// if (stats != null) {
// used = stats.getByteUsed();
// available = capacity - used;
// }
// s_logger.debug("Successfully recieved the storagePool statistics. TotalDiskSize - " +capacity+ " AllocatedDiskSize - " +used );
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISK_SIZE_TOTAL.getName(), Long.valueOf(storagePool.getCapacityBytes()).toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISK_SIZE_ALLOCATED.getName(), Long.valueOf(used).toString()));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TAGS.getName(), getManagementServer().getStoragePoolTags(storagePool.getId())));
//
// List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
// embeddedObject.add(new Pair<String, Object>("storagepool", new Object[] { returnValues } ));
// return embeddedObject;
// }
if (stats != null) {
used = stats.getByteUsed();
available = capacity - used;
}
s_logger.debug("Successfully recieved the storagePool statistics. TotalDiskSize - " +capacity+ " AllocatedDiskSize - " +used );
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISK_SIZE_TOTAL.getName(), Long.valueOf(storagePool.getCapacityBytes()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DISK_SIZE_ALLOCATED.getName(), Long.valueOf(used).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TAGS.getName(), getManagementServer().getStoragePoolTags(storagePool.getId())));
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
embeddedObject.add(new Pair<String, Object>("storagepool", new Object[] { returnValues } ));
return embeddedObject;
}
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -1,37 +1,21 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.storage.VMTemplateVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="updateTemplatePermissions", manager=Manager.ManagementServer)
public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd {
public Logger s_logger = getLogger();
protected static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
protected String s_name = getResponseName();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_NAMES, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.IS_FEATURED, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.IS_PUBLIC, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.OP, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@ -82,97 +66,19 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd {
@Override
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
protected boolean templateIsCorrectType(VMTemplateVO template) {
return true;
}
}
protected String getResponseName() {
return "updatetemplateorisopermissionsresponse";
}
protected String getMediaType() {
return "templateOrIso";
}
protected Logger getLogger() {
return Logger.getLogger(UpdateTemplateOrIsoPermissionsCmd.class.getName());
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long id = (Long)params.get(BaseCmd.Properties.ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Boolean isPublic = (Boolean)params.get(BaseCmd.Properties.IS_PUBLIC.getName());
Boolean isFeatured = (Boolean)params.get(BaseCmd.Properties.IS_FEATURED.getName());
String accoutNames = (String)params.get(BaseCmd.Properties.ACCOUNT_NAMES.getName());
String operation = (String)params.get(BaseCmd.Properties.OP.getName());
Boolean publishTemplateResult = Boolean.FALSE;
VMTemplateVO template = getManagementServer().findTemplateById(id.longValue());
if (template == null || !templateIsCorrectType(template)) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "unable to find " + getMediaType() + " with id " + id);
}
if (account != null) {
if (!isAdmin(account.getType()) && (template.getAccountId() != account.getId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to update permissions for " + getMediaType() + " with id " + id);
} else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN) {
Long templateOwnerDomainId = getManagementServer().findDomainIdByAccountId(template.getAccountId());
if (!getManagementServer().isChildDomain(account.getDomainId(), templateOwnerDomainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update permissions for " + getMediaType() + " with id " + id);
}
}
}
// If the template is removed throw an error.
if (template.getRemoved() != null){
s_logger.error("unable to update permissions for " + getMediaType() + " with id " + id + " as it is removed ");
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to update permissions for " + getMediaType() + " with id " + id + " as it is removed ");
}
if (id == Long.valueOf(1)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to update permissions for " + getMediaType() + " with id " + id);
}
boolean isAdmin = ((account == null) || isAdmin(account.getType()));
boolean allowPublicUserTemplates = Boolean.parseBoolean(getManagementServer().getConfigurationValue("allow.public.user.templates"));
if (!isAdmin && !allowPublicUserTemplates && isPublic != null && isPublic) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Only private " + getMediaType() + "s can be created.");
}
// package up the accountNames as a list
List<String> accountNameList = new ArrayList<String>();
if (accoutNames != null) {
if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset"))) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." +
" Given operation is: '" + operation + "'");
}
StringTokenizer st = new StringTokenizer(accoutNames, ",");
while (st.hasMoreTokens()) {
accountNameList.add(st.nextToken());
}
}
try {
publishTemplateResult = getManagementServer().updateTemplatePermissions(id, operation, isPublic, isFeatured, accountNameList);
} catch (InvalidParameterValueException ex) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Failed to update " + getMediaType() + " permissions for template " + template.getName() + ": internal error.");
} catch (PermissionDeniedException ex) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Failed to update " + getMediaType() + " permissions for template " + template.getName() + ": internal error.");
} catch (Exception ex) {
s_logger.error("Exception editing template", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update " + getMediaType() + " permissions for template " + template.getName() + ": internal error.");
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.SUCCESS.getName(), publishTemplateResult.toString()));
return returnValues;
public String getResponse()
{
return null;//return the response here
}
}

View File

@ -20,23 +20,17 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.api.Implementation;
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="updateTemplatePermissions", manager=Manager.ManagementServer)
public class UpdateTemplatePermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd {
protected String getResponseName() {
return "updatetemplatepermissionsresponse";
}
protected String getMediaType() {
return "template";
}
protected Logger getLogger() {
return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName());
}
protected boolean templateIsCorrectType(VMTemplateVO template) {
return !template.getFormat().equals(ImageFormat.ISO);
}
}
}

View File

@ -25,30 +25,20 @@ import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.Pair;
@Implementation(method="updateUser", manager=Manager.ManagementServer)
public class UpdateUserCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName());
private static final String s_name = "updateuserresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.API_KEY, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.EMAIL, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.FIRSTNAME, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.LASTNAME, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.PASSWORD, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.SECRET_KEY, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.TIMEZONE, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USERNAME, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -128,75 +118,12 @@ public class UpdateUserCmd extends BaseCmd {
public String getName() {
return s_name;
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long userId = (Long)params.get(BaseCmd.Properties.ID.getName());
String username = (String)params.get(BaseCmd.Properties.USERNAME.getName());
String password = (String)params.get(BaseCmd.Properties.PASSWORD.getName());
String firstname = (String)params.get(BaseCmd.Properties.FIRSTNAME.getName());
String lastname = (String)params.get(BaseCmd.Properties.LASTNAME.getName());
String email = (String)params.get(BaseCmd.Properties.EMAIL.getName());
String timezone = (String)params.get(BaseCmd.Properties.TIMEZONE.getName());
String apiKey = (String)params.get(BaseCmd.Properties.API_KEY.getName());
String secretKey = (String)params.get(BaseCmd.Properties.SECRET_KEY.getName());
//check if the user exists in the system
User user = getManagementServer().getUser(userId.longValue());
if (user == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find user by id");
}
if((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null))
{
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please provide an api key/secret key pair");
}
// If the account is an admin type, return an error. We do not allow this
Account account = getManagementServer().findAccountById(user.getAccountId());
if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "user id : " + userId + " is system account, update is not allowed");
}
if (firstname == null) {
firstname = user.getFirstname();
}
if (lastname == null) {
lastname = user.getLastname();
}
if (username == null) {
username = user.getUsername();
}
if (password == null) {
password = user.getPassword();
}
if (email == null) {
email = user.getEmail();
}
if (timezone == null) {
timezone = user.getTimezone();
}
if (apiKey == null) {
apiKey = user.getApiKey();
}
if (secretKey == null) {
secretKey = user.getSecretKey();
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
boolean success = false;
try {
success = getManagementServer().updateUser(user.getId(), username, password, firstname, lastname, email, timezone, apiKey, secretKey);
} catch (InvalidParameterValueException e)
{
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage());
}
if (success) {
returnValues.add(new Pair<String,Object> (BaseCmd.Properties.SUCCESS.getName(), Boolean.valueOf(success).toString()));
} else {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "failed to update user");
}
return returnValues;
}
@Override
public String getResponse() {
// TODO Auto-generated method stub
//response returned is true or false, based on which you can throw an error
return null;
}
}

View File

@ -18,33 +18,19 @@
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.response.UpgradeVmResponse;
import com.cloud.vm.UserVmVO;
@Implementation(method="updateVirtualMachine", manager=Manager.UserVmManager)
public class UpdateVMCmd extends BaseCmd{
public static final Logger s_logger = Logger.getLogger(UpdateVMCmd.class.getName());
private static final String s_name = "updatevirtualmachineresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DISPLAY_NAME, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.GROUP, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.HA_ENABLE, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -86,71 +72,30 @@ public class UpdateVMCmd extends BaseCmd{
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
private UserVmVO responseObject = null;
@Override
public String getName() {
return s_name;
}
@Override
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long vmId = (Long)params.get(BaseCmd.Properties.ID.getName());
String group = (String)params.get(BaseCmd.Properties.GROUP.getName());
String displayName = (String)params.get(BaseCmd.Properties.DISPLAY_NAME.getName());
Boolean enable = (Boolean)params.get(BaseCmd.Properties.HA_ENABLE.getName());
UserVmVO vmInstance = null;
// default userId to SYSTEM user
if (userId == null) {
userId = Long.valueOf(1);
}
// Verify input parameters
try {
vmInstance = getManagementServer().findUserVMInstanceById(vmId.longValue());
} catch (Exception ex1) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "unable to find virtual machine by id");
}
if (vmInstance == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find virtual machine with id " + vmId);
}
if (account != null) {
if (!isAdmin(account.getType()) && (account.getId().longValue() != vmInstance.getAccountId())) {
throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR, "unable to find a virtual machine with id " + vmId + " for this account");
} else if (!getManagementServer().isChildDomain(account.getDomainId(), vmInstance.getDomainId())) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid virtual machine id (" + vmId + ") given, unable to update virtual machine.");
}
}
public static String getResultObjectName() {
return "virtualmachine";
}
@Override
public String getResponse()
{
UpgradeVmResponse response = new UpgradeVmResponse();
UserVmVO userVm = (UserVmVO)getResponseObject();
UserVmVO responseObject = (UserVmVO)getResponseObject();
if (responseObject != null)
{
//just pass back success or failure from here
}
if (group == null) {
group = vmInstance.getGroup();
}
return null;
}
if (displayName == null) {
displayName = vmInstance.getDisplayName();
}
if (enable == null) {
enable = vmInstance.isHaEnabled();
}
long accountId = vmInstance.getAccountId();
try {
getManagementServer().updateVirtualMachine(vmId, displayName, group, enable, userId, accountId);
} catch (Exception ex) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update virtual machine" + vmId + ": internal error.");
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.SUCCESS.getName(), Boolean.TRUE));
return returnValues;
}
}

View File

@ -18,15 +18,13 @@
package com.cloud.api.commands;
import java.util.Date;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.serializer.Param;
import com.cloud.api.response.UpgradeVmResponse;
import com.cloud.vm.UserVmVO;
@Implementation(method="upgradeVirtualMachine", manager=Manager.UserVmManager)
@ -74,9 +72,11 @@ public class UpgradeVMCmd extends BaseCmd {
public String getResponse()
{
UpgradeVmResponse response = new UpgradeVmResponse();
return null;//TODO -- construct response
// if (responseObject != null) {
// response.set
UserVmVO userVm = (UserVmVO)getResponseObject();
UserVmVO responseObject = (UserVmVO)getResponseObject();
if (responseObject != null)
{
//
// Account acct = ms.findAccountById(Long.valueOf(vm.getAccountId()));
// resultObj.setAccount(acct.getAccountName());
@ -126,286 +126,13 @@ public class UpgradeVMCmd extends BaseCmd {
// }
//
// return SerializerHelper.toSerializedString(responseObject);
}
return null;
}
public void setResponseObject(UserVmVO userVm) {
responseObject = userVm;
}
// helper class for the response object
private class UpgradeVmResponse
{
@Param(name="id")
private long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public long getDomainId() {
return domainId;
}
public void setDomainId(long domainId) {
this.domainId = domainId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public boolean isHaEnable() {
return haEnable;
}
public void setHaEnable(boolean haEnable) {
this.haEnable = haEnable;
}
public long getZoneId() {
return zoneId;
}
public void setZoneId(long zoneId) {
this.zoneId = zoneId;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
public long getHostId() {
return hostId;
}
public void setHostId(long hostId) {
this.hostId = hostId;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public long getTemplateId() {
return templateId;
}
public void setTemplateId(long templateId) {
this.templateId = templateId;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getTemplateDisplayText() {
return templateDisplayText;
}
public void setTemplateDisplayText(String templateDisplayText) {
this.templateDisplayText = templateDisplayText;
}
public boolean isPasswordEnabled() {
return passwordEnabled;
}
public void setPasswordEnabled(boolean passwordEnabled) {
this.passwordEnabled = passwordEnabled;
}
public long getServiceOfferingId() {
return serviceOfferingId;
}
public void setServiceOfferingId(long serviceOfferingId) {
this.serviceOfferingId = serviceOfferingId;
}
public String getServiceOfferingName() {
return serviceOfferingName;
}
public void setServiceOfferingName(String serviceOfferingName) {
this.serviceOfferingName = serviceOfferingName;
}
public long getCpuSpeed() {
return cpuSpeed;
}
public void setCpuSpeed(long cpuSpeed) {
this.cpuSpeed = cpuSpeed;
}
public long getMemory() {
return memory;
}
public void setMemory(long memory) {
this.memory = memory;
}
public long getCpuUsed() {
return cpuUsed;
}
public void setCpuUsed(long cpuUsed) {
this.cpuUsed = cpuUsed;
}
public long getNetworkKbsRead() {
return networkKbsRead;
}
public void setNetworkKbsRead(long networkKbsRead) {
this.networkKbsRead = networkKbsRead;
}
public long getNetworkKbsWrite() {
return networkKbsWrite;
}
public void setNetworkKbsWrite(long networkKbsWrite) {
this.networkKbsWrite = networkKbsWrite;
}
public long isId()
{
return id;
}
@Param(name="name")
private String name;
@Param(name="created")
private Date created;
@Param(name="ipaddress")
private String ipAddress;
@Param(name="state")
private String state;
@Param(name="account")
private String account;
@Param(name="domainid")
private long domainId;
@Param(name="domain")
private String domain;
@Param(name="haenable")
private boolean haEnable;
@Param(name="zoneid")
private long zoneId;
@Param(name="displayname")
private String displayName;
@Param(name="zonename")
private String zoneName;
@Param(name="hostid")
private long hostId;
@Param(name="hostname")
private String hostName;
@Param(name="templateid")
private long templateId;
@Param(name="templatename")
private String templateName;
@Param(name="templatedisplaytext")
private String templateDisplayText;
@Param(name="passwordenabled")
private boolean passwordEnabled;
@Param(name="serviceofferingid")
private long serviceOfferingId;
@Param(name="serviceofferingname")
private String serviceOfferingName;
@Param(name="cpunumber")
private long cpuSpeed;
@Param(name="memory")
private long memory;
@Param(name="cpuused")
private long cpuUsed;
@Param(name="networkkbsread")
private long networkKbsRead;
@Param(name="networkkbswrite")
private long networkKbsWrite;
}
}

View File

@ -0,0 +1,96 @@
package com.cloud.api.response;
import java.util.Date;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class DiskOfferingResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="domainid")
private Long domainId;
@Param(name="domain")
private String domain;
@Param(name="name")
private String name;
@Param(name="displaytext")
private String displayText;
@Param(name="disksize")
private Long diskSize;
@Param(name="created")
private Date created;
@Param(name="tags")
private String tags;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getDomainId() {
return domainId;
}
public void setDomainId(Long domainId) {
this.domainId = domainId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
}
public Long getDiskSize() {
return diskSize;
}
public void setDiskSize(Long diskSize) {
this.diskSize = diskSize;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
}

View File

@ -0,0 +1,61 @@
package com.cloud.api.response;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class DomainResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="name")
private String domainName;
@Param(name="level")
private Integer level;
@Param(name="parentdomainid")
private Long parentDomainId;
@Param(name="parentdomainname")
private String parentDomainName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Long getParentDomainId() {
return parentDomainId;
}
public void setParentDomainId(Long parentDomainId) {
this.parentDomainId = parentDomainId;
}
public String getParentDomainName() {
return parentDomainName;
}
public void setParentDomainName(String parentDomainName) {
this.parentDomainName = parentDomainName;
}
}

View File

@ -0,0 +1,72 @@
package com.cloud.api.response;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class FirewallRuleResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="privateport")
private String privatePort;
@Param(name="protocol")
private String protocol;
@Param(name="publicport")
private String publicPort;
@Param(name="virtualmachineid")
private Long virtualMachineId;
@Param(name="virtualmachinename")
private String virtualMachineName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrivatePort() {
return privatePort;
}
public void setPrivatePort(String privatePort) {
this.privatePort = privatePort;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getPublicPort() {
return publicPort;
}
public void setPublicPort(String publicPort) {
this.publicPort = publicPort;
}
public Long getVirtualMachineId() {
return virtualMachineId;
}
public void setVirtualMachineId(Long virtualMachineId) {
this.virtualMachineId = virtualMachineId;
}
public String getVirtualMachineName() {
return virtualMachineName;
}
public void setVirtualMachineName(String virtualMachineName) {
this.virtualMachineName = virtualMachineName;
}
}

View File

@ -0,0 +1,116 @@
package com.cloud.api.response;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class LoadBalancerResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="name")
private String name;
@Param(name="description")
private String description;
@Param(name="publicip")
private String publicIp;
@Param(name="publicport")
private String publicPort;
@Param(name="privateport")
private String privatePort;
@Param(name="algorithm")
private String algorithm;
@Param(name="account")
private String accountName;
@Param(name="domainid")
private Long domainId;
@Param(name="domain")
private String domainName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublicIp() {
return publicIp;
}
public void setPublicIp(String publicIp) {
this.publicIp = publicIp;
}
public String getPublicPort() {
return publicPort;
}
public void setPublicPort(String publicPort) {
this.publicPort = publicPort;
}
public String getPrivatePort() {
return privatePort;
}
public void setPrivatePort(String privatePort) {
this.privatePort = privatePort;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getDomainId() {
return domainId;
}
public void setDomainId(Long domainId) {
this.domainId = domainId;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}

View File

@ -0,0 +1,72 @@
package com.cloud.api.response;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class NetworkGroupResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="name")
private String name;
@Param(name="description")
private String description;
@Param(name="account")
private String accountName;
@Param(name="domainid")
private Long domainId;
@Param(name="domain")
private String domainName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getDomainId() {
return domainId;
}
public void setDomainId(Long domainId) {
this.domainId = domainId;
}
public String getDomainName() {
return domainName;
}
public void setDomainName(String domainName) {
this.domainName = domainName;
}
}

View File

@ -0,0 +1,94 @@
package com.cloud.api.response;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class PodResponse implements ResponseObject {
@Param(name="id")
private Long id;
@Param(name="name")
private String name;
@Param(name="zoneid")
private Long zoneId;
@Param(name="zonename")
private String zoneName;
@Param(name="gateway")
private String gateway;
@Param(name="cidr")
private String cidr;
@Param(name="startip")
private String startIp;
@Param(name="endIp")
private String endIp;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 String getGateway() {
return gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getCidr() {
return cidr;
}
public void setCidr(String cidr) {
this.cidr = cidr;
}
public String getStartIp() {
return startIp;
}
public void setStartIp(String startIp) {
this.startIp = startIp;
}
public String getEndIp() {
return endIp;
}
public void setEndIp(String endIp) {
this.endIp = endIp;
}
}

View File

@ -0,0 +1,281 @@
package com.cloud.api.response;
import java.util.Date;
import com.cloud.api.ResponseObject;
import com.cloud.serializer.Param;
public class UpgradeVmResponse implements ResponseObject
{
@Param(name="id")
private long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public long getDomainId() {
return domainId;
}
public void setDomainId(long domainId) {
this.domainId = domainId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public boolean isHaEnable() {
return haEnable;
}
public void setHaEnable(boolean haEnable) {
this.haEnable = haEnable;
}
public long getZoneId() {
return zoneId;
}
public void setZoneId(long zoneId) {
this.zoneId = zoneId;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
public long getHostId() {
return hostId;
}
public void setHostId(long hostId) {
this.hostId = hostId;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public long getTemplateId() {
return templateId;
}
public void setTemplateId(long templateId) {
this.templateId = templateId;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public String getTemplateDisplayText() {
return templateDisplayText;
}
public void setTemplateDisplayText(String templateDisplayText) {
this.templateDisplayText = templateDisplayText;
}
public boolean isPasswordEnabled() {
return passwordEnabled;
}
public void setPasswordEnabled(boolean passwordEnabled) {
this.passwordEnabled = passwordEnabled;
}
public long getServiceOfferingId() {
return serviceOfferingId;
}
public void setServiceOfferingId(long serviceOfferingId) {
this.serviceOfferingId = serviceOfferingId;
}
public String getServiceOfferingName() {
return serviceOfferingName;
}
public void setServiceOfferingName(String serviceOfferingName) {
this.serviceOfferingName = serviceOfferingName;
}
public long getCpuSpeed() {
return cpuSpeed;
}
public void setCpuSpeed(long cpuSpeed) {
this.cpuSpeed = cpuSpeed;
}
public long getMemory() {
return memory;
}
public void setMemory(long memory) {
this.memory = memory;
}
public long getCpuUsed() {
return cpuUsed;
}
public void setCpuUsed(long cpuUsed) {
this.cpuUsed = cpuUsed;
}
public long getNetworkKbsRead() {
return networkKbsRead;
}
public void setNetworkKbsRead(long networkKbsRead) {
this.networkKbsRead = networkKbsRead;
}
public long getNetworkKbsWrite() {
return networkKbsWrite;
}
public void setNetworkKbsWrite(long networkKbsWrite) {
this.networkKbsWrite = networkKbsWrite;
}
public long isId()
{
return id;
}
@Param(name="name")
private String name;
@Param(name="created")
private Date created;
@Param(name="ipaddress")
private String ipAddress;
@Param(name="state")
private String state;
@Param(name="account")
private String account;
@Param(name="domainid")
private long domainId;
@Param(name="domain")
private String domain;
@Param(name="haenable")
private boolean haEnable;
@Param(name="zoneid")
private long zoneId;
@Param(name="displayname")
private String displayName;
@Param(name="zonename")
private String zoneName;
@Param(name="hostid")
private long hostId;
@Param(name="hostname")
private String hostName;
@Param(name="templateid")
private long templateId;
@Param(name="templatename")
private String templateName;
@Param(name="templatedisplaytext")
private String templateDisplayText;
@Param(name="passwordenabled")
private boolean passwordEnabled;
@Param(name="serviceofferingid")
private long serviceOfferingId;
@Param(name="serviceofferingname")
private String serviceOfferingName;
@Param(name="cpunumber")
private long cpuSpeed;
@Param(name="memory")
private long memory;
@Param(name="cpuused")
private long cpuUsed;
@Param(name="networkkbsread")
private long networkKbsRead;
@Param(name="networkkbswrite")
private long networkKbsWrite;
}

View File

@ -1,133 +1,134 @@
/**
* 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 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.serializer.GsonHelper;
import com.cloud.server.ManagementServer;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VmStats;
import com.google.gson.Gson;
public class UpgradeVMExecutor extends BaseAsyncJobExecutor {
public static final Logger s_logger = Logger.getLogger(UpgradeVMExecutor.class.getName());
public boolean execute() {
AsyncJobManager asyncMgr = getAsyncJobMgr();
AsyncJobVO job = getJob();
Gson gson = GsonHelper.getBuilder().create();
if(getSyncSource() == null) {
VMOperationParam param = gson.fromJson(job.getCmdInfo(), VMOperationParam.class);
asyncMgr.syncAsyncJobExecution(job.getId(), "UserVM", param.getVmId());
// always true if it does not have sync-source
return true;
} else {
ManagementServer managementServer = asyncMgr.getExecutorContext().getManagementServer();
UpgradeVMParam param = gson.fromJson(job.getCmdInfo(), UpgradeVMParam.class);
try {
asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", param.getVmId());
boolean success = managementServer.upgradeVirtualMachine(param.getUserId(),
param.getVmId(), param.getServiceOfferingId(), param.getEventId());
if (success) {
//get the upgraded vm to compose the result object
UserVmVO userVm = managementServer.findUserVMInstanceById(param.getVmId());
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0,
composeResultObject(userVm, managementServer));
} else {
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.VM_CHANGE_SERVICE_ERROR,
composeResultObject(null, managementServer));
}
} catch(Exception e) {
s_logger.warn("Unable to upgrade VM " + param.getVmId() + ":" + e.getMessage(), e);
asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
BaseCmd.INTERNAL_ERROR,
e.getMessage());
}
return true;
}
}
private VmResultObject composeResultObject(UserVmVO vm, ManagementServer ms)
{
if(vm == null)
return null;
VmResultObject resultObj = new VmResultObject();
Account acct = ms.findAccountById(Long.valueOf(vm.getAccountId()));
resultObj.setAccount(acct.getAccountName());
ServiceOfferingVO offering = ms.findServiceOfferingById(vm.getServiceOfferingId());
resultObj.setCpuSpeed(offering.getSpeed());
resultObj.setMemory(offering.getRamSize());
if(offering.getDisplayText()!=null)
resultObj.setServiceOfferingName(offering.getDisplayText());
else
resultObj.setServiceOfferingName(offering.getName());
resultObj.setServiceOfferingId(vm.getServiceOfferingId());
VmStats vmStats = ms.getVmStatistics(vm.getId());
if(vmStats != null)
{
resultObj.setCpuUsed((long) vmStats.getCPUUtilization());
resultObj.setNetworkKbsRead((long) vmStats.getNetworkReadKBs());
resultObj.setNetworkKbsWrite((long) vmStats.getNetworkWriteKBs());
}
resultObj.setCreated(vm.getCreated());
resultObj.setDisplayName(vm.getDisplayName());
resultObj.setDomain(ms.findDomainIdById(acct.getDomainId()).getName());
resultObj.setDomainId(acct.getDomainId());
resultObj.setHaEnable(vm.isHaEnabled());
if(vm.getHostId() != null)
{
resultObj.setHostId(vm.getHostId());
resultObj.setHostName(ms.getHostBy(vm.getHostId()).getName());
}
resultObj.setIpAddress(vm.getPrivateIpAddress());
resultObj.setName(vm.getName());
resultObj.setState(vm.getState().toString());
resultObj.setZoneId(vm.getDataCenterId());
resultObj.setZoneName(ms.findDataCenterById(vm.getDataCenterId()).getName());
VMTemplateVO template = ms.findTemplateById(vm.getTemplateId());
resultObj.setPasswordEnabled(template.getEnablePassword());
resultObj.setTemplateDisplayText(template.getDisplayText());
resultObj.setTemplateId(template.getId());
resultObj.setTemplateName(template.getName());
return resultObj;
}
}
//TODO -- This will be removed
///**
// * 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 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.serializer.GsonHelper;
//import com.cloud.server.ManagementServer;
//import com.cloud.service.ServiceOfferingVO;
//import com.cloud.storage.VMTemplateVO;
//import com.cloud.user.Account;
//import com.cloud.uservm.UserVm;
//import com.cloud.vm.UserVmVO;
//import com.cloud.vm.VMInstanceVO;
//import com.cloud.vm.VmStats;
//import com.google.gson.Gson;
//
//public class UpgradeVMExecutor extends BaseAsyncJobExecutor {
// public static final Logger s_logger = Logger.getLogger(UpgradeVMExecutor.class.getName());
//
// public boolean execute() {
// AsyncJobManager asyncMgr = getAsyncJobMgr();
// AsyncJobVO job = getJob();
// Gson gson = GsonHelper.getBuilder().create();
//
// if(getSyncSource() == null) {
// VMOperationParam param = gson.fromJson(job.getCmdInfo(), VMOperationParam.class);
// asyncMgr.syncAsyncJobExecution(job.getId(), "UserVM", param.getVmId());
//
// // always true if it does not have sync-source
// return true;
// } else {
// ManagementServer managementServer = asyncMgr.getExecutorContext().getManagementServer();
// UpgradeVMParam param = gson.fromJson(job.getCmdInfo(), UpgradeVMParam.class);
//
// try {
// asyncMgr.updateAsyncJobAttachment(job.getId(), "vm_instance", param.getVmId());
// boolean success = managementServer.upgradeVirtualMachine(param.getUserId(),
// param.getVmId(), param.getServiceOfferingId(), param.getEventId());
//
// if (success) {
// //get the upgraded vm to compose the result object
// UserVmVO userVm = managementServer.findUserVMInstanceById(param.getVmId());
// asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_SUCCEEDED, 0,
// composeResultObject(userVm, managementServer));
//
// } else {
// asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
// BaseCmd.VM_CHANGE_SERVICE_ERROR,
// composeResultObject(null, managementServer));
// }
// } catch(Exception e) {
// s_logger.warn("Unable to upgrade VM " + param.getVmId() + ":" + e.getMessage(), e);
// asyncMgr.completeAsyncJob(getJob().getId(), AsyncJobResult.STATUS_FAILED,
// BaseCmd.INTERNAL_ERROR,
// e.getMessage());
// }
// return true;
// }
// }
//
// private VmResultObject composeResultObject(UserVmVO vm, ManagementServer ms)
// {
// if(vm == null)
// return null;
//
// VmResultObject resultObj = new VmResultObject();
// Account acct = ms.findAccountById(Long.valueOf(vm.getAccountId()));
// resultObj.setAccount(acct.getAccountName());
//
// ServiceOfferingVO offering = ms.findServiceOfferingById(vm.getServiceOfferingId());
// resultObj.setCpuSpeed(offering.getSpeed());
// resultObj.setMemory(offering.getRamSize());
// if(offering.getDisplayText()!=null)
// resultObj.setServiceOfferingName(offering.getDisplayText());
// else
// resultObj.setServiceOfferingName(offering.getName());
// resultObj.setServiceOfferingId(vm.getServiceOfferingId());
//
// VmStats vmStats = ms.getVmStatistics(vm.getId());
// if(vmStats != null)
// {
// resultObj.setCpuUsed((long) vmStats.getCPUUtilization());
// resultObj.setNetworkKbsRead((long) vmStats.getNetworkReadKBs());
// resultObj.setNetworkKbsWrite((long) vmStats.getNetworkWriteKBs());
// }
//
// resultObj.setCreated(vm.getCreated());
// resultObj.setDisplayName(vm.getDisplayName());
// resultObj.setDomain(ms.findDomainIdById(acct.getDomainId()).getName());
// resultObj.setDomainId(acct.getDomainId());
// resultObj.setHaEnable(vm.isHaEnabled());
// if(vm.getHostId() != null)
// {
// resultObj.setHostId(vm.getHostId());
// resultObj.setHostName(ms.getHostBy(vm.getHostId()).getName());
// }
// resultObj.setIpAddress(vm.getPrivateIpAddress());
// resultObj.setName(vm.getName());
// resultObj.setState(vm.getState().toString());
// resultObj.setZoneId(vm.getDataCenterId());
// resultObj.setZoneName(ms.findDataCenterById(vm.getDataCenterId()).getName());
//
// VMTemplateVO template = ms.findTemplateById(vm.getTemplateId());
// resultObj.setPasswordEnabled(template.getEnablePassword());
// resultObj.setTemplateDisplayText(template.getDisplayText());
// resultObj.setTemplateId(template.getId());
// resultObj.setTemplateName(template.getName());
//
// return resultObj;
// }
//}

View File

@ -21,10 +21,13 @@ import java.util.List;
import com.cloud.api.commands.AddConfigCmd;
import com.cloud.api.commands.CreateDiskOfferingCmd;
import com.cloud.api.commands.CreatePodCmd;
import com.cloud.api.commands.DeleteDiskOfferingCmd;
import com.cloud.api.commands.DeletePodCmd;
import com.cloud.api.commands.UpdateCfgCmd;
import com.cloud.api.commands.UpdateDiskOfferingCmd;
import com.cloud.api.commands.UpdatePodCmd;
import com.cloud.api.commands.UpdateServiceOfferingCmd;
import com.cloud.api.commands.UpdateZoneCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
@ -86,7 +89,8 @@ public interface ConfigurationManager extends Manager {
* @param tags
* @return updated service offering
*/
ServiceOfferingVO updateServiceOffering(long serviceOfferingId, long userId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags);
// ServiceOfferingVO updateServiceOffering(long serviceOfferingId, long userId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags);
ServiceOfferingVO updateServiceOffering(UpdateServiceOfferingCmd cmd);
/**
* Updates a disk offering
@ -137,7 +141,16 @@ public interface ConfigurationManager extends Manager {
* @return Pod
*/
HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
/**
* Creates a new pod based on the parameters specified in the command object
* @param cmd the command object that specifies the name, zone, gateway, cidr, and ip range for the pod
* @return the new pod if successful, null otherwise
* @throws InvalidParameterValueException
* @throws InternalErrorException
*/
HostPodVO createPod(CreatePodCmd cmd) throws InvalidParameterValueException, InternalErrorException;
/**
* Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system.
* @param userId
@ -147,9 +160,11 @@ public interface ConfigurationManager extends Manager {
* @param startIp
* @param endIp
* @return Pod
* @throws InternalErrorException
* @throws InvalidParameterValueException
*/
HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
// HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
HostPodVO editPod(UpdatePodCmd cmd) throws InvalidParameterValueException, InternalErrorException;
/**
* Deletes a pod from the database. Will not allow you to delete pods that are being used anywhere in the system.
* @param userId

View File

@ -35,10 +35,13 @@ import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AddConfigCmd;
import com.cloud.api.commands.CreateDiskOfferingCmd;
import com.cloud.api.commands.CreatePodCmd;
import com.cloud.api.commands.DeleteDiskOfferingCmd;
import com.cloud.api.commands.DeletePodCmd;
import com.cloud.api.commands.UpdateCfgCmd;
import com.cloud.api.commands.UpdateDiskOfferingCmd;
import com.cloud.api.commands.UpdatePodCmd;
import com.cloud.api.commands.UpdateServiceOfferingCmd;
import com.cloud.api.commands.UpdateZoneCmd;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.AccountVlanMapVO;
@ -66,6 +69,7 @@ import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserContext;
@ -73,6 +77,7 @@ import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
@ -102,6 +107,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
@Inject AccountDao _accountDao;
@Inject EventDao _eventDao;
@Inject UserDao _userDao;
@Inject DataCenterDao _dcDao;
@Inject HostPodDao _hostPodDao;
public boolean _premium;
private int _maxVolumeSizeInGb;
@ -392,25 +399,54 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
}
@DB
public HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException {
public HostPodVO editPod(UpdatePodCmd cmd) throws InvalidParameterValueException, InternalErrorException
{
//Input validation
String cidr = cmd.getCidr();
String startIp = cmd.getStartIp();
String endIp = cmd.getEndIp();
String gateway = cmd.getGateway();
Long id = cmd.getId();
String name = cmd.getName();
Long userId = UserContext.current().getUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
//verify parameters
HostPodVO pod = _hostPodDao.findById(id);;
if (pod == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find pod by id " + id);
}
long zoneId = pod.getDataCenterId();
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find zone by id " + zoneId);
}
if (endIp != null && startIp == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "If an end IP is specified, a start IP must be specified.");
}
// Make sure the pod exists
if (!validPod(podId)) {
throw new InvalidParameterValueException("A pod with ID: " + podId + " does not exist.");
if (!validPod(id)) {
throw new InvalidParameterValueException("A pod with ID: " + id + " does not exist.");
}
// If the gateway, CIDR, private IP range is being updated, check if the pod has allocated private IP addresses
if (gateway!= null || cidr != null || startIp != null || endIp != null) {
if (podHasAllocatedPrivateIPs(podId)) {
if (podHasAllocatedPrivateIPs(id)) {
throw new InternalErrorException("The specified pod has allocated private IP addresses, so its CIDR and IP address range cannot be changed.");
}
}
HostPodVO pod = _podDao.findById(podId);
String oldPodName = pod.getName();
long zoneId = pod.getDataCenterId();
if (newPodName == null) {
newPodName = oldPodName;
if (name == null) {
name = oldPodName;
}
if (gateway == null) {
@ -421,8 +457,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
cidr = pod.getCidrAddress() + "/" + pod.getCidrSize();
}
boolean checkForDuplicates = !oldPodName.equals(newPodName);
checkPodAttributes(podId, newPodName, pod.getDataCenterId(), gateway, cidr, startIp, endIp, checkForDuplicates);
boolean checkForDuplicates = !oldPodName.equals(name);
checkPodAttributes(id, name, pod.getDataCenterId(), gateway, cidr, startIp, endIp, checkForDuplicates);
String cidrAddress = getCidrAddress(cidr);
long cidrSize = getCidrSize(cidr);
@ -451,14 +487,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
ipRange = pod.getDescription();
}
pod.setName(newPodName);
pod.setName(name);
pod.setDataCenterId(zoneId);
pod.setGateway(gateway);
pod.setCidrAddress(cidrAddress);
pod.setCidrSize(cidrSize);
pod.setDescription(ipRange);
if (!_podDao.update(podId, pod)) {
if (!_podDao.update(id, pod)) {
throw new InternalErrorException("Failed to edit pod. Please contact Cloud Support.");
}
@ -469,13 +505,39 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
throw new InternalErrorException("Failed to edit pod. Please contact Cloud Support.");
}
DataCenterVO zone = _zoneDao.findById(zoneId);
saveConfigurationEvent(userId, null, EventTypes.EVENT_POD_EDIT, "Successfully edited pod. New pod name is: " + newPodName + " and new zone name is: " + zone.getName() + ".", "podId=" + pod.getId(), "dcId=" + zone.getId(), "gateway=" + gateway, "cidr=" + cidr, "startIp=" + startIp, "endIp=" + endIp);
saveConfigurationEvent(userId, null, EventTypes.EVENT_POD_EDIT, "Successfully edited pod. New pod name is: " + name + " and new zone name is: " + zone.getName() + ".", "podId=" + pod.getId(), "dcId=" + zone.getId(), "gateway=" + gateway, "cidr=" + cidr, "startIp=" + startIp, "endIp=" + endIp);
return pod;
}
@DB
@Override
public HostPodVO createPod(CreatePodCmd cmd) throws InvalidParameterValueException, InternalErrorException {
String cidr = cmd.getCidr();
String endIp = cmd.getEndIp();
String gateway = cmd.getGateway();
String name = cmd.getPodName();
String startIp = cmd.getStartIp();
Long zoneId = cmd.getZoneId();
//verify input parameters
DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Failed to create pod " + name + " -- unable to find zone " + zoneId);
}
if (endIp != null && startIp == null) {
throw new InvalidParameterValueException("Failed to create pod " + name + " -- if an end IP is specified, a start IP must be specified.");
}
Long userId = UserContext.current().getUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
return createPod(userId.longValue(), name, zoneId, gateway, cidr, startIp, endIp);
}
@Override @DB
public HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException {
checkPodAttributes(-1, podName, zoneId, gateway, cidr, startIp, endIp, true);
@ -752,7 +814,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
}
//5. Reached here, hence editable
DataCenterVO zoneHandle = _zoneDao.findById(zoneId);
String oldZoneName = zone.getName();
if (zoneName == null) {
@ -869,13 +930,32 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
}
}
public ServiceOfferingVO updateServiceOffering(long userId, long serviceOfferingId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags) {
boolean updateNeeded = (name != null || displayText != null || offerHA != null || useVirtualNetwork != null || tags != null);
if (!updateNeeded) {
return _serviceOfferingDao.findById(serviceOfferingId);
public ServiceOfferingVO updateServiceOffering(UpdateServiceOfferingCmd cmd) {
String displayText = cmd.getDisplayText();
Long id = cmd.getId();
String name = cmd.getName();
Boolean ha = cmd.getOfferHa();
String tags = cmd.getTags();
Boolean useVirtualNetwork = cmd.getUseVirtualNetwork();
Long userId = UserContext.current().getUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
// Verify input parameters
ServiceOfferingVO offeringHandle = _serviceOfferingDao.findById(id);;
if (offeringHandle == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find service offering " + id);
}
ServiceOfferingVO offering = _serviceOfferingDao.createForUpdate(serviceOfferingId);
boolean updateNeeded = (name != null || displayText != null || ha != null || useVirtualNetwork != null || tags != null);
if (!updateNeeded) {
return _serviceOfferingDao.findById(id);
}
ServiceOfferingVO offering = _serviceOfferingDao.createForUpdate(id);
if (name != null) {
offering.setName(name);
@ -885,8 +965,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
offering.setDisplayText(displayText);
}
if (offerHA != null) {
offering.setOfferHA(offerHA);
if (ha != null) {
offering.setOfferHA(ha);
}
if (useVirtualNetwork != null) {
@ -902,8 +982,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
}
}
if (_serviceOfferingDao.update(serviceOfferingId, offering)) {
offering = _serviceOfferingDao.findById(serviceOfferingId);
if (_serviceOfferingDao.update(id, offering)) {
offering = _serviceOfferingDao.findById(id);
saveConfigurationEvent(userId, null, EventTypes.EVENT_SERVICE_OFFERING_EDIT, "Successfully updated service offering with name: " + offering.getName() + ".", "soId=" + offering.getId(), "name=" + offering.getName(),
"displayText=" + offering.getDisplayText(), "offerHA=" + offering.getOfferHA(), "useVirtualNetwork=" + (offering.getGuestIpType() == GuestIpType.Virtualized), "tags=" + offering.getTags());
return offering;
@ -1014,8 +1094,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
}
}
public String changePrivateIPRange(boolean add, long podId, String startIP, String endIP) throws InvalidParameterValueException {
checkPrivateIpRangeErrors(podId, startIP, endIP);
@ -1777,5 +1855,5 @@ public class ConfigurationManagerImpl implements ConfigurationManager {
s_logger.error("Unable to add the new config entry:",ex);
return false;
}
}
}
}

View File

@ -21,6 +21,8 @@ import java.util.List;
import java.util.Map;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.CreateIPForwardingRuleCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
@ -162,7 +164,21 @@ public interface NetworkManager extends Manager {
* @return list of rules successfully updated
*/
public List<FirewallRuleVO> updateFirewallRules(String publicIpAddress, List<FirewallRuleVO> fwRules, DomainRouterVO router);
/**
* Create a port forwarding rule from the given ipAddress/port to the given virtual machine/port.
* @param cmd the command specifying the ip address, public port, protocol, private port, and virtual machine id.
* @return the newly created FirewallRuleVO if successful, null otherwise.
*/
public FirewallRuleVO createPortForwardingRule(CreateIPForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, NetworkRuleConflictException;
/**
* Create a load balancer rule from the given ipAddress/port to the given private port
* @param cmd the command specifying the ip address, public port, protocol, private port, and algorithm
* @return the newly created LoadBalancerVO if successful, null otherwise
*/
public LoadBalancerVO createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException;
/**
* Associates or disassociates a list of public IP address for a router.
* @param router router object to send the association to

View File

@ -18,6 +18,7 @@
package com.cloud.network;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@ -56,6 +57,8 @@ import com.cloud.agent.api.routing.VmDataCommand;
import com.cloud.agent.manager.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.api.commands.AssignToLoadBalancerRuleCmd;
import com.cloud.api.commands.CreateIPForwardingRuleCmd;
import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO;
@ -100,6 +103,7 @@ import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.LoadBalancerVMMapDao;
import com.cloud.network.dao.SecurityGroupDao;
import com.cloud.network.dao.SecurityGroupVMMapDao;
import com.cloud.offering.ServiceOffering.GuestIpType;
import com.cloud.service.ServiceOfferingVO;
@ -186,6 +190,7 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
@Inject ConfigurationManager _configMgr;
@Inject AsyncJobManager _asyncMgr;
@Inject StoragePoolDao _storagePoolDao = null;
@Inject SecurityGroupDao _securityGroupDao = null;
@Inject ServiceOfferingDao _serviceOfferingDao = null;
@Inject UserStatisticsDao _statsDao;
@ -1359,9 +1364,11 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
if (answers.length != ipAddrList.size()) {
return false;
}
for (int i1=0; i1 < answers.length; i1++) {
Answer ans = answers[i1];
// FIXME: this used to be a loop for all answers, but then we always returned the
// first one in the array, so what should really be done here?
if (answers.length > 0) {
Answer ans = answers[0];
return ans.getResult();
}
@ -1534,6 +1541,121 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
return result;
}
@Override
public FirewallRuleVO createPortForwardingRule(CreateIPForwardingRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, NetworkRuleConflictException {
// validate IP Address exists
IPAddressVO ipAddress = _ipAddressDao.findById(cmd.getIpAddress());
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid IP address specified.");
}
// validate user VM exists
UserVmVO userVM = _vmDao.findById(cmd.getVirtualMachineId());
if (userVM == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + cmd.getVirtualMachineId() + ").");
}
// validate that IP address and userVM belong to the same account
if ((ipAddress.getAccountId() == null) || (ipAddress.getAccountId().longValue() != userVM.getAccountId())) {
throw new InvalidParameterValueException("Unable to create port forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVM.toString());
}
// validate that userVM is in the same availability zone as the IP address
if (ipAddress.getDataCenterId() != userVM.getDataCenterId()) {
throw new InvalidParameterValueException("Unable to create port forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVM.toString());
}
// if an admin account was passed in, or no account was passed in, make sure we honor the accountName/domainId parameters
Account account = (Account)UserContext.current().getAccountObject();
if (account != null) {
if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
if (!_domainDao.isChildDomain(account.getDomainId(), userVM.getDomainId())) {
throw new PermissionDeniedException("Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + cmd.getVirtualMachineId() + ", permission denied.");
}
} else if (account.getId().longValue() != userVM.getAccountId()) {
throw new PermissionDeniedException("Unable to create port forwarding rule, IP address " + ipAddress + " to virtual machine " + cmd.getVirtualMachineId() + ", permission denied.");
}
}
// set up some local variables
String protocol = cmd.getProtocol();
String publicPort = cmd.getPublicPort();
String privatePort = cmd.getPrivatePort();
// sanity check that the vm can be applied to the load balancer
ServiceOfferingVO offering = _serviceOfferingDao.findById(userVM.getServiceOfferingId());
if ((offering == null) || !GuestIpType.Virtualized.equals(offering.getGuestIpType())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to create port forwarding rule (" + protocol + ":" + publicPort + "->" + privatePort + ") for virtual machine " + userVM.toString() + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
}
throw new IllegalArgumentException("Unable to create port forwarding rule (" + protocol + ":" + publicPort + "->" + privatePort + ") for virtual machine " + userVM.toString() + ", bad network type (" + ((offering == null) ? "null" : offering.getGuestIpType()) + ")");
}
// check for ip address/port conflicts by checking existing forwarding and load balancing rules
List<FirewallRuleVO> existingRulesOnPubIp = _rulesDao.listIPForwarding(ipAddress.getAddress());
Map<String, Pair<String, String>> mappedPublicPorts = new HashMap<String, Pair<String, String>>();
if (existingRulesOnPubIp != null) {
for (FirewallRuleVO fwRule : existingRulesOnPubIp) {
mappedPublicPorts.put(fwRule.getPublicPort(), new Pair<String, String>(fwRule.getPrivateIpAddress(), fwRule.getPrivatePort()));
}
}
Pair<String, String> privateIpPort = mappedPublicPorts.get(publicPort);
if (privateIpPort != null) {
if (privateIpPort.first().equals(userVM.getGuestIpAddress()) && privateIpPort.second().equals(privatePort)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("skipping the creating of firewall rule " + ipAddress + ":" + publicPort + " to " + userVM.getGuestIpAddress() + ":" + privatePort + "; rule already exists.");
}
return null; // already mapped
} else {
// FIXME: Will we need to refactor this for both assign port forwarding service and create port forwarding rule?
// throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + publicPort
// + " already exists, found while trying to create mapping to " + userVM.getGuestIpAddress() + ":" + privatePort + ((securityGroupId == null) ? "." : " from port forwarding service "
// + securityGroupId.toString() + "."));
throw new NetworkRuleConflictException("An existing port forwarding service rule for " + ipAddress + ":" + publicPort
+ " already exists, found while trying to create mapping to " + userVM.getGuestIpAddress() + ":" + privatePort + ".");
}
}
FirewallRuleVO newFwRule = new FirewallRuleVO();
newFwRule.setEnabled(true);
newFwRule.setForwarding(true);
newFwRule.setPrivatePort(privatePort);
newFwRule.setProtocol(protocol);
newFwRule.setPublicPort(publicPort);
newFwRule.setPublicIpAddress(ipAddress.getAddress());
newFwRule.setPrivateIpAddress(userVM.getGuestIpAddress());
// newFwRule.setGroupId(securityGroupId);
newFwRule.setGroupId(null);
// In 1.0 the rules were always persisted when a user created a rule. When the rules get sent down
// the stopOnError parameter is set to false, so the agent will apply all rules that it can. That
// behavior is preserved here by persisting the rule before sending it to the agent.
_rulesDao.persist(newFwRule);
boolean success = updateFirewallRule(newFwRule, null, null);
// Save and create the event
String description;
String ruleName = "ip forwarding";
String level = EventVO.LEVEL_INFO;
if (success == true) {
description = "created new " + ruleName + " rule [" + newFwRule.getPublicIpAddress() + ":" + newFwRule.getPublicPort() + "]->["
+ newFwRule.getPrivateIpAddress() + ":" + newFwRule.getPrivatePort() + "]" + " " + newFwRule.getProtocol();
} else {
level = EventVO.LEVEL_ERROR;
description = "failed to create new " + ruleName + " rule [" + newFwRule.getPublicIpAddress() + ":" + newFwRule.getPublicPort() + "]->["
+ newFwRule.getPrivateIpAddress() + ":" + newFwRule.getPrivatePort() + "]" + " " + newFwRule.getProtocol();
}
EventUtils.saveEvent(UserContext.current().getUserId(), userVM.getAccountId(), level, EventTypes.EVENT_NET_RULE_ADD, description);
return newFwRule;
}
@Override
public void assignToLoadBalancer(AssignToLoadBalancerRuleCmd cmd) throws NetworkRuleConflictException, InternalErrorException,
PermissionDeniedException, InvalidParameterValueException {
@ -1764,6 +1886,121 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
}
}
@Override
public LoadBalancerVO createLoadBalancerRule(CreateLoadBalancerRuleCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
String publicIp = cmd.getPublicIp();
// make sure ip address exists
IPAddressVO ipAddr = _ipAddressDao.findById(cmd.getPublicIp());
if (ipAddr == null) {
throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address " + publicIp);
}
VlanVO vlan = _vlanDao.findById(ipAddr.getVlanDbId());
if (vlan != null) {
if (!VlanType.VirtualNetwork.equals(vlan.getVlanType())) {
throw new InvalidParameterValueException("Unable to create load balancer rule for IP address " + publicIp + ", only VirtualNetwork type IP addresses can be used for load balancers.");
}
} // else ERROR?
// Verify input parameters
if ((ipAddr.getAccountId() == null) || (ipAddr.getAllocated() == null)) {
throw new InvalidParameterValueException("Unable to create load balancer rule, cannot find account owner for ip " + publicIp);
}
Account account = (Account)UserContext.current().getAccountObject();
if (account != null) {
if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
if (!_domainDao.isChildDomain(account.getDomainId(), ipAddr.getDomainId())) {
throw new PermissionDeniedException("Unable to create load balancer rule on IP address " + publicIp + ", permission denied.");
}
} else if (account.getId().longValue() != ipAddr.getAccountId().longValue()) {
throw new PermissionDeniedException("Unable to create load balancer rule, account " + account.getAccountName() + " doesn't own ip address " + publicIp);
}
}
String loadBalancerName = cmd.getLoadBalancerRuleName();
LoadBalancerVO existingLB = _loadBalancerDao.findByAccountAndName(ipAddr.getAccountId(), loadBalancerName);
if (existingLB != null) {
throw new InvalidParameterValueException("Unable to create load balancer rule, an existing load balancer rule with name " + loadBalancerName + " already exists.");
}
// validate params
String publicPort = cmd.getPublicPort();
String privatePort = cmd.getPrivatePort();
String algorithm = cmd.getAlgorithm();
if (!NetUtils.isValidPort(publicPort)) {
throw new InvalidParameterValueException("publicPort is an invalid value");
}
if (!NetUtils.isValidPort(privatePort)) {
throw new InvalidParameterValueException("privatePort is an invalid value");
}
if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) {
throw new InvalidParameterValueException("Invalid algorithm");
}
boolean locked = false;
try {
LoadBalancerVO exitingLB = _loadBalancerDao.findByIpAddressAndPublicPort(publicIp, publicPort);
if (exitingLB != null) {
throw new InvalidParameterValueException("IP Address/public port already load balanced by an existing load balancer rule");
}
List<FirewallRuleVO> existingFwRules = _rulesDao.listIPForwarding(publicIp, publicPort, true);
if ((existingFwRules != null) && !existingFwRules.isEmpty()) {
FirewallRuleVO existingFwRule = existingFwRules.get(0);
String securityGroupName = null;
if (existingFwRule.getGroupId() != null) {
long groupId = existingFwRule.getGroupId();
SecurityGroupVO securityGroup = _securityGroupDao.findById(groupId);
securityGroupName = securityGroup.getName();
}
throw new InvalidParameterValueException("IP Address (" + publicIp + ") and port (" + publicPort + ") already in use" +
((securityGroupName == null) ? "" : " by port forwarding service " + securityGroupName));
}
ipAddr = _ipAddressDao.acquire(publicIp);
if (ipAddr == null) {
throw new PermissionDeniedException("User does not own ip address " + publicIp);
}
locked = true;
LoadBalancerVO loadBalancer = new LoadBalancerVO(loadBalancerName, cmd.getDescription(), ipAddr.getAccountId(), publicIp, publicPort, privatePort, algorithm);
loadBalancer = _loadBalancerDao.persist(loadBalancer);
Long id = loadBalancer.getId();
// Save off information for the event that the security group was applied
Long userId = UserContext.current().getUserId();
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(ipAddr.getAccountId());
event.setType(EventTypes.EVENT_LOAD_BALANCER_CREATE);
if (id == null) {
event.setDescription("Failed to create load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]");
event.setLevel(EventVO.LEVEL_ERROR);
} else {
event.setDescription("Successfully created load balancer " + loadBalancer.getName() + " on ip address " + publicIp + "[" + publicPort + "->" + privatePort + "]");
String params = "id="+loadBalancer.getId()+"\ndcId="+ipAddr.getDataCenterId();
event.setParameters(params);
event.setLevel(EventVO.LEVEL_INFO);
}
_eventDao.persist(event);
return _loadBalancerDao.findById(id);
} finally {
if (locked) {
_ipAddressDao.release(publicIp);
}
}
}
@Override @DB
public boolean releasePublicIpAddress(long userId, final String ipAddress) {
IPAddressVO ip = null;

View File

@ -20,6 +20,8 @@ package com.cloud.network.security;
import java.util.HashMap;
import java.util.List;
import com.cloud.api.commands.CreateNetworkGroupCmd;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.server.Criteria;
@ -45,6 +47,13 @@ public interface NetworkGroupManager extends Manager {
String [] cidrList, List<NetworkGroupVO> authorizedGroups);
public NetworkGroupVO createNetworkGroup(String name, String description, Long domainId, Long accountId, String accountName);
/**
* Create a network group with the given name and description
* @param command the command specifying the name and description
* @return the created network group if successful, null otherwise
*/
public NetworkGroupVO createNetworkGroup(CreateNetworkGroupCmd command) throws PermissionDeniedException, InvalidParameterValueException;
public NetworkGroupVO createDefaultNetworkGroup( Long accountId);

View File

@ -41,10 +41,12 @@ import com.cloud.agent.api.Command;
import com.cloud.agent.api.NetworkIngressRulesCmd;
import com.cloud.agent.api.NetworkIngressRulesCmd.IpPortAndProto;
import com.cloud.agent.manager.AgentManager;
import com.cloud.api.commands.CreateNetworkGroupCmd;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.network.security.NetworkGroupWorkVO.Step;
@ -58,6 +60,7 @@ import com.cloud.server.Criteria;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.UserContext;
import com.cloud.user.dao.AccountDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
@ -537,7 +540,66 @@ public class NetworkGroupManagerImpl implements NetworkGroupManager {
}
}
@Override
public NetworkGroupVO createNetworkGroup(CreateNetworkGroupCmd cmd) throws PermissionDeniedException, InvalidParameterValueException {
if (!_enabled) {
return null;
}
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
Long accountId = null;
Account account = (Account)UserContext.current().getAccountObject();
if (account != null) {
if ((account.getType() == Account.ACCOUNT_TYPE_ADMIN) || (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
if ((domainId != null) && (accountName != null)) {
if (!_domainDao.isChildDomain(account.getDomainId(), domainId)) {
throw new PermissionDeniedException("Unable to create network group in domain " + domainId + ", permission denied.");
}
Account userAccount = _accountDao.findActiveAccount(accountName, domainId);
if (userAccount == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId + ", failed to create network group " + cmd.getNetworkGroupName());
}
accountId = userAccount.getId();
} else {
// the admin must be creating a network group for himself/herself
if (account != null) {
accountId = account.getId();
domainId = account.getDomainId();
accountName = account.getAccountName();
}
}
} else {
accountId = account.getId();
domainId = account.getDomainId();
accountName = account.getAccountName();
}
}
// if no account exists in the context, it's a system level command, look up the account
if (accountId == null) {
if ((accountName != null) && (domainId != null)) {
Account userAccount = _accountDao.findActiveAccount(accountName, domainId);
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId + ", failed to create network group " + cmd.getNetworkGroupName());
}
} else {
throw new InvalidParameterValueException("Missing account information (account: " + accountName + ", domain: " + domainId + "), failed to create network group " + cmd.getNetworkGroupName());
}
}
if (_networkGroupDao.isNameInUse(accountId, domainId, cmd.getNetworkGroupName())) {
throw new InvalidParameterValueException("Unable to create network group, a group with name " + cmd.getNetworkGroupName() + " already exisits.");
}
return createNetworkGroup(cmd.getNetworkGroupName(), cmd.getDescription(), domainId, accountId, accountName);
}
@DB
@Override
@ -629,8 +691,9 @@ public class NetworkGroupManagerImpl implements NetworkGroupManager {
@DB
public void work() {
s_logger.trace("Checking the database");
if (s_logger.isTraceEnabled()) {
s_logger.trace("Checking the database");
}
final NetworkGroupWorkVO work = _workDao.take(_serverId);
if (work == null) {
return;
@ -800,7 +863,7 @@ public class NetworkGroupManagerImpl implements NetworkGroupManager {
if (networkGroup != null) {
sc.setParameters("name", networkGroup);
} else if (keyword != null) {
SearchCriteria ssc = _networkGroupRulesDao.createSearchCriteria();
SearchCriteria<NetworkGroupRulesVO> ssc = _networkGroupRulesDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);

View File

@ -25,24 +25,27 @@ import java.util.List;
import java.util.Map;
import com.cloud.alert.AlertVO;
import com.cloud.api.commands.CreateDomainCmd;
import com.cloud.api.commands.EnableAccountCmd;
import com.cloud.api.commands.EnableUserCmd;
import com.cloud.api.commands.GetCloudIdentifierCmd;
import com.cloud.api.commands.UpdateAccountCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.api.commands.UpdateTemplateCmd;
import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd;
import com.cloud.api.commands.UpdateUserCmd;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.capacity.CapacityVO;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterIpAddressVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.domain.DomainVO;
import com.cloud.event.EventVO;
import com.cloud.exception.ConcurrentOperationException;
@ -296,7 +299,7 @@ public interface ManagementServer {
* @return true if update was successful, false otherwise
* @throws InvalidParameterValueException
*/
boolean updateUser(long userId, String username, String password, String firstname, String lastname, String email, String timezone, String apiKey, String secretKey) throws InvalidParameterValueException;
// boolean updateUser(long userId, String username, String password, String firstname, String lastname, String email, String timezone, String apiKey, String secretKey) throws InvalidParameterValueException;
/**
* Locate a user by their apiKey
@ -730,8 +733,8 @@ public interface ManagementServer {
* @param serviceOfferingId
* @return success/failure
*/
boolean upgradeVirtualMachine(long userId, long vmId, long serviceOfferingId, long startEventId);
long upgradeVirtualMachineAsync(long userId, long vmId, long serviceOfferingId) throws InvalidParameterValueException;
// boolean upgradeVirtualMachine(long userId, long vmId, long serviceOfferingId, long startEventId);
// long upgradeVirtualMachineAsync(long userId, long vmId, long serviceOfferingId) throws InvalidParameterValueException;
/**
@ -742,14 +745,14 @@ public interface ManagementServer {
* @param userId - id of user performing the update on the virtual machine
* @param accountId - id of the account that owns the virtual machine
*/
void updateVirtualMachine(long vmId, String displayName, String group, boolean enable, Long userId, long accountId);
// void updateVirtualMachine(long vmId, String displayName, String group, boolean enable, Long userId, long accountId);
/**
* Updates a storage pool.
* @param poolId ID of the storage pool to be updated
* @param tags Tags that will be added to the storage pool
*/
StoragePoolVO updateStoragePool(long poolId, String tags);
// StoragePoolVO updateStoragePool(long poolId, String tags);
/**
* Starts a Domain Router
@ -987,20 +990,7 @@ public interface ManagementServer {
* @param tags tags for the service offering. if null, no change will be made. if empty string, all tags will be removed.
* @return the updated ServiceOfferingVO
*/
ServiceOfferingVO updateServiceOffering(long userId, long serviceOfferingId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags);
/**
* Adds a new pod to the database
* @param userId
* @param podName
* @param zoneId
* @param gateway
* @param cidr
* @param startIp
* @param endIp
* @return Pod
*/
HostPodVO createPod(long userId, String podName, Long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
// ServiceOfferingVO updateServiceOffering(long userId, long serviceOfferingId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags);
/**
* Edits a pod in the database
@ -1013,7 +1003,7 @@ public interface ManagementServer {
* @param endIp
* @return Pod
*/
HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
// HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException;
// /**
// * Deletes a pod from the database
@ -1255,18 +1245,6 @@ public interface ManagementServer {
*/
List<FirewallRuleVO> listIPForwarding(String publicIPAddress, boolean forwarding);
/**
* Create a single port forwarding rule from the given ip address and port to the vm's guest IP address and private port with the given protocol.
* @param userId the id of the user performing the action (could be an admin's ID if performing on behalf of a user)
* @param ipAddressVO
* @param userVM
* @param publicPort
* @param privatePort
* @param protocol
* @return
*/
FirewallRuleVO createPortForwardingRule(long userId, IPAddressVO ipAddressVO, UserVmVO userVM, String publicPort, String privatePort, String protocol) throws NetworkRuleConflictException;
/**
* Update an existing port forwarding rule on the given public IP / public port for the given protocol
* @param userId id of the user performing the action
@ -1518,13 +1496,9 @@ public interface ManagementServer {
/**
* create a new domain
* @param id
* @param domain name
* @param ownerId
* @param parentId
*
* @param command - the create command defining the name to use and the id of the parent domain under which to create the new domain.
*/
DomainVO createDomain(String name, Long ownerId, Long parentId);
DomainVO createDomain(CreateDomainCmd command) throws InvalidParameterValueException, PermissionDeniedException;
/**
* delete a domain with the given domainId
@ -1631,7 +1605,7 @@ public interface ManagementServer {
* @return
* @throws InvalidParameterValueException
*/
ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException;
// ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException;
/**
* Deletes a Limit
@ -1654,7 +1628,7 @@ public interface ManagementServer {
* @param type
* @return a list of Limits
*/
List<ResourceLimitVO> searchForLimits(Criteria c);
// List<ResourceLimitVO> searchForLimits(Criteria c);
/**
* Finds the correct limit for an account. I.e. if an account's limit is not present, it will check the account's domain, and as a last resort use the global limit.
@ -1781,7 +1755,7 @@ public interface ManagementServer {
* @throws PermissionDeniedException
* @throws InternalErrorException
*/
boolean updateTemplatePermissions(long templateId, String operation, Boolean isPublic, Boolean isFeatured, List<String> accountNames) throws InvalidParameterValueException, PermissionDeniedException, InternalErrorException;
// boolean updateTemplatePermissions(long templateId, String operation, Boolean isPublic, Boolean isFeatured, List<String> accountNames) throws InvalidParameterValueException, PermissionDeniedException, InternalErrorException;
/**
* List the permissions on a template. This will return a list of account names that have been granted permission to launch instances from the template.
@ -1927,7 +1901,6 @@ public interface ManagementServer {
LoadBalancerVO findLoadBalancerById(long loadBalancerId);
List<UserVmVO> listLoadBalancerInstances(long loadBalancerId, boolean applied);
List<LoadBalancerVO> searchForLoadBalancers(Criteria c);
LoadBalancerVO createLoadBalancer(Long userId, Long accountId, String name, String description, String ipAddress, String publicPort, String privatePort, String algorithm) throws InvalidParameterValueException, PermissionDeniedException;
boolean deleteLoadBalancer(long userId, long loadBalancerId);
long deleteLoadBalancerAsync(long userId, long loadBalancerId);
@ -2041,16 +2014,6 @@ public interface ManagementServer {
*/
ArrayList<String> getCloudIdentifierResponse(GetCloudIdentifierCmd cmd) throws InvalidParameterValueException;
/**
* check if a network security group name in the given account/domain is in use
* - if accountId is specified, look only for the account
* - otherwise look for the name in domain-level security groups (accountId is null)
* @param domainId id of the domain in which to search for security groups
* @param accountId id of the account in which to search for security groups
* @param name name of the security group to look for
* @return true if the security group name is found, false otherwise
*/
boolean isNetworkSecurityGroupNameInUse(Long domainId, Long accountId, String name);
NetworkGroupVO findNetworkGroupByName(Long accountId, String groupName);
/**
@ -2089,8 +2052,6 @@ public interface ManagementServer {
long revokeNetworkGroupIngressAsync(Long accountId, String groupName, String protocol, int startPort, int endPort, String [] cidrList, List<NetworkGroupVO> authorizedGroups);
boolean revokeNetworkGroupIngress(AccountVO account, String groupName, String protocol, int startPort, int endPort, String [] cidrList, List<NetworkGroupVO> authorizedGroups);
NetworkGroupVO createNetworkGroup(String name, String description, Long domainId, Long accountId, String accountName);
/**
* Delete an empty network group. If the group is not empty an error is returned.
* @param groupId
@ -2137,4 +2098,6 @@ public interface ManagementServer {
// boolean addConfig(String instance, String component, String category, String name, String value, String description);
boolean validateCustomVolumeSizeRange(long size) throws InvalidParameterValueException;
boolean updateUser(UpdateUserCmd cmd) throws InvalidParameterValueException;
boolean updateTemplatePermissions(UpdateTemplateOrIsoPermissionsCmd cmd)throws InvalidParameterValueException, PermissionDeniedException,InternalErrorException;
}

View File

@ -64,6 +64,7 @@ import com.cloud.api.commands.AuthorizeNetworkGroupIngressCmd;
import com.cloud.api.commands.CancelMaintenanceCmd;
import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd;
import com.cloud.api.commands.CopyTemplateCmd;
import com.cloud.api.commands.CreateDomainCmd;
import com.cloud.api.commands.CreatePortForwardingServiceRuleCmd;
import com.cloud.api.commands.CreateTemplateCmd;
import com.cloud.api.commands.CreateVolumeCmd;
@ -82,8 +83,11 @@ import com.cloud.api.commands.StartSystemVMCmd;
import com.cloud.api.commands.StartVMCmd;
import com.cloud.api.commands.UpdateAccountCmd;
import com.cloud.api.commands.UpdateDomainCmd;
import com.cloud.api.commands.UpdateIsoPermissionsCmd;
import com.cloud.api.commands.UpdateTemplateCmd;
import com.cloud.api.commands.UpgradeVMCmd;
import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd;
import com.cloud.api.commands.UpdateTemplatePermissionsCmd;
import com.cloud.api.commands.UpdateUserCmd;
import com.cloud.async.AsyncInstanceCreateStatus;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
@ -106,17 +110,16 @@ import com.cloud.async.executor.NetworkGroupIngressParam;
import com.cloud.async.executor.ResetVMPasswordParam;
import com.cloud.async.executor.SecurityGroupParam;
import com.cloud.async.executor.UpdateLoadBalancerParam;
import com.cloud.async.executor.UpgradeVMParam;
import com.cloud.async.executor.VMOperationParam;
import com.cloud.async.executor.VMOperationParam.VmOp;
import com.cloud.async.executor.VolumeOperationParam;
import com.cloud.async.executor.VMOperationParam.VmOp;
import com.cloud.async.executor.VolumeOperationParam.VolumeOp;
import com.cloud.capacity.CapacityVO;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.consoleproxy.ConsoleProxyManager;
@ -126,8 +129,8 @@ import com.cloud.dc.DataCenterIpAddressVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.VlanVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.dc.dao.AccountVlanMapDao;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
@ -193,22 +196,22 @@ import com.cloud.storage.GuestOSCategoryVO;
import com.cloud.storage.GuestOSVO;
import com.cloud.storage.LaunchPermissionVO;
import com.cloud.storage.Snapshot;
import com.cloud.storage.Snapshot.SnapshotType;
import com.cloud.storage.SnapshotPolicyVO;
import com.cloud.storage.SnapshotScheduleVO;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.Storage;
import com.cloud.storage.Storage.FileSystem;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.StorageStats;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.Volume.VolumeType;
import com.cloud.storage.VolumeStats;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.Snapshot.SnapshotType;
import com.cloud.storage.Storage.FileSystem;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Volume.VolumeType;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.DiskTemplateDao;
import com.cloud.storage.dao.GuestOSCategoryDao;
@ -218,9 +221,9 @@ import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotPolicyDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VMTemplateDao.TemplateFilter;
import com.cloud.storage.dao.VMTemplateHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VMTemplateDao.TemplateFilter;
import com.cloud.storage.preallocatedlun.PreallocatedLunVO;
import com.cloud.storage.preallocatedlun.dao.PreallocatedLunDao;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
@ -242,12 +245,12 @@ import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.uservm.UserVm;
import com.cloud.utils.DateUtil;
import com.cloud.utils.DateUtil.IntervalType;
import com.cloud.utils.EnumUtils;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.StringUtils;
import com.cloud.utils.DateUtil.IntervalType;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.concurrency.NamedThreadFactory;
@ -368,7 +371,8 @@ public class ManagementServerImpl implements ManagementServer {
private boolean _isHypervisorSnapshotCapable = false;
private final int _maxVolumeSizeInGb;
protected ManagementServerImpl() {
ComponentLocator locator = ComponentLocator.getLocator(Name);
_lunDao = locator.getDao(PreallocatedLunDao.class);
@ -462,6 +466,11 @@ public class ManagementServerImpl implements ManagementServer {
// Parse the max number of UserVMs and public IPs from server-setup.xml,
// and set them in the right places
String maxVolumeSizeInGbString = _configs.get("max.volume.size.gb");
int maxVolumeSizeGb = NumbersUtil.parseInt(maxVolumeSizeInGbString, 2000);
_maxVolumeSizeInGb = maxVolumeSizeGb;
_routerRamSize = NumbersUtil.parseInt(_configs.get("router.ram.size"),NetworkManager.DEFAULT_ROUTER_VM_RAMSIZE);
_proxyRamSize = NumbersUtil.parseInt(_configs.get("consoleproxy.ram.size"), ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE);
@ -1266,14 +1275,68 @@ public class ManagementServerImpl implements ManagementServer {
@Override
public boolean updateUser(long userId, String username, String password, String firstname, String lastname, String email, String timezone, String apiKey, String secretKey) throws InvalidParameterValueException{
UserVO user = _userDao.findById(userId);
public boolean updateUser(UpdateUserCmd cmd) throws InvalidParameterValueException
{
Long id = cmd.getId();
String apiKey = cmd.getApiKey();
String firstName = cmd.getFirstname();
String email = cmd.getEmail();
String lastName = cmd.getLastname();
String password = cmd.getPassword();
String secretKey = cmd.getSecretKey();
String timeZone = cmd.getTimezone();
String userName = cmd.getUsername();
//Input validation
UserVO user = _userDao.getUser(id);
if (user == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find user by id");
}
if((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null))
{
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please provide an api key/secret key pair");
}
// If the account is an admin type, return an error. We do not allow this
Account account = (Account)UserContext.current().getAccountObject();
if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "user id : " + id + " is system account, update is not allowed");
}
if (firstName == null) {
firstName = user.getFirstname();
}
if (lastName == null) {
lastName = user.getLastname();
}
if (userName == null) {
userName = user.getUsername();
}
if (password == null) {
password = user.getPassword();
}
if (email == null) {
email = user.getEmail();
}
if (timeZone == null) {
timeZone = user.getTimezone();
}
if (apiKey == null) {
apiKey = user.getApiKey();
}
if (secretKey == null) {
secretKey = user.getSecretKey();
}
Long accountId = user.getAccountId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("updating user with id: " + userId);
s_logger.debug("updating user with id: " + id);
}
UserAccount userAccount = _userAccountDao.findById(userId);
UserAccount userAccount = _userAccountDao.findById(id);
try
{
//check if the apiKey and secretKey are globally unique
@ -1285,8 +1348,8 @@ public class ManagementServerImpl implements ManagementServer {
{
User usr = apiKeyOwner.first();
if(usr.getId() != userId)
throw new InvalidParameterValueException("The api key:"+apiKey+" exists in the system for user id:"+userId+" ,please provide a unique key");
if(usr.getId() != id)
throw new InvalidParameterValueException("The api key:"+apiKey+" exists in the system for user id:"+id+" ,please provide a unique key");
else
{
//allow the updation to take place
@ -1296,12 +1359,12 @@ public class ManagementServerImpl implements ManagementServer {
}
_userDao.update(userId, username, password, firstname, lastname, email, accountId, timezone, apiKey, secretKey);
EventUtils.saveEvent(new Long(1), Long.valueOf(1), EventVO.LEVEL_INFO, EventTypes.EVENT_USER_UPDATE, "User, " + username + " for accountId = "
+ accountId + " domainId = " + userAccount.getDomainId() + " and timezone = "+timezone + " was updated.");
_userDao.update(id, userName, password, firstName, lastName, email, accountId, timeZone, apiKey, secretKey);
EventUtils.saveEvent(new Long(1), Long.valueOf(1), EventVO.LEVEL_INFO, EventTypes.EVENT_USER_UPDATE, "User, " + userName + " for accountId = "
+ accountId + " domainId = " + userAccount.getDomainId() + " and timezone = "+timeZone + " was updated.");
} catch (Throwable th) {
s_logger.error("error updating user", th);
EventUtils.saveEvent(Long.valueOf(1), Long.valueOf(1), EventVO.LEVEL_ERROR, EventTypes.EVENT_USER_UPDATE, "Error updating user, " + username
EventUtils.saveEvent(Long.valueOf(1), Long.valueOf(1), EventVO.LEVEL_ERROR, EventTypes.EVENT_USER_UPDATE, "Error updating user, " + userName
+ " for accountId = " + accountId + " and domainId = " + userAccount.getDomainId());
return false;
}
@ -2610,6 +2673,7 @@ public class ManagementServerImpl implements ManagementServer {
return _vmMgr.recoverVirtualMachine(vmId);
}
/*
@Override
public boolean upgradeVirtualMachine(long userId, long vmId, long serviceOfferingId,long startEventId) {
UserVmVO userVm = _userVmDao.findById(vmId);
@ -2700,35 +2764,12 @@ public class ManagementServerImpl implements ManagementServer {
return _asyncMgr.submitAsyncJob(job, true);
}
@Override
public void updateVirtualMachine(long vmId, String displayName, String group, boolean enable, Long userId, long accountId) {
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new CloudRuntimeException("Unable to find virual machine with id " + vmId);
}
boolean haEnabled = vm.isHaEnabled();
_userVmDao.updateVM(vmId, displayName, group, enable);
if (haEnabled != enable) {
String description = null;
String type = null;
if (enable) {
description = "Successfully enabled HA for virtual machine " + vm.getName();
type = EventTypes.EVENT_VM_ENABLE_HA;
} else {
description = "Successfully disabled HA for virtual machine " + vm.getName();
type = EventTypes.EVENT_VM_DISABLE_HA;
}
// create a event for the change in HA Enabled flag
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_INFO, type, description, null);
}
}
*/
@Override
public StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException {
return _storageMgr.updateStoragePool(poolId, tags);
}
// @Override
// public StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException {
// return _storageMgr.updateStoragePool(poolId, tags);
// }
@Override
public DomainRouter startRouter(long routerId, long startEventId) throws InternalErrorException {
@ -4272,37 +4313,11 @@ public class ManagementServerImpl implements ManagementServer {
return _configMgr.createServiceOffering(userId, name, cpu, ramSize, speed, displayText, localStorageRequired, offerHA, useVirtualNetwork, tags);
}
@Override
public ServiceOfferingVO updateServiceOffering(long userId, long serviceOfferingId, String name, String displayText, Boolean offerHA, Boolean useVirtualNetwork, String tags) {
return _configMgr.updateServiceOffering(userId, serviceOfferingId, name, displayText, offerHA, useVirtualNetwork, tags);
}
@Override
public HostPodVO createPod(long userId, String podName, Long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException {
return _configMgr.createPod(userId, podName, zoneId, gateway, cidr, startIp, endIp);
}
@Override
public HostPodVO editPod(long userId, long podId, String newPodName, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException {
return _configMgr.editPod(userId, podId, newPodName, gateway, cidr, startIp, endIp);
}
// @Override
// public void deletePod(long userId, long podId) throws InvalidParameterValueException, InternalErrorException {
// _configMgr.deletePod(userId, podId);
// }
@Override
public DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String vnetRange,String guestCidr) throws InvalidParameterValueException, InternalErrorException {
return _configMgr.createZone(userId, zoneName, dns1, dns2, internalDns1, internalDns2, vnetRange, guestCidr);
}
// @Override
// public DataCenterVO editZone(long userId, Long zoneId, String newZoneName, String dns1, String dns2, String dns3, String dns4, String vnetRange, String guestCidr) throws InvalidParameterValueException, InternalErrorException {
// return _configMgr.editZone(userId, zoneId, newZoneName, dns1, dns2, dns3, dns4, vnetRange, guestCidr);
// }
@Override
public void deleteZone(long userId, Long zoneId) throws InvalidParameterValueException, InternalErrorException {
_configMgr.deleteZone(userId, zoneId);
@ -4429,10 +4444,10 @@ public class ManagementServerImpl implements ManagementServer {
return null;
}
@Override
public ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException {
return _accountMgr.updateResourceLimit(domainId, accountId, type, max);
}
// @Override
// public ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException {
// return _accountMgr.updateResourceLimit(domainId, accountId, type, max);
// }
@Override
public boolean deleteLimit(Long limitId) {
@ -4448,117 +4463,6 @@ public class ManagementServerImpl implements ManagementServer {
return _resourceLimitDao.findById(limitId);
}
@Override
public List<ResourceLimitVO> searchForLimits(Criteria c) {
Long domainId = (Long) c.getCriteria(Criteria.DOMAINID);
Long accountId = (Long) c.getCriteria(Criteria.ACCOUNTID);
ResourceType type = (ResourceType) c.getCriteria(Criteria.TYPE);
// For 2.0, we are just limiting the scope to having an user retrieve
// limits for himself and if limits don't exist, use the ROOT domain's limits.
// - Will
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
if(accountId!=null && domainId!=null)
{
//if domainId==1 and account belongs to admin
//return all records for resource limits (bug 3778)
if(domainId==1)
{
AccountVO account = _accountDao.findById(accountId);
if(account!=null && account.getType()==1)
{
//account belongs to admin
//return all limits
limits = _resourceLimitDao.listAll();
return limits;
}
}
//if account belongs to system, accountid=1,domainid=1
//return all the records for resource limits (bug:3778)
if(accountId==1 && domainId==1)
{
limits = _resourceLimitDao.listAll();
return limits;
}
}
if (accountId != null) {
SearchBuilder<ResourceLimitVO> sb = _resourceLimitDao.createSearchBuilder();
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
SearchCriteria<ResourceLimitVO> sc = sb.create();
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (type != null) {
sc.setParameters("type", type);
}
// Listing all limits for an account
if (type == null) {
//List<ResourceLimitVO> userLimits = _resourceLimitDao.search(sc, searchFilter);
List<ResourceLimitVO> userLimits = _resourceLimitDao.listByAccountId(accountId);
List<ResourceLimitVO> rootLimits = _resourceLimitDao.listByDomainId(DomainVO.ROOT_DOMAIN);
ResourceType resourceTypes[] = ResourceType.values();
for (ResourceType resourceType: resourceTypes) {
boolean found = false;
for (ResourceLimitVO userLimit : userLimits) {
if (userLimit.getType() == resourceType) {
limits.add(userLimit);
found = true;
break;
}
}
if (!found) {
// Check the ROOT domain
for (ResourceLimitVO rootLimit : rootLimits) {
if (rootLimit.getType() == resourceType) {
limits.add(rootLimit);
found = true;
break;
}
}
}
if (!found) {
limits.add(new ResourceLimitVO(domainId, accountId, resourceType, -1L));
}
}
} else {
AccountVO account = _accountDao.findById(accountId);
limits.add(new ResourceLimitVO(null, accountId, type, _accountMgr.findCorrectResourceLimit(account, type)));
}
} else if (domainId != null) {
if (type == null) {
ResourceType resourceTypes[] = ResourceType.values();
List<ResourceLimitVO> domainLimits = _resourceLimitDao.listByDomainId(domainId);
for (ResourceType resourceType: resourceTypes) {
boolean found = false;
for (ResourceLimitVO domainLimit : domainLimits) {
if (domainLimit.getType() == resourceType) {
limits.add(domainLimit);
found = true;
break;
}
}
if (!found) {
limits.add(new ResourceLimitVO(domainId, null, resourceType, -1L));
}
}
} else {
limits.add(_resourceLimitDao.findByDomainIdAndType(domainId, type));
}
}
return limits;
}
@Override
public long findCorrectResourceLimit(ResourceType type, long accountId) {
@ -5120,11 +5024,6 @@ public class ManagementServerImpl implements ManagementServer {
return _firewallRulesDao.listIPForwarding(publicIPAddress, forwarding);
}
@Override
public FirewallRuleVO createPortForwardingRule(long userId, IPAddressVO ipAddressVO, UserVmVO userVM, String publicPort, String privatePort, String protocol) throws NetworkRuleConflictException {
return createFirewallRule(userId, ipAddressVO.getAddress(), userVM, publicPort, privatePort, protocol, null);
}
@Override
public FirewallRuleVO updatePortForwardingRule(long userId, String publicIp, String privateIp, String publicPort, String privatePort, String protocol) {
List<FirewallRuleVO> fwRules = _firewallRulesDao.listIPForwardingForUpdate(publicIp, publicPort, protocol);
@ -6247,9 +6146,31 @@ public class ManagementServerImpl implements ManagementServer {
return _domainDao.search(sc, searchFilter);
}
@Override
public DomainVO createDomain(String name, Long ownerId, Long parentId) {
public DomainVO createDomain(CreateDomainCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
String name = cmd.getDomainName();
Long parentId = cmd.getParentDomainId();
Long ownerId = UserContext.current().getAccountId();
Account account = (Account)UserContext.current().getAccountObject();
if (ownerId == null) {
ownerId = Long.valueOf(1);
}
if (parentId == null) {
parentId = Long.valueOf(DomainVO.ROOT_DOMAIN);
}
DomainVO parentDomain = _domainDao.findById(parentId);
if (parentDomain == null) {
throw new InvalidParameterValueException("Unable to create domain " + name + ", parent domain " + parentId + " not found.");
}
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), parentId)) {
throw new PermissionDeniedException("Unable to create domain " + name + ", permission denied.");
}
SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, name);
sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
@ -6688,15 +6609,102 @@ public class ManagementServerImpl implements ManagementServer {
public List<DiskOfferingVO> findPrivateDiskOffering() {
return _diskOfferingDao.findPrivateDiskOffering();
}
protected boolean templateIsCorrectType(VMTemplateVO template) {
return true;
}
public static boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
@Override
@DB
public boolean updateTemplatePermissions(long templateId, String operation, Boolean isPublic, Boolean isFeatured, List<String> accountNames) throws InvalidParameterValueException,
public boolean updateTemplatePermissions(UpdateTemplateOrIsoPermissionsCmd cmd) throws InvalidParameterValueException,
PermissionDeniedException, InternalErrorException {
Transaction txn = Transaction.currentTxn();
VMTemplateVO template = _templateDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("Unable to find template with id " + templateId);
//Input validation
Long id = cmd.getId();
Account account = (Account) UserContext.current().getAccountObject();
List<String> accountNames = cmd.getAccountNames();
Long userId = UserContext.current().getUserId();
Boolean isFeatured = cmd.isFeatured();
Boolean isPublic = cmd.isPublic();
String operation = cmd.getOperation();
String mediaType = "";
VMTemplateVO template = _templateDao.findById(id);
if (template == null || !templateIsCorrectType(template)) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "unable to find " + mediaType + " with id " + id);
}
if(cmd instanceof UpdateTemplatePermissionsCmd)
{
mediaType = "template";
if(template.getFormat().equals(ImageFormat.ISO))
{
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Please provide a valid template");
}
}
if(cmd instanceof UpdateIsoPermissionsCmd)
{
mediaType = "iso";
if(!template.getFormat().equals(ImageFormat.ISO))
{
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Please provide a valid iso");
}
}
if (account != null)
{
if (!isAdmin(account.getType()) && (template.getAccountId() != account.getId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to update permissions for " + mediaType + " with id " + id);
} else if (account.getType() != Account.ACCOUNT_TYPE_ADMIN) {
Long templateOwnerDomainId = findDomainIdByAccountId(template.getAccountId());
if (!isChildDomain(account.getDomainId(), templateOwnerDomainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update permissions for " + mediaType + " with id " + id);
}
}
}
// If command is executed via 8096 port, set userId to the id of System account (1)
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
// If the template is removed throw an error.
if (template.getRemoved() != null){
s_logger.error("unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
}
if (id == Long.valueOf(1)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to update permissions for " + mediaType + " with id " + id);
}
boolean isAdmin = ((account == null) || isAdmin(account.getType()));
boolean allowPublicUserTemplates = Boolean.parseBoolean(getConfigurationValue("allow.public.user.templates"));
if (!isAdmin && !allowPublicUserTemplates && isPublic != null && isPublic) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Only private " + mediaType + "s can be created.");
}
// // package up the accountNames as a list
// List<String> accountNameList = new ArrayList<String>();
if (accountNames != null)
{
if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset")))
{
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." +
" Given operation is: '" + operation + "'");
}
// StringTokenizer st = new StringTokenizer(accountNames, ",");
// while (st.hasMoreTokens()) {
// accountNameList.add(st.nextToken());
// }
}
Long accountId = template.getAccountId();
@ -6705,11 +6713,6 @@ public class ManagementServerImpl implements ManagementServer {
throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName());
}
Account account = _accountDao.findById(accountId);
if (account == null) {
throw new PermissionDeniedException("Unable to verify owner of template " + template.getName());
}
VMTemplateVO updatedTemplate = _templateDao.createForUpdate();
if (isPublic != null) {
@ -6731,9 +6734,9 @@ public class ManagementServerImpl implements ManagementServer {
if (permittedAccount.getId().longValue() == account.getId().longValue()) {
continue; // don't grant permission to the template owner, they implicitly have permission
}
LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(templateId, permittedAccount.getId().longValue());
LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId().longValue());
if (existingPermission == null) {
LaunchPermissionVO launchPermission = new LaunchPermissionVO(templateId, permittedAccount.getId().longValue());
LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId().longValue());
_launchPermissionDao.persist(launchPermission);
}
} else {
@ -6752,7 +6755,7 @@ public class ManagementServerImpl implements ManagementServer {
accountIds.add(permittedAccount.getId());
}
}
_launchPermissionDao.removePermissions(templateId, accountIds);
_launchPermissionDao.removePermissions(id, accountIds);
} catch (CloudRuntimeException ex) {
throw new InternalErrorException("Internal error removing launch permissions for template " + template.getName());
}
@ -6763,7 +6766,7 @@ public class ManagementServerImpl implements ManagementServer {
updatedTemplate.setPublicTemplate(false);
updatedTemplate.setFeatured(false);
_templateDao.update(template.getId(), updatedTemplate);
_launchPermissionDao.removeAllPermissions(templateId);
_launchPermissionDao.removeAllPermissions(id);
}
return true;
}
@ -7085,86 +7088,6 @@ public class ManagementServerImpl implements ManagementServer {
return _loadBalancerDao.findById(Long.valueOf(loadBalancerId));
}
@Override
@DB
public LoadBalancerVO createLoadBalancer(Long userId, Long accountId, String name, String description, String ipAddress, String publicPort, String privatePort, String algorithm)
throws InvalidParameterValueException, PermissionDeniedException {
if (accountId == null) {
throw new InvalidParameterValueException("accountId not specified");
}
if (!NetUtils.isValidIp(ipAddress)) {
throw new InvalidParameterValueException("invalid ip address");
}
if (!NetUtils.isValidPort(publicPort)) {
throw new InvalidParameterValueException("publicPort is an invalid value");
}
if (!NetUtils.isValidPort(privatePort)) {
throw new InvalidParameterValueException("privatePort is an invalid value");
}
if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) {
throw new InvalidParameterValueException("Invalid algorithm");
}
boolean locked = false;
try {
LoadBalancerVO exitingLB = _loadBalancerDao.findByIpAddressAndPublicPort(ipAddress, publicPort);
if (exitingLB != null) {
throw new InvalidParameterValueException("IP Address/public port already load balanced by an existing load balancer rule");
}
List<FirewallRuleVO> existingFwRules = _firewallRulesDao.listIPForwarding(ipAddress, publicPort, true);
if ((existingFwRules != null) && !existingFwRules.isEmpty()) {
FirewallRuleVO existingFwRule = existingFwRules.get(0);
String securityGroupName = null;
if (existingFwRule.getGroupId() != null) {
long groupId = existingFwRule.getGroupId();
SecurityGroupVO securityGroup = _securityGroupDao.findById(groupId);
securityGroupName = securityGroup.getName();
}
throw new InvalidParameterValueException("IP Address (" + ipAddress + ") and port (" + publicPort + ") already in use" +
((securityGroupName == null) ? "" : " by port forwarding service " + securityGroupName));
}
IPAddressVO addr = _publicIpAddressDao.acquire(ipAddress);
if (addr == null) {
throw new PermissionDeniedException("User does not own ip address " + ipAddress);
}
locked = true;
if ((addr.getAllocated() == null) || !accountId.equals(addr.getAccountId())) {
throw new PermissionDeniedException("User does not own ip address " + ipAddress);
}
LoadBalancerVO loadBalancer = new LoadBalancerVO(name, description, accountId.longValue(), ipAddress, publicPort, privatePort, algorithm);
loadBalancer = _loadBalancerDao.persist(loadBalancer);
Long id = loadBalancer.getId();
// Save off information for the event that the security group was applied
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(accountId);
event.setType(EventTypes.EVENT_LOAD_BALANCER_CREATE);
if (id == null) {
event.setDescription("Failed to create load balancer " + loadBalancer.getName() + " on ip address " + ipAddress + "[" + publicPort + "->" + privatePort + "]");
event.setLevel(EventVO.LEVEL_ERROR);
} else {
event.setDescription("Successfully created load balancer " + loadBalancer.getName() + " on ip address " + ipAddress + "[" + publicPort + "->" + privatePort + "]");
String params = "id="+loadBalancer.getId()+"\ndcId="+addr.getDataCenterId();
event.setParameters(params);
event.setLevel(EventVO.LEVEL_INFO);
}
_eventDao.persist(event);
return _loadBalancerDao.findById(id);
} finally {
if (locked) {
_publicIpAddressDao.release(ipAddress);
}
}
}
/*
@Override @DB
public long assignToLoadBalancerAsync(long userId, long loadBalancerId, List<Long> instanceIds, Map<String, String> params) {
@ -8147,15 +8070,6 @@ public class ManagementServerImpl implements ManagementServer {
return groupVO;
}
@Override
public boolean isNetworkSecurityGroupNameInUse(Long domainId, Long accountId, String name) {
if (domainId == null) {
domainId = DomainVO.ROOT_DOMAIN;
}
_networkGroupMgr.createDefaultNetworkGroup(accountId);
return _networkSecurityGroupDao.isNameInUse(accountId, domainId, name);
}
@Override
public List<IngressRuleVO> authorizeNetworkGroupIngress(AccountVO account, String groupName, String protocol, int startPort, int endPort, String [] cidrList, List<NetworkGroupVO> authorizedGroups) {
return _networkGroupMgr.authorizeNetworkGroupIngress(account, groupName, protocol, startPort, endPort, cidrList, authorizedGroups);
@ -8203,11 +8117,6 @@ public class ManagementServerImpl implements ManagementServer {
return _asyncMgr.submitAsyncJob(job);
}
@Override
public NetworkGroupVO createNetworkGroup(String name, String description, Long domainId, Long accountId, String accountName) {
return _networkGroupMgr.createNetworkGroup(name, description, domainId, accountId, accountName);
}
@Override
public void deleteNetworkGroup(Long groupId, Long accountId) throws ResourceInUseException, PermissionDeniedException {
_networkGroupMgr.deleteNetworkGroup(groupId, accountId);

View File

@ -24,6 +24,7 @@ import java.util.Map;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command;
import com.cloud.api.commands.UpdateStoragePoolCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.exception.InternalErrorException;
@ -260,7 +261,7 @@ public interface StorageManager extends Manager {
* @param poolId ID of the storage pool to be updated
* @param tags Tags that will be added to the storage pool
*/
StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException;
// StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException;
/**
* Find all of the storage pools needed for this vm.
@ -288,4 +289,6 @@ public interface StorageManager extends Manager {
* @return
*/
public boolean cancelPrimaryStorageForMaintenance(long primaryStorageId, long userId);
public StoragePoolVO updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException;
}

View File

@ -59,6 +59,7 @@ import com.cloud.agent.api.to.VolumeTO;
import com.cloud.agent.manager.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.commands.UpdateStoragePoolCmd;
import com.cloud.async.AsyncInstanceCreateStatus;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
@ -1306,14 +1307,19 @@ public class StorageManagerImpl implements StorageManager {
}
@Override
public StoragePoolVO updateStoragePool(long poolId, String tags) throws IllegalArgumentException {
StoragePoolVO pool = _storagePoolDao.findById(poolId);
public StoragePoolVO updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException
{
//Input validation
Long id = cmd.getId();
String tags = cmd.getTags();
StoragePoolVO pool = _storagePoolDao.findById(id);
if (pool == null) {
throw new IllegalArgumentException("Unable to find storage pool with ID: " + poolId);
throw new IllegalArgumentException("Unable to find storage pool with ID: " + id);
}
if (tags != null) {
Map<String, String> details = _storagePoolDao.getDetails(poolId);
Map<String, String> details = _storagePoolDao.getDetails(id);
String[] tagsList = tags.split(",");
for (String tag : tagsList) {
tag = tag.trim();
@ -1322,7 +1328,7 @@ public class StorageManagerImpl implements StorageManager {
}
}
_storagePoolDao.updateDetails(poolId, details);
_storagePoolDao.updateDetails(id, details);
}
return pool;

View File

@ -18,11 +18,15 @@
package com.cloud.user;
import java.util.List;
import com.cloud.api.commands.UpdateResourceLimitCmd;
import com.cloud.configuration.ResourceCount;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.domain.DomainVO;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.server.Criteria;
import com.cloud.utils.component.Manager;
/**
@ -98,6 +102,10 @@ public interface AccountManager extends Manager {
* @return
* @throws InvalidParameterValueException
*/
public ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException;
// public ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException;
List<ResourceLimitVO> searchForLimits(Criteria c);
ResourceLimitVO updateResourceLimit(UpdateResourceLimitCmd cmd) throws InvalidParameterValueException;
}

View File

@ -18,6 +18,7 @@
package com.cloud.user;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -26,6 +27,9 @@ import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.UpdateResourceLimitCmd;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.dao.ResourceCountDao;
@ -33,12 +37,15 @@ import com.cloud.configuration.dao.ResourceLimitDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.server.Criteria;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
@Local(value={AccountManager.class})
@ -252,9 +259,200 @@ public class AccountManagerImpl implements AccountManager {
public long getResourceCount(AccountVO account, ResourceType type) {
return _resourceCountDao.getAccountCount(account.getId(), type);
}
@Override
public List<ResourceLimitVO> searchForLimits(Criteria c) {
Long domainId = (Long) c.getCriteria(Criteria.DOMAINID);
Long accountId = (Long) c.getCriteria(Criteria.ACCOUNTID);
ResourceType type = (ResourceType) c.getCriteria(Criteria.TYPE);
// For 2.0, we are just limiting the scope to having an user retrieve
// limits for himself and if limits don't exist, use the ROOT domain's limits.
// - Will
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
if(accountId!=null && domainId!=null)
{
//if domainId==1 and account belongs to admin
//return all records for resource limits (bug 3778)
if(domainId==1)
{
AccountVO account = _accountDao.findById(accountId);
if(account!=null && account.getType()==1)
{
//account belongs to admin
//return all limits
limits = _resourceLimitDao.listAll();
return limits;
}
}
//if account belongs to system, accountid=1,domainid=1
//return all the records for resource limits (bug:3778)
if(accountId==1 && domainId==1)
{
limits = _resourceLimitDao.listAll();
return limits;
}
}
if (accountId != null) {
SearchBuilder<ResourceLimitVO> sb = _resourceLimitDao.createSearchBuilder();
sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
SearchCriteria<ResourceLimitVO> sc = sb.create();
if (accountId != null) {
sc.setParameters("accountId", accountId);
}
if (type != null) {
sc.setParameters("type", type);
}
// Listing all limits for an account
if (type == null) {
//List<ResourceLimitVO> userLimits = _resourceLimitDao.search(sc, searchFilter);
List<ResourceLimitVO> userLimits = _resourceLimitDao.listByAccountId(accountId);
List<ResourceLimitVO> rootLimits = _resourceLimitDao.listByDomainId(DomainVO.ROOT_DOMAIN);
ResourceType resourceTypes[] = ResourceType.values();
for (ResourceType resourceType: resourceTypes) {
boolean found = false;
for (ResourceLimitVO userLimit : userLimits) {
if (userLimit.getType() == resourceType) {
limits.add(userLimit);
found = true;
break;
}
}
if (!found) {
// Check the ROOT domain
for (ResourceLimitVO rootLimit : rootLimits) {
if (rootLimit.getType() == resourceType) {
limits.add(rootLimit);
found = true;
break;
}
}
}
if (!found) {
limits.add(new ResourceLimitVO(domainId, accountId, resourceType, -1L));
}
}
} else {
AccountVO account = _accountDao.findById(accountId);
limits.add(new ResourceLimitVO(null, accountId, type, findCorrectResourceLimit(account, type)));
}
} else if (domainId != null) {
if (type == null) {
ResourceType resourceTypes[] = ResourceType.values();
List<ResourceLimitVO> domainLimits = _resourceLimitDao.listByDomainId(domainId);
for (ResourceType resourceType: resourceTypes) {
boolean found = false;
for (ResourceLimitVO domainLimit : domainLimits) {
if (domainLimit.getType() == resourceType) {
limits.add(domainLimit);
found = true;
break;
}
}
if (!found) {
limits.add(new ResourceLimitVO(domainId, null, resourceType, -1L));
}
}
} else {
limits.add(_resourceLimitDao.findByDomainIdAndType(domainId, type));
}
}
return limits;
}
@Override
public ResourceLimitVO updateResourceLimit(Long domainId, Long accountId, ResourceType type, Long max) throws InvalidParameterValueException {
public ResourceLimitVO updateResourceLimit(UpdateResourceLimitCmd cmd) throws InvalidParameterValueException {
Account account = (Account)UserContext.current().getAccountObject();
Long userId = UserContext.current().getUserId();
Long domainId = cmd.getDomainId();
Long max = cmd.getMax();
Integer type = cmd.getResourceType();
//Validate input
Long accountId = null;
if (max == null) {
max = new Long(-1);
} else if (max < -1) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify either '-1' for an infinite limit, or a limit that is at least '0'.");
}
// Map resource type
ResourceType resourceType;
try {
resourceType = ResourceType.values()[type];
} catch (ArrayIndexOutOfBoundsException e) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid resource type.");
}
/*
if (accountName==null && domainId != null && !domainId.equals(DomainVO.ROOT_DOMAIN)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Resource limits must be made for an account or the ROOT domain.");
}
*/
if (account != null) {
if (domainId != null) {
if (!_domainDao.isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((account.getAccountName() == null) ? "" : "account " + account.getAccountName() + " in ") + "domain " + domainId + ", permission denied");
}
} else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
domainId = DomainVO.ROOT_DOMAIN; // for root admin, default to root domain if domain is not specified
}
if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
if ((domainId != null) && (account.getAccountName() == null) && domainId.equals(account.getDomainId())) {
// if the admin is trying to update their own domain, disallow...
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to update resource limit for " + ((account.getAccountName() == null) ? "" : "account " + account.getAccountName() + " in ") + "domain " + domainId + ", permission denied");
}
// If there is an existing ROOT domain limit, make sure its max isn't being exceeded
Criteria c = new Criteria();
c.addCriteria(Criteria.DOMAINID, DomainVO.ROOT_DOMAIN);
c.addCriteria(Criteria.TYPE, resourceType);
List<ResourceLimitVO> currentRootDomainLimits = searchForLimits(c);
ResourceLimitVO currentRootDomainLimit = (currentRootDomainLimits.size() == 0) ? null : currentRootDomainLimits.get(0);
if (currentRootDomainLimit != null) {
long currentRootDomainMax = currentRootDomainLimits.get(0).getMax();
if ((max == -1 && currentRootDomainMax != -1) || max > currentRootDomainMax) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "The current ROOT domain limit for resource type " + resourceType + " is " + currentRootDomainMax + " and cannot be exceeded.");
}
}
}
} else if (domainId == null) {
domainId = DomainVO.ROOT_DOMAIN; // for system commands, default to root domain if domain is not specified
}
if (domainId == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to update resource limit, unable to determine domain in which to update limit.");
} else if (account.getAccountName() != null) {
if (domainId == null) {
domainId = DomainVO.ROOT_DOMAIN;
}
Account userAccount = _accountDao.findActiveAccount(account.getAccountName(), domainId);
if (userAccount == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find account by name " + account.getAccountName() + " in domain with id " + domainId);
}
accountId = userAccount.getId();
domainId = userAccount.getDomainId();
}
if (accountId != null) domainId = null;
// Either a domainId or an accountId must be passed in, but not both.
if ((domainId == null) && (accountId == null)) {
throw new InvalidParameterValueException("Either a domainId or domainId/accountId must be passed in.");
@ -262,17 +460,17 @@ public class AccountManagerImpl implements AccountManager {
// Check if the domain or account exists and is valid
if (accountId != null) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
AccountVO accountHandle = _accountDao.findById(accountId);
if (accountHandle == null) {
throw new InvalidParameterValueException("Please specify a valid account ID.");
} else if (account.getRemoved() != null) {
} else if (accountHandle.getRemoved() != null) {
throw new InvalidParameterValueException("Please specify an active account.");
} else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN || account.getType() == Account.ACCOUNT_ID_SYSTEM) {
} else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN || accountHandle.getType() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException("Please specify a non-admin account.");
}
DomainVO domain = _domainDao.findById(account.getDomainId());
long parentMaximum = findCorrectResourceLimit(domain, type);
long parentMaximum = findCorrectResourceLimit(domain, resourceType);
if ((parentMaximum >= 0) && ((max.longValue() == -1) || (max.longValue() > parentMaximum))) {
throw new InvalidParameterValueException("Account " + account.getAccountName() + "(id: " + accountId + ") has maximum allowed resource limit " + parentMaximum +
" for " + type + ", please specify a value less that or equal to " + parentMaximum);
@ -288,7 +486,7 @@ public class AccountManagerImpl implements AccountManager {
Long parentDomainId = domain.getParent();
if (parentDomainId != null) {
DomainVO parentDomain = _domainDao.findById(parentDomainId);
long parentMaximum = findCorrectResourceLimit(parentDomain, type);
long parentMaximum = findCorrectResourceLimit(parentDomain, resourceType);
if ((parentMaximum >= 0) && (max.longValue() > parentMaximum)) {
throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + domainId + ") has maximum allowed resource limit " + parentMaximum +
" for " + type + ", please specify a value less that or equal to " + parentMaximum);
@ -325,8 +523,7 @@ public class AccountManagerImpl implements AccountManager {
return _resourceLimitDao.findById(limit.getId());
} else {
// Persist the new Limit
return _resourceLimitDao.persist(new ResourceLimitVO(domainId, accountId, type, max));
return _resourceLimitDao.persist(new ResourceLimitVO(domainId, accountId, resourceType, max));
}
}
}

View File

@ -22,6 +22,7 @@ import java.util.List;
import com.cloud.agent.api.VmStatsEntry;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.UpdateVMCmd;
import com.cloud.api.commands.UpgradeVMCmd;
import com.cloud.async.executor.DestroyVMExecutor;
import com.cloud.async.executor.OperationResponse;
@ -222,4 +223,6 @@ public interface UserVmManager extends Manager, VirtualMachineManager<UserVmVO>
*/
void releaseGuestIpAddress(UserVmVO userVm);
void updateVirtualMachine(UpdateVMCmd cmd);
}

View File

@ -66,6 +66,7 @@ import com.cloud.agent.manager.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.UpdateVMCmd;
import com.cloud.api.commands.UpgradeVMCmd;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
@ -1093,6 +1094,9 @@ public class UserVmManagerImpl implements UserVmManager {
}
@Override
/*
* TODO: cleanup eventually - Refactored API call
*/
public boolean upgradeVirtualMachine(UpgradeVMCmd cmd) throws ServerApiException, InvalidParameterValueException
{
Long virtualMachineId = cmd.getId();
@ -1107,22 +1111,7 @@ public class UserVmManagerImpl implements UserVmManager {
throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR, "unable to find a virtual machine with id " + virtualMachineId);
}
if (account != null)
{
if (!isAdmin(account.getType()) && (account.getId().longValue() != vmInstance.getAccountId()))
{
throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR, "unable to find a virtual machine with id " + virtualMachineId + " for this account");
}
else if (_domainDao.isChildDomain(account.getDomainId(),vmInstance.getDomainId()))
{
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid virtual machine id (" + virtualMachineId + ") given, unable to upgrade virtual machine.");
}
}
// If command is executed via 8096 port, set userId to the id of System account (1)
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
userId = accountAndUserValidation(virtualMachineId, account, userId,vmInstance);
// Check that the specified service offering ID is valid
ServiceOfferingVO newServiceOffering = _offeringDao.findById(serviceOfferingId);
@ -1182,6 +1171,27 @@ public class UserVmManagerImpl implements UserVmManager {
}
private Long accountAndUserValidation(Long virtualMachineId,Account account, Long userId, UserVmVO vmInstance) throws ServerApiException
{
if (account != null)
{
if (!isAdmin(account.getType()) && (account.getId().longValue() != vmInstance.getAccountId()))
{
throw new ServerApiException(BaseCmd.VM_INVALID_PARAM_ERROR, "unable to find a virtual machine with id " + virtualMachineId + " for this account");
}
else if (_domainDao.isChildDomain(account.getDomainId(),vmInstance.getDomainId()))
{
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid virtual machine id (" + virtualMachineId + ") given, unable to upgrade virtual machine.");
}
}
// If command is executed via 8096 port, set userId to the id of System account (1)
if (userId == null) {
userId = Long.valueOf(User.UID_SYSTEM);
}
return userId;
}
@Override
public HashMap<Long, VmStatsEntry> getVirtualMachineStatistics(long hostId, String hostName, List<Long> vmIds) throws InternalErrorException {
HashMap<Long, VmStatsEntry> vmStatsById = new HashMap<Long, VmStatsEntry>();
@ -3041,4 +3051,74 @@ public class UserVmManagerImpl implements UserVmManager {
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
@Override
public void updateVirtualMachine(UpdateVMCmd cmd)
{
String displayName = cmd.getDisplayName();
String group = cmd.getGroup();
Boolean ha = cmd.getHaEnable();
Long id = cmd.getId();
Account account = (Account)UserContext.current().getAccountObject();
Long userId = UserContext.current().getUserId();
//Input validation
UserVmVO vmInstance = null;
// Verify input parameters
try
{
vmInstance = _userVmDao.findById(id.longValue());
}
catch (Exception ex1)
{
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "unable to find virtual machine by id");
}
if (vmInstance == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find virtual machine with id " + id);
}
userId = accountAndUserValidation(id, account, userId,vmInstance);
if (group == null) {
group = vmInstance.getGroup();
}
if (displayName == null) {
displayName = vmInstance.getDisplayName();
}
if (ha == null) {
ha = vmInstance.isHaEnabled();
}
long accountId = vmInstance.getAccountId();
UserVmVO vm = _userVmDao.findById(id);
if (vm == null) {
throw new CloudRuntimeException("Unable to find virual machine with id " + id);
}
boolean haEnabled = vm.isHaEnabled();
_userVmDao.updateVM(id, displayName, group, ha);
if (haEnabled != ha) {
String description = null;
String type = null;
if (ha)
{
description = "Successfully enabled HA for virtual machine " + vm.getName();
type = EventTypes.EVENT_VM_ENABLE_HA;
}
else
{
description = "Successfully disabled HA for virtual machine " + vm.getName();
type = EventTypes.EVENT_VM_DISABLE_HA;
}
// create a event for the change in HA Enabled flag
EventUtils.saveEvent(userId, accountId, EventVO.LEVEL_INFO, type, description, null);
}
}
}