Refactored copyIso/copyTemplate/attachIso/startRouter/stopRouter/rebootRouter commands

This commit is contained in:
alena 2010-09-07 18:53:04 -07:00
parent 176921bb5c
commit 41000e61d3
13 changed files with 672 additions and 507 deletions

View File

@ -25,7 +25,7 @@ import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
@Implementation(method="attachISOToVM", manager=Manager.ManagementServer)
@Implementation(method="attachIso", manager=Manager.TemplateManager)
public class AttachIsoCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(AttachIsoCmd.class.getName());
@ -63,6 +63,12 @@ public class AttachIsoCmd extends BaseCmd {
public String getName() {
return s_name;
}
@Override
public String getResponse() {
// TODO Add the response object as per executor
return null;
}
/*
@Override

View File

@ -20,15 +20,13 @@ package com.cloud.api.commands;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseAsyncCmd;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.async.executor.CopyTemplateResultObject;
import com.cloud.serializer.SerializerHelper;
@Implementation(method="copyTemplate", manager=Manager.ManagementServer)
public class CopyIsoCmd extends BaseCmd {
@Implementation(method="copyIso", manager=Manager.TemplateManager)
public class CopyIsoCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(CopyIsoCmd.class.getName());
private static final String s_name = "copyisoresponse";
@ -138,12 +136,19 @@ public class CopyIsoCmd extends BaseCmd {
}
*/
protected long getInstanceIdFromJobSuccessResult(String result) {
CopyTemplateResultObject resultObject = (CopyTemplateResultObject)SerializerHelper.fromSerializedString(result);
if (resultObject != null) {
return resultObject.getId();
}
return 0;
// protected long getInstanceIdFromJobSuccessResult(String result) {
// CopyTemplateResultObject resultObject = (CopyTemplateResultObject)SerializerHelper.fromSerializedString(result);
// if (resultObject != null) {
// return resultObject.getId();
// }
//
// return 0;
// }
@Override
public String getResponse() {
// TODO Add the response object as per executor
return null;
}
}

View File

@ -18,34 +18,17 @@
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.BaseAsyncCmd;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.async.executor.CopyTemplateResultObject;
import com.cloud.serializer.SerializerHelper;
import com.cloud.storage.Storage;
import com.cloud.storage.VMTemplateVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
public class CopyTemplateCmd extends BaseCmd {
@Implementation(method="copyTemplate", manager=Manager.TemplateManager)
public class CopyTemplateCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName());
private static final String s_name = "copytemplateresponse";
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.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.SOURCE_ZONE_ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DEST_ZONE_ID, Boolean.TRUE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -91,79 +74,80 @@ public class CopyTemplateCmd extends BaseCmd {
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 templateId = (Long)params.get(BaseCmd.Properties.ID.getName());
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long sourceZoneId = (Long)params.get(BaseCmd.Properties.SOURCE_ZONE_ID.getName());
Long destZoneId = (Long)params.get(BaseCmd.Properties.DEST_ZONE_ID.getName());
if (userId == null) {
userId = Long.valueOf(1);
}
VMTemplateVO template1 = getManagementServer().findTemplateById(templateId.longValue());
if (template1 == null) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find template with id " + templateId);
}
boolean isIso = Storage.ImageFormat.ISO.equals(template1.getFormat());
if (isIso) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid template.");
}
if (account != null) {
if (!isAdmin(account.getType())) {
if (template1.getAccountId() != account.getId()) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to copy template with id " + templateId);
}
} else {
Account templateOwner = getManagementServer().findAccountById(template1.getAccountId());
if ((templateOwner != null) && !getManagementServer().isChildDomain(account.getDomainId(), templateOwner.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to copy template with id " + templateId + " to zone " + destZoneId);
}
}
}
try {
long jobId = getManagementServer().copyTemplateAsync(userId, templateId, sourceZoneId, destZoneId);
if (jobId == 0) {
s_logger.warn("Unable to schedule async-job for CopyTemplate command");
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug("CopyTemplate command has been accepted, job id: " + jobId);
}
}
templateId = waitInstanceCreation(jobId);
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TEMPLATE_ID.getName(), Long.valueOf(templateId)));
return returnValues;
} catch (Exception ex) {
if (ex instanceof ServerApiException) {
throw (ServerApiException)ex;
}
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template: " + ex.getMessage());
}
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long templateId = (Long)params.get(BaseCmd.Properties.ID.getName());
// Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
// Long sourceZoneId = (Long)params.get(BaseCmd.Properties.SOURCE_ZONE_ID.getName());
// Long destZoneId = (Long)params.get(BaseCmd.Properties.DEST_ZONE_ID.getName());
//
// if (userId == null) {
// userId = Long.valueOf(1);
// }
//
// VMTemplateVO template1 = getManagementServer().findTemplateById(templateId.longValue());
// if (template1 == null) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "unable to find template with id " + templateId);
// }
//
// boolean isIso = Storage.ImageFormat.ISO.equals(template1.getFormat());
// if (isIso) {
// throw new ServerApiException(BaseCmd.PARAM_ERROR, "Please specify a valid template.");
// }
//
// if (account != null) {
// if (!isAdmin(account.getType())) {
// if (template1.getAccountId() != account.getId()) {
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "unable to copy template with id " + templateId);
// }
// } else {
// Account templateOwner = getManagementServer().findAccountById(template1.getAccountId());
// if ((templateOwner != null) && !getManagementServer().isChildDomain(account.getDomainId(), templateOwner.getDomainId())) {
// throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to copy template with id " + templateId + " to zone " + destZoneId);
// }
// }
// }
//
// try {
// long jobId = getManagementServer().copyTemplateAsync(userId, templateId, sourceZoneId, destZoneId);
//
// if (jobId == 0) {
// s_logger.warn("Unable to schedule async-job for CopyTemplate command");
// } else {
// if (s_logger.isDebugEnabled()) {
// s_logger.debug("CopyTemplate command has been accepted, job id: " + jobId);
// }
// }
//
// templateId = waitInstanceCreation(jobId);
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.TEMPLATE_ID.getName(), Long.valueOf(templateId)));
//
// return returnValues;
// } catch (Exception ex) {
// if (ex instanceof ServerApiException) {
// throw (ServerApiException)ex;
// }
// throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template: " + ex.getMessage());
// }
//
// }
//
// protected long getInstanceIdFromJobSuccessResult(String result) {
// CopyTemplateResultObject resultObject = (CopyTemplateResultObject)SerializerHelper.fromSerializedString(result);
// if (resultObject != null) {
// return resultObject.getId();
// }
//
// return 0;
// }
protected long getInstanceIdFromJobSuccessResult(String result) {
CopyTemplateResultObject resultObject = (CopyTemplateResultObject)SerializerHelper.fromSerializedString(result);
if (resultObject != null) {
return resultObject.getId();
}
return 0;
@Override
public String getResponse() {
// TODO Add the response object as per executor
return null;
}
}

View File

@ -18,29 +18,17 @@
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.BaseAsyncCmd;
import com.cloud.api.BaseCmd.Manager;
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.vm.DomainRouterVO;
public class RebootRouterCmd extends BaseCmd {
@Implementation(method="rebootRouter", manager=Manager.NetworkManager)
public class RebootRouterCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName());
private static final String s_name = "rebootrouterresponse";
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.ACCOUNT_OBJ, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -64,36 +52,38 @@ public class RebootRouterCmd 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 routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
//verify parameters
DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
if (router == null) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
}
if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to reboot router.");
}
long jobId = getManagementServer().rebootRouterAsync(routerId.longValue());
if (jobId == 0) {
s_logger.warn("Unable to schedule async-job for RebootRouter comamnd");
} else {
if (s_logger.isDebugEnabled())
s_logger.debug("RebootRouter command has been accepted, job id: " + jobId);
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
//
// //verify parameters
// DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
// if (router == null) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
// }
//
// if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to reboot router.");
// }
//
// long jobId = getManagementServer().rebootRouterAsync(routerId.longValue());
// if (jobId == 0) {
// s_logger.warn("Unable to schedule async-job for RebootRouter comamnd");
// } else {
// if (s_logger.isDebugEnabled())
// s_logger.debug("RebootRouter command has been accepted, job id: " + jobId);
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
// return returnValues;
// }
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -18,29 +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.BaseAsyncCmd;
import com.cloud.api.BaseCmd.Manager;
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.vm.DomainRouterVO;
public class StartRouterCmd extends BaseCmd {
@Implementation(method="startRouter", manager=Manager.NetworkManager)
public class StartRouterCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName());
private static final String s_name = "startrouterresponse";
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.ACCOUNT_OBJ, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -68,34 +58,36 @@ public class StartRouterCmd extends BaseCmd {
public static String getResultObjectName() {
return "router";
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
//verify parameters
DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
if (router == null) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
}
if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to start router.");
}
long jobId = getManagementServer().startRouterAsync(routerId.longValue());
if (jobId == 0) {
s_logger.warn("Unable to schedule async-job for StartRouter comamnd");
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("StartRouter command has been accepted, job id: " + jobId);
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
return returnValues;
}
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
//
// //verify parameters
// DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
// if (router == null) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
// }
// if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to start router.");
// }
//
// long jobId = getManagementServer().startRouterAsync(routerId.longValue());
// if (jobId == 0) {
// s_logger.warn("Unable to schedule async-job for StartRouter comamnd");
// } else {
// if(s_logger.isDebugEnabled())
// s_logger.debug("StartRouter command has been accepted, job id: " + jobId);
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
// return returnValues;
// }
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -18,29 +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.BaseAsyncCmd;
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.vm.DomainRouterVO;
public class StopRouterCmd extends BaseCmd {
import com.cloud.api.BaseCmd.Manager;
@Implementation(method="stopRouter", manager=Manager.NetworkManager)
public class StopRouterCmd extends BaseAsyncCmd {
public static final Logger s_logger = Logger.getLogger(StopRouterCmd.class.getName());
private static final String s_name = "stoprouterresponse";
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.ACCOUNT_OBJ, Boolean.FALSE));
}
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
@ -63,37 +52,39 @@ public class StopRouterCmd 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 routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
// verify parameters
DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
if (router == null) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
}
if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to stop router.");
}
long jobId = getManagementServer().stopRouterAsync(routerId.longValue());
if(jobId == 0) {
s_logger.warn("Unable to schedule async-job for StopRouter comamnd");
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("StopRouter command has been accepted, job id: " + jobId);
}
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
return returnValues;
}
// @Override
// public List<Pair<String, Object>> execute(Map<String, Object> params) {
// Long routerId = (Long)params.get(BaseCmd.Properties.ID.getName());
// Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
//
// // verify parameters
// DomainRouterVO router = getManagementServer().findDomainRouterById(routerId);
// if (router == null) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "unable to find a domain router with id " + routerId);
// }
//
// if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), router.getDomainId())) {
// throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to stop router.");
// }
//
// long jobId = getManagementServer().stopRouterAsync(routerId.longValue());
// if(jobId == 0) {
// s_logger.warn("Unable to schedule async-job for StopRouter comamnd");
// } else {
// if(s_logger.isDebugEnabled())
// s_logger.debug("StopRouter command has been accepted, job id: " + jobId);
// }
//
// List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
// returnValues.add(new Pair<String, Object>(BaseCmd.Properties.JOB_ID.getName(), Long.valueOf(jobId)));
// return returnValues;
// }
@Override
public String getResponse() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -27,7 +27,10 @@ import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.DeletePortForwardingServiceRuleCmd;
import com.cloud.api.commands.DisassociateIPAddrCmd;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.api.commands.RebootRouterCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.StartRouterCmd;
import com.cloud.api.commands.StopRouterCmd;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
@ -107,15 +110,21 @@ public interface NetworkManager extends Manager {
DomainRouterVO startRouter(long routerId, long eventId);
DomainRouterVO startRouter(StartRouterCmd cmd) throws InvalidParameterValueException;
boolean releaseRouter(long routerId);
boolean destroyRouter(long routerId);
boolean stopRouter(long routerId, long eventId);
boolean stopRouter(StopRouterCmd cmd) throws InvalidParameterValueException;
boolean getRouterStatistics(long vmId, Map<String, long[]> netStats, Map<String, long[]> diskStats);
boolean rebootRouter(long routerId, long eventId);
boolean rebootRouter(RebootRouterCmd cmd) throws InvalidParameterValueException;
/**
* @param hostId get all of the virtual machine routers on a host.
* @return collection of VirtualMachineRouter

View File

@ -65,11 +65,15 @@ import com.cloud.api.commands.CreateLoadBalancerRuleCmd;
import com.cloud.api.commands.DeletePortForwardingServiceRuleCmd;
import com.cloud.api.commands.DisassociateIPAddrCmd;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.api.commands.RebootRouterCmd;
import com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;
import com.cloud.api.commands.StartRouterCmd;
import com.cloud.api.commands.StopRouterCmd;
import com.cloud.async.AsyncJobExecutor;
import com.cloud.async.AsyncJobManager;
import com.cloud.async.AsyncJobVO;
import com.cloud.async.BaseAsyncJobExecutor;
import com.cloud.async.executor.VMOperationParam;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationManager;
@ -116,6 +120,7 @@ import com.cloud.network.dao.NetworkRuleConfigDao;
import com.cloud.network.dao.SecurityGroupDao;
import com.cloud.network.dao.SecurityGroupVMMapDao;
import com.cloud.offering.ServiceOffering.GuestIpType;
import com.cloud.serializer.GsonHelper;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.StorageManager;
@ -161,6 +166,7 @@ import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineName;
import com.cloud.vm.dao.DomainRouterDao;
import com.cloud.vm.dao.UserVmDao;
import com.google.gson.Gson;
/**
* NetworkManagerImpl implements NetworkManager.
@ -792,6 +798,24 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
return null;
}
}
@Override
public DomainRouterVO startRouter(StartRouterCmd cmd) throws InvalidParameterValueException{
Long routerId = cmd.getId();
Account account = (Account)UserContext.current().getAccountObject();
//verify parameters
DomainRouterVO router = _routerDao.findById(routerId);
if (router == null) {
throw new InvalidParameterValueException ("Unable to find a domain router with id " + routerId);
}
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "Invalid domain router id (" + routerId + ") given, unable to start router.");
}
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_START, "starting Router with Id: "+routerId);
return startRouter(routerId, eventId);
}
@Override @DB
public DomainRouterVO start(long routerId, long startEventId) throws StorageUnavailableException, ConcurrentOperationException {
@ -1209,6 +1233,27 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
return stop(_routerDao.findById(routerId), eventId);
}
@Override
public boolean stopRouter(StopRouterCmd cmd) throws InvalidParameterValueException{
Long routerId = cmd.getId();
Account account = (Account)UserContext.current().getAccountObject();
// verify parameters
DomainRouterVO router = _routerDao.findById(routerId);
if (router == null) {
throw new InvalidParameterValueException ("Unable to find a domain router with id " + routerId);
}
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new InvalidParameterValueException ("Invalid domain router id (" + routerId + ") given, unable to stop router.");
}
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping Router with Id: "+routerId);
return stopRouter(routerId, eventId);
}
@DB
public void processStopOrRebootAnswer(final DomainRouterVO router, Answer answer) {
@ -1332,6 +1377,25 @@ public class NetworkManagerImpl implements NetworkManager, VirtualMachineManager
return startRouter(routerId, 0) != null;
}
}
@Override
public boolean rebootRouter(RebootRouterCmd cmd) throws InvalidParameterValueException{
Long routerId = cmd.getId();
Account account = (Account)UserContext.current().getAccountObject();
//verify parameters
DomainRouterVO router = _routerDao.findById(routerId);
if (router == null) {
throw new InvalidParameterValueException("Unable to find a domain router with id " + routerId);
}
if ((account != null) && !_domainDao.isChildDomain(account.getDomainId(), router.getDomainId())) {
throw new InvalidParameterValueException("Invalid domain router id (" + routerId + ") given, unable to reboot router.");
}
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_REBOOT, "rebooting Router with Id: "+routerId);
return rebootRouter(routerId, eventId);
}
@Override
public boolean associateIP(final DomainRouterVO router, final List<String> ipAddrList, final boolean add) {

View File

@ -619,7 +619,7 @@ public interface ManagementServer {
* @return
*/
boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach, long startEventId);
long attachISOToVMAsync(long vmId, long userId, long isoId) throws InvalidParameterValueException;
// long attachISOToVMAsync(long vmId, long userId, long isoId) throws InvalidParameterValueException;
// long detachISOFromVMAsync(long vmId, long userId) throws InvalidParameterValueException;
/**
@ -658,7 +658,7 @@ public interface ManagementServer {
* @throws ConcurrentOperationException
*/
//UserVm startVirtualMachine(long userId, long vmId, String isoPath) throws InternalErrorException, ExecutionException, StorageUnavailableException, ConcurrentOperationException;
long startVirtualMachineAsync(long userId, long vmId, String isoPath);
// long startVirtualMachineAsync(long userId, long vmId, String isoPath);
/**
* Stops a Virtual Machine
@ -668,7 +668,7 @@ public interface ManagementServer {
* @return true if successfully stopped, false otherwise
*/
//boolean stopVirtualMachine(long userId, long vmId);
long stopVirtualMachineAsync(long userId, long vmId);
// long stopVirtualMachineAsync(long userId, long vmId);
/**
* Reboots a Virtual Machine
@ -744,7 +744,7 @@ public interface ManagementServer {
* @return DomainRouter if successfully started, false otherwise
*/
DomainRouter startRouter(long routerId, long startEventId) throws InternalErrorException;
long startRouterAsync(long routerId);
// long startRouterAsync(long routerId);
/**
* Stops a Domain Router
@ -753,7 +753,7 @@ public interface ManagementServer {
* @return true if successfully stopped, false otherwise
*/
boolean stopRouter(long routerId, long startEventId);
long stopRouterAsync(long routerId);
// long stopRouterAsync(long routerId);
/**
* Reboots a Domain Router
@ -762,7 +762,7 @@ public interface ManagementServer {
* @return true if successfully rebooted, false otherwise
*/
boolean rebootRouter(long routerId, long startEventId) throws InternalErrorException;
long rebootRouterAsync(long routerId);
// long rebootRouterAsync(long routerId);
/**
* Destroys a Domain Router
@ -770,7 +770,7 @@ public interface ManagementServer {
* @param routerId
* @return true if successfully destroyed, false otherwise
*/
boolean destroyRouter(long routerId);
// boolean destroyRouter(long routerId);
/**
* Finds a domain router by user and data center
@ -1086,7 +1086,7 @@ public interface ManagementServer {
* @throws InternalErrorException
*/
boolean copyTemplate(long userId, long templateId, long sourceZoneId, long destZoneId, long startEventId) throws InternalErrorException;
long copyTemplateAsync(long userId, long templateId, long sourceZoneId, long destZoneId) throws InvalidParameterValueException;
// long copyTemplateAsync(long userId, long templateId, long sourceZoneId, long destZoneId) throws InvalidParameterValueException;
/**
* Deletes an ISO from all secondary storage servers

View File

@ -2070,45 +2070,45 @@ public class ManagementServerImpl implements ManagementServer {
EventUtils.saveEvent(userId, vm.getAccountId(), EventVO.LEVEL_ERROR, EventTypes.EVENT_ISO_DETACH, "Failed to detach ISO from VM with ID: " + vmId, null, startEventId);
}
}
return success;
}
@Override
public long attachISOToVMAsync(long vmId, long userId, long isoId) throws InvalidParameterValueException {
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find VM with ID " + vmId);
}
VMTemplateVO iso = _templateDao.findById(isoId);
if (iso == null || !iso.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Unable to find ISO with id " + isoId);
}
AccountVO account = _accountDao.findById(vm.getAccountId());
if (account == null) {
throw new InvalidParameterValueException("Unable to find account for VM with ID " + vmId);
}
State vmState = vm.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
long eventId = EventUtils.saveScheduledEvent(userId, account.getId(), EventTypes.EVENT_ISO_ATTACH, "attaching ISO: "+isoId+" to Vm: "+vmId);
AttachISOParam param = new AttachISOParam(vmId, userId, isoId, true);
param.setEventId(eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(vm.getAccountId());
job.setCmd("AttachISO");
job.setCmdInfo(gson.toJson(param));
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long attachISOToVMAsync(long vmId, long userId, long isoId) throws InvalidParameterValueException {
// UserVmVO vm = _userVmDao.findById(vmId);
// if (vm == null) {
// throw new InvalidParameterValueException("Unable to find VM with ID " + vmId);
// }
//
// VMTemplateVO iso = _templateDao.findById(isoId);
// if (iso == null || !iso.getFormat().equals(ImageFormat.ISO)) {
// throw new InvalidParameterValueException("Unable to find ISO with id " + isoId);
// }
//
// AccountVO account = _accountDao.findById(vm.getAccountId());
// if (account == null) {
// throw new InvalidParameterValueException("Unable to find account for VM with ID " + vmId);
// }
//
// State vmState = vm.getState();
// if (vmState != State.Running && vmState != State.Stopped) {
// throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
// }
//
// long eventId = EventUtils.saveScheduledEvent(userId, account.getId(), EventTypes.EVENT_ISO_ATTACH, "attaching ISO: "+isoId+" to Vm: "+vmId);
//
// AttachISOParam param = new AttachISOParam(vmId, userId, isoId, true);
// param.setEventId(eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(vm.getAccountId());
// job.setCmd("AttachISO");
// job.setCmdInfo(gson.toJson(param));
// return _asyncMgr.submitAsyncJob(job, true);
// }
// @Override
// public long detachISOFromVMAsync(long vmId, long userId) throws InvalidParameterValueException {
@ -2532,50 +2532,50 @@ public class ManagementServerImpl implements ManagementServer {
// return _vmMgr.startVirtualMachine(userId, vmId, isoPath, 0);
// }
@Override
public long startVirtualMachineAsync(long userId, long vmId, String isoPath) {
UserVmVO userVm = _userVmDao.findById(vmId);
long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_VM_START, "starting Vm with Id: "+vmId);
VMOperationParam param = new VMOperationParam(userId, vmId, isoPath, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(userVm.getAccountId());
job.setCmd("StartVM");
job.setCmdInfo(gson.toJson(param));
job.setCmdOriginator(StartVMCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long startVirtualMachineAsync(long userId, long vmId, String isoPath) {
//
// UserVmVO userVm = _userVmDao.findById(vmId);
//
// long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_VM_START, "starting Vm with Id: "+vmId);
//
// VMOperationParam param = new VMOperationParam(userId, vmId, isoPath, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(userVm.getAccountId());
// job.setCmd("StartVM");
// job.setCmdInfo(gson.toJson(param));
// job.setCmdOriginator(StartVMCmd.getResultObjectName());
// return _asyncMgr.submitAsyncJob(job, true);
// }
// @Override
// public boolean stopVirtualMachine(long userId, long vmId) {
// return _vmMgr.stopVirtualMachine(userId, vmId);
// }
@Override
public long stopVirtualMachineAsync(long userId, long vmId) {
UserVmVO userVm = _userVmDao.findById(vmId);
long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_VM_STOP, "stopping Vm with Id: "+vmId);
VMOperationParam param = new VMOperationParam(userId, userVm.getAccountId(), vmId, null, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(userVm.getAccountId());
job.setCmd("StopVM");
job.setCmdInfo(gson.toJson(param));
// use the same result result object name as StartVMCmd
job.setCmdOriginator(StartVMCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long stopVirtualMachineAsync(long userId, long vmId) {
//
// UserVmVO userVm = _userVmDao.findById(vmId);
//
// long eventId = EventUtils.saveScheduledEvent(userId, userVm.getAccountId(), EventTypes.EVENT_VM_STOP, "stopping Vm with Id: "+vmId);
//
// VMOperationParam param = new VMOperationParam(userId, userVm.getAccountId(), vmId, null, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(userVm.getAccountId());
// job.setCmd("StopVM");
// job.setCmdInfo(gson.toJson(param));
//
// // use the same result result object name as StartVMCmd
// job.setCmdOriginator(StartVMCmd.getResultObjectName());
// return _asyncMgr.submitAsyncJob(job, true);
// }
// @Override
// public boolean rebootVirtualMachine(long userId, long vmId) {
@ -2733,69 +2733,69 @@ public class ManagementServerImpl implements ManagementServer {
return _networkMgr.startRouter(routerId, startEventId);
}
@Override
public long startRouterAsync(long routerId) {
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_START, "starting Router with Id: "+routerId);
VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
job.setCmd("StartRouter");
job.setCmdInfo(gson.toJson(param));
job.setCmdOriginator(StartRouterCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long startRouterAsync(long routerId) {
// long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_START, "starting Router with Id: "+routerId);
//
// VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
// job.setCmd("StartRouter");
// job.setCmdInfo(gson.toJson(param));
// job.setCmdOriginator(StartRouterCmd.getResultObjectName());
// return _asyncMgr.submitAsyncJob(job, true);
// }
@Override
public boolean stopRouter(long routerId, long startEventId) {
return _networkMgr.stopRouter(routerId, startEventId);
}
@Override
public long stopRouterAsync(long routerId) {
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping Router with Id: "+routerId);
VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
job.setCmd("StopRouter");
job.setCmdInfo(gson.toJson(param));
// use the same result object name as StartRouterCmd
job.setCmdOriginator(StartRouterCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
// @Override
// public long stopRouterAsync(long routerId) {
// long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_STOP, "stopping Router with Id: "+routerId);
// VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
// job.setCmd("StopRouter");
// job.setCmdInfo(gson.toJson(param));
// // use the same result object name as StartRouterCmd
// job.setCmdOriginator(StartRouterCmd.getResultObjectName());
//
// return _asyncMgr.submitAsyncJob(job, true);
// }
@Override
public boolean rebootRouter(long routerId, long startEventId) throws InternalErrorException {
return _networkMgr.rebootRouter(routerId, startEventId);
}
@Override
public long rebootRouterAsync(long routerId) {
long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_REBOOT, "rebooting Router with Id: "+routerId);
VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
Gson gson = GsonHelper.getBuilder().create();
// @Override
// public long rebootRouterAsync(long routerId) {
// long eventId = EventUtils.saveScheduledEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, EventTypes.EVENT_ROUTER_REBOOT, "rebooting Router with Id: "+routerId);
// VMOperationParam param = new VMOperationParam(0, routerId, null, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
// job.setCmd("RebootRouter");
// job.setCmdInfo(gson.toJson(param));
// // use the same result object name as StartRouterCmd
// job.setCmdOriginator(StartRouterCmd.getResultObjectName());
// return _asyncMgr.submitAsyncJob(job, true);
// }
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(Account.ACCOUNT_ID_SYSTEM);
job.setCmd("RebootRouter");
job.setCmdInfo(gson.toJson(param));
// use the same result object name as StartRouterCmd
job.setCmdOriginator(StartRouterCmd.getResultObjectName());
return _asyncMgr.submitAsyncJob(job, true);
}
@Override
public boolean destroyRouter(long routerId) {
return _networkMgr.destroyRouter(routerId);
}
// @Override
// public boolean destroyRouter(long routerId) {
// return _networkMgr.destroyRouter(routerId);
// }
@Override
public DomainRouterVO findDomainRouterBy(long accountId, long dataCenterId) {
@ -4755,67 +4755,67 @@ public class ManagementServerImpl implements ManagementServer {
}
return success;
}
@Override
public long copyTemplateAsync(long userId, long templateId, long sourceZoneId, long destZoneId) throws InvalidParameterValueException {
UserVO user = _userDao.findById(userId);
if (user == null) {
throw new InvalidParameterValueException("Please specify a valid user.");
}
VMTemplateVO template = _templateDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("Please specify a valid template/ISO.");
}
if (template.getFormat().equals(ImageFormat.ISO) && template.getName().equals("xs-tools.iso")) {
throw new InvalidParameterValueException("The XenServer Tools ISO cannot be copied.");
}
DataCenterVO sourceZone = _dcDao.findById(sourceZoneId);
if (sourceZone == null) {
throw new InvalidParameterValueException("Please specify a valid source zone.");
}
DataCenterVO destZone = _dcDao.findById(destZoneId);
if (destZone == null) {
throw new InvalidParameterValueException("Please specify a valid destination zone.");
}
if (sourceZoneId == destZoneId) {
throw new InvalidParameterValueException("Please specify different source and destination zones.");
}
HostVO srcSecHost = _hostDao.findSecondaryStorageHost(sourceZoneId);
if (srcSecHost == null) {
throw new InvalidParameterValueException("Source zone is not ready");
}
if (_hostDao.findSecondaryStorageHost(destZoneId) == null) {
throw new InvalidParameterValueException("Destination zone is not ready.");
}
VMTemplateHostVO srcTmpltHost = null;
srcTmpltHost = _templateHostDao.findByHostTemplate(srcSecHost.getId(), templateId);
if (srcTmpltHost == null || srcTmpltHost.getDestroyed() || srcTmpltHost.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
throw new InvalidParameterValueException("Please specify a template that is installed on secondary storage host: " + srcSecHost.getName());
}
long eventId = EventUtils.saveScheduledEvent(userId, template.getAccountId(), EventTypes.EVENT_TEMPLATE_COPY, "copying template with Id: "+templateId+" from zone: "+sourceZoneId+" to: "+destZoneId);
CopyTemplateParam param = new CopyTemplateParam(userId, templateId, sourceZoneId, destZoneId, eventId);
Gson gson = GsonHelper.getBuilder().create();
AsyncJobVO job = new AsyncJobVO();
job.setUserId(UserContext.current().getUserId());
job.setAccountId(template.getAccountId());
job.setCmd("CopyTemplate");
job.setCmdInfo(gson.toJson(param));
job.setCmdOriginator(CopyTemplateCmd.getStaticName());
return _asyncMgr.submitAsyncJob(job);
}
//
// @Override
// public long copyTemplateAsync(long userId, long templateId, long sourceZoneId, long destZoneId) throws InvalidParameterValueException {
// UserVO user = _userDao.findById(userId);
// if (user == null) {
// throw new InvalidParameterValueException("Please specify a valid user.");
// }
//
// VMTemplateVO template = _templateDao.findById(templateId);
// if (template == null) {
// throw new InvalidParameterValueException("Please specify a valid template/ISO.");
// }
//
// if (template.getFormat().equals(ImageFormat.ISO) && template.getName().equals("xs-tools.iso")) {
// throw new InvalidParameterValueException("The XenServer Tools ISO cannot be copied.");
// }
//
// DataCenterVO sourceZone = _dcDao.findById(sourceZoneId);
// if (sourceZone == null) {
// throw new InvalidParameterValueException("Please specify a valid source zone.");
// }
//
// DataCenterVO destZone = _dcDao.findById(destZoneId);
// if (destZone == null) {
// throw new InvalidParameterValueException("Please specify a valid destination zone.");
// }
//
// if (sourceZoneId == destZoneId) {
// throw new InvalidParameterValueException("Please specify different source and destination zones.");
// }
//
// HostVO srcSecHost = _hostDao.findSecondaryStorageHost(sourceZoneId);
//
// if (srcSecHost == null) {
// throw new InvalidParameterValueException("Source zone is not ready");
// }
//
// if (_hostDao.findSecondaryStorageHost(destZoneId) == null) {
// throw new InvalidParameterValueException("Destination zone is not ready.");
// }
//
// VMTemplateHostVO srcTmpltHost = null;
// srcTmpltHost = _templateHostDao.findByHostTemplate(srcSecHost.getId(), templateId);
// if (srcTmpltHost == null || srcTmpltHost.getDestroyed() || srcTmpltHost.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
// throw new InvalidParameterValueException("Please specify a template that is installed on secondary storage host: " + srcSecHost.getName());
// }
//
// long eventId = EventUtils.saveScheduledEvent(userId, template.getAccountId(), EventTypes.EVENT_TEMPLATE_COPY, "copying template with Id: "+templateId+" from zone: "+sourceZoneId+" to: "+destZoneId);
//
// CopyTemplateParam param = new CopyTemplateParam(userId, templateId, sourceZoneId, destZoneId, eventId);
// Gson gson = GsonHelper.getBuilder().create();
//
// AsyncJobVO job = new AsyncJobVO();
// job.setUserId(UserContext.current().getUserId());
// job.setAccountId(template.getAccountId());
// job.setCmd("CopyTemplate");
// job.setCmdInfo(gson.toJson(param));
// job.setCmdOriginator(CopyTemplateCmd.getStaticName());
//
// return _asyncMgr.submitAsyncJob(job);
// }
// @Override
// public long deleteIsoAsync(long userId, long isoId, Long zoneId) throws InvalidParameterValueException {

View File

@ -21,6 +21,9 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import com.cloud.api.commands.AttachIsoCmd;
import com.cloud.api.commands.CopyIsoCmd;
import com.cloud.api.commands.CopyTemplateCmd;
import com.cloud.api.commands.DeleteIsoCmd;
import com.cloud.api.commands.DeleteTemplateCmd;
import com.cloud.api.commands.DetachIsoCmd;
@ -109,6 +112,8 @@ public interface TemplateManager extends Manager {
* @throws InvalidParameterValueException
*/
boolean copy(long userId, long templateId, long sourceZoneId, long destZoneId, long startEventId) throws InternalErrorException, StorageUnavailableException, InvalidParameterValueException;
boolean copyIso(CopyIsoCmd cmd) throws InvalidParameterValueException, StorageUnavailableException;
boolean copyTemplate(CopyTemplateCmd cmd) throws InvalidParameterValueException, StorageUnavailableException;
/**
* Deletes a template from secondary storage servers
@ -120,6 +125,9 @@ public interface TemplateManager extends Manager {
boolean delete(long userId, long templateId, Long zoneId) throws InternalErrorException;
boolean detachIso(DetachIsoCmd cmd) throws InternalErrorException, InvalidParameterValueException;
boolean attachIso(AttachIsoCmd cmd) throws InternalErrorException, InvalidParameterValueException;
/**
* Lists templates in the specified storage pool that are not being used by any VM.
* @param pool

View File

@ -38,6 +38,9 @@ import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand;
import com.cloud.agent.manager.AgentManager;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.api.commands.AttachIsoCmd;
import com.cloud.api.commands.CopyIsoCmd;
import com.cloud.api.commands.CopyTemplateCmd;
import com.cloud.api.commands.DeleteIsoCmd;
import com.cloud.api.commands.DeleteTemplateCmd;
import com.cloud.api.commands.DetachIsoCmd;
@ -60,6 +63,7 @@ import com.cloud.exception.StorageUnavailableException;
import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao;
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;
@ -67,6 +71,7 @@ import com.cloud.storage.StoragePoolHostVO;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VMTemplateHostVO;
import com.cloud.storage.VMTemplateStoragePoolVO;
import com.cloud.storage.VMTemplateStorageResourceAssoc;
import com.cloud.storage.VMTemplateStorageResourceAssoc.Status;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VMTemplateZoneVO;
@ -506,22 +511,35 @@ public class TemplateManagerImpl implements TemplateManager {
HostVO srcSecHost = _storageMgr.getSecondaryStorageHost(sourceZoneId);
HostVO dstSecHost = _storageMgr.getSecondaryStorageHost(destZoneId);
DataCenterVO destZone = _dcDao.findById(destZoneId);
DataCenterVO sourceZone = _dcDao.findById(sourceZoneId);
if (sourceZone == null) {
throw new InvalidParameterValueException("Please specify a valid source zone.");
}
DataCenterVO dstZone = _dcDao.findById(destZoneId);
if (dstZone == null) {
throw new InvalidParameterValueException("Please specify a valid destination zone.");
}
if (sourceZoneId == destZoneId) {
throw new InvalidParameterValueException("Please specify different source and destination zones.");
}
if (srcSecHost == null) {
throw new StorageUnavailableException("Source zone is not ready");
}
if (dstSecHost == null) {
throw new StorageUnavailableException("Destination zone is not ready");
}
VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
if (vmTemplate == null) {
throw new InvalidParameterValueException("Invalid or illegal template id");
}
VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
VMTemplateHostVO srcTmpltHost = null;
srcTmpltHost = _tmpltHostDao.findByHostTemplate(srcSecHost.getId(), templateId);
if (srcTmpltHost == null) {
throw new InvalidParameterValueException("Template " + vmTemplate.getName() + " not associated with " + srcSecHost.getName());
}
if (srcTmpltHost == null || srcTmpltHost.getDestroyed() || srcTmpltHost.getDownloadState() != VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
throw new InvalidParameterValueException("Please specify a template that is installed on secondary storage host: " + srcSecHost.getName());
}
EventVO event = new EventVO();
event.setUserId(userId);
event.setAccountId(vmTemplate.getAccountId());
@ -593,6 +611,61 @@ public class TemplateManagerImpl implements TemplateManager {
saveEvent(userId, account.getId(), account.getDomainId(), copyEventType, copyEventDescription, EventVO.LEVEL_INFO, params, startEventId);
return true;
}
@Override
public boolean copyIso(CopyIsoCmd cmd) throws InvalidParameterValueException, StorageUnavailableException {
Long isoId = cmd.getId();
Long userId = UserContext.current().getUserId();
Long sourceZoneId = cmd.getSourceZoneId();
Long destZoneId = cmd.getDestinationZoneId();
Account account = (Account)UserContext.current().getAccountObject();
//Verify parameters
VMTemplateVO iso = _tmpltDao.findById(isoId);
if (iso == null) {
throw new InvalidParameterValueException("Unable to find ISO with id " + isoId);
}
boolean isIso = Storage.ImageFormat.ISO.equals(iso.getFormat());
if (!isIso) {
throw new InvalidParameterValueException("Please specify a valid ISO.");
}
//Verify account information
String errMsg = "Unable to copy ISO " + isoId;
userId = accountAndUserValidation(account, userId, null, iso, errMsg);
long eventId = EventUtils.saveScheduledEvent(userId, iso.getAccountId(), EventTypes.EVENT_ISO_COPY, "copying iso with Id: " + isoId +" from zone: " + sourceZoneId +" to: " + destZoneId);
return copy(userId, isoId, sourceZoneId, destZoneId, eventId);
}
@Override
public boolean copyTemplate(CopyTemplateCmd cmd) throws InvalidParameterValueException, StorageUnavailableException {
Long templateId = cmd.getId();
Long userId = UserContext.current().getUserId();
Long sourceZoneId = cmd.getSourceZoneId();
Long destZoneId = cmd.getDestinationZoneId();
Account account = (Account)UserContext.current().getAccountObject();
//Verify parameters
VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("Unable to find template with id");
}
boolean isIso = Storage.ImageFormat.ISO.equals(template.getFormat());
if (isIso) {
throw new InvalidParameterValueException("Please specify a valid template.");
}
//Verify account information
String errMsg = "Unable to copy template " + templateId;
userId = accountAndUserValidation(account, userId, null, template, errMsg);
long eventId = EventUtils.saveScheduledEvent(userId, template.getAccountId(), EventTypes.EVENT_TEMPLATE_COPY, "copying template with Id: " + templateId+" from zone: " + sourceZoneId +" to: " + destZoneId);
return copy(userId, templateId, sourceZoneId, destZoneId, eventId);
}
@Override
public boolean delete(long userId, long templateId, Long zoneId) throws InternalErrorException {
@ -893,10 +966,6 @@ public class TemplateManagerImpl implements TemplateManager {
throw new ServerApiException (BaseCmd.VM_INVALID_PARAM_ERROR, "Unable to find a virtual machine with id " + vmId);
}
String errMsg = "Unable to detach ISO from virtual machine ";
userId = accountAndUserValidation(account, userId, vmInstanceCheck, null, errMsg);
UserVm userVM = _userVmDao.findById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Please specify a valid VM.");
@ -912,9 +981,41 @@ public class TemplateManagerImpl implements TemplateManager {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
String errMsg = "Unable to detach ISO " + isoId + " from virtual machine";
userId = accountAndUserValidation(account, userId, vmInstanceCheck, null, errMsg);
return attachISOToVM(vmId, userId, isoId, false); //attach=false => detach
}
@Override
public boolean attachIso(AttachIsoCmd cmd) throws InternalErrorException, InvalidParameterValueException {
Account account = (Account) UserContext.current().getAccountObject();
Long userId = UserContext.current().getUserId();
Long vmId = cmd.getVirtualMachineId();
Long isoId = cmd.getId();
// Verify input parameters
UserVmVO vmInstanceCheck = _userVmDao.findById(vmId);
if (vmInstanceCheck == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
VMTemplateVO iso = _tmpltDao.findById(isoId);
if (iso == null) {
throw new ServerApiException (BaseCmd.PARAM_ERROR, "Unable to find an ISO with id " + isoId);
}
State vmState = vmInstanceCheck.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
String errMsg = "Unable to attach ISO" + isoId + "to virtual machine " + vmId;
userId = accountAndUserValidation(account, userId, vmInstanceCheck, iso, errMsg);
return attachISOToVM(vmId, userId, isoId, true);
}
private boolean attachISOToVM(long vmId, long userId, long isoId, boolean attach) {
UserVmVO vm = _userVmDao.findById(vmId);
@ -953,16 +1054,31 @@ public class TemplateManagerImpl implements TemplateManager {
}
private Long accountAndUserValidation(Account account, Long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg) {
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId().longValue() != vmInstanceCheck.getAccountId()) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + vmInstanceCheck!=null ? vmInstanceCheck.getName():template.getName() + " for this account");
}
} else if (!_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + vmInstanceCheck!=null ? vmInstanceCheck.getName():template.getName() + ", permission denied.");
}
}
if (account != null) {
if (!isAdmin(account.getType())) {
if ((vmInstanceCheck != null) && (account.getId().longValue() != vmInstanceCheck.getAccountId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + ". Permission denied.");
}
if ((template != null) && (!template.isPublicTemplate() && (account.getId().longValue() != template.getAccountId()) && (!template.getName().startsWith("xs-tools")))) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + ". Permission denied.");
}
} else {
if ((vmInstanceCheck != null) && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + ". Permission denied.");
}
// FIXME: if template/ISO owner is null we probably need to throw some kind of exception
if (template != null) {
Account templateOwner = _accountDao.findById(template.getId());
if ((templateOwner != null) && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, msg + ". Permission denied.");
}
}
}
}
// If command is executed via 8096 port, set userId to the id of System account (1)
if (userId == null)
userId = new Long(1);

View File

@ -1210,52 +1210,52 @@ public class UserVmManagerImpl implements UserVmManager {
throw new InvalidParameterValueException("Unable to find a service offering with id " + serviceOfferingId);
}
// Check that the VM is stopped
if (!vmInstance.getState().equals(State.Stopped)) {
s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before upgrading.");
// Check that the VM is stopped
if (!vmInstance.getState().equals(State.Stopped)) {
s_logger.warn("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before upgrading.");
}
// Check if the service offering being upgraded to is what the VM is already running with
if (vmInstance.getServiceOfferingId() == newServiceOffering.getId()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")");
}
// Check if the service offering being upgraded to is what the VM is already running with
if (vmInstance.getServiceOfferingId() == newServiceOffering.getId()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")");
}
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")");
}
// Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering
ServiceOfferingVO currentServiceOffering = _offeringDao.findById(vmInstance.getServiceOfferingId());
if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) {
String errorMsg = "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType();
errorMsg += ". Please select a service offering with the same guest IP type as the VM's current service offering (" + currentServiceOffering.getGuestIpType() + ").";
throw new InvalidParameterValueException(errorMsg);
}
// Check that the service offering being upgraded to has the same storage pool preference as the VM's current service offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + ", cannot switch between local storage and shared storage service offerings. Current offering useLocalStorage=" +
currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
}
throw new InvalidParameterValueException("Not upgrading vm " + vmInstance.toString() + " since it already has the requested service offering (" + newServiceOffering.getName() + ")");
}
// Check that the service offering being upgraded to has the same Guest IP type as the VM's current service offering
ServiceOfferingVO currentServiceOffering = _offeringDao.findById(vmInstance.getServiceOfferingId());
if (!currentServiceOffering.getGuestIpType().equals(newServiceOffering.getGuestIpType())) {
String errorMsg = "The service offering being upgraded to has a guest IP type: " + newServiceOffering.getGuestIpType();
errorMsg += ". Please select a service offering with the same guest IP type as the VM's current service offering (" + currentServiceOffering.getGuestIpType() + ").";
throw new InvalidParameterValueException(errorMsg);
}
// Check that the service offering being upgraded to has the same storage pool preference as the VM's current service offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine " + vmInstance.toString() + ", cannot switch between local storage and shared storage service offerings. Current offering useLocalStorage=" +
currentServiceOffering.getUseLocalStorage() + ", target offering useLocalStorage=" + newServiceOffering.getUseLocalStorage());
}
// Check that there are enough resources to upgrade the service offering
if (!_agentMgr.isVirtualMachineUpgradable(vmInstance, newServiceOffering)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available for an offering of " +
newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
}
// Check that the service offering being upgraded to has all the tags of the current service offering
List<String> currentTags = _configMgr.csvTagsToList(currentServiceOffering.getTags());
List<String> newTags = _configMgr.csvTagsToList(newServiceOffering.getTags());
if (!newTags.containsAll(currentTags)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering does not have all the tags of the " +
"current service offering. Current service offering tags: " + currentTags + "; " +
"new service offering tags: " + newTags);
}
// Check that there are enough resources to upgrade the service offering
if (!_agentMgr.isVirtualMachineUpgradable(vmInstance, newServiceOffering)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine, not enough resources available for an offering of " +
newServiceOffering.getCpu() + " cpu(s) at " + newServiceOffering.getSpeed() + " Mhz, and " + newServiceOffering.getRamSize() + " MB of memory");
}
// Check that the service offering being upgraded to has all the tags of the current service offering
List<String> currentTags = _configMgr.csvTagsToList(currentServiceOffering.getTags());
List<String> newTags = _configMgr.csvTagsToList(newServiceOffering.getTags());
if (!newTags.containsAll(currentTags)) {
throw new InvalidParameterValueException("Unable to upgrade virtual machine; the new service offering does not have all the tags of the " +
"current service offering. Current service offering tags: " + currentTags + "; " +
"new service offering tags: " + newTags);
}
// FIXME: save this eventId somewhere as part of the async process?
/*long eventId = */EventUtils.saveScheduledEvent(userId, vmInstance.getAccountId(), EventTypes.EVENT_VM_UPGRADE, "upgrading Vm with Id: "+vmInstance.getId());
// FIXME: save this eventId somewhere as part of the async process?
/*long eventId = */EventUtils.saveScheduledEvent(userId, vmInstance.getAccountId(), EventTypes.EVENT_VM_UPGRADE, "upgrading Vm with Id: "+vmInstance.getId());
vmInstance.setServiceOfferingId(serviceOfferingId);
vmInstance.setHaEnabled(_serviceOfferingDao.findById(serviceOfferingId).getOfferHA());