use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class ScaleVMCmdTest method testCreateSuccess.
@Test
public void testCreateSuccess() {
UserVmService userVmService = Mockito.mock(UserVmService.class);
UserVm userVm = Mockito.mock(UserVm.class);
try {
Mockito.when(userVmService.upgradeVirtualMachine(scaleVMCmd)).thenReturn(userVm);
} catch (Exception e) {
Assert.fail("Received exception when success expected " + e.getMessage());
}
ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class);
scaleVMCmd._responseGenerator = responseGenerator;
UserVmResponse userVmResponse = Mockito.mock(UserVmResponse.class);
//List<UserVmResponse> list = Mockito.mock(UserVmResponse.class);
//list.add(userVmResponse);
//LinkedList<UserVmResponse> mockedList = Mockito.mock(LinkedList.class);
//Mockito.when(mockedList.get(0)).thenReturn(userVmResponse);
List<UserVmResponse> list = new LinkedList<UserVmResponse>();
list.add(userVmResponse);
Mockito.when(responseGenerator.createUserVmResponse(ResponseView.Restricted, "virtualmachine", userVm)).thenReturn(list);
scaleVMCmd._userVmService = userVmService;
scaleVMCmd.execute();
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class VirtualMachineModel method build.
/**
* Resynchronize internal state from the cloudstack DB object.
* @param instance
*/
public void build(ModelController controller, VMInstanceVO instance) {
setProperties(controller, instance);
UserVm userVm = controller.getVmDao().findById(instance.getId());
if (userVm != null && userVm.getUserData() != null) {
s_logger.debug("vm " + instance.getInstanceName() + " user data: " + userVm.getUserData());
final Gson json = new Gson();
Map<String, String> kvmap = json.fromJson(userVm.getUserData(), new TypeToken<Map<String, String>>() {
}.getType());
//Renamed "data" to "serviceUuid" because it's clearer.
String serviceUuid = kvmap.get("service-instance");
if (serviceUuid != null) {
/*
* UUID.fromString() does not validate an UUID properly. I tried, for example, informing less digits in the UUID, where 12 were expected,
* and the UUID.fromstring() did not thrown the exception as expected. However, if you try UUID.fromString("aaa") it breaks, but if you try
* UUID.fromString("3dd4fa6e-2899-4429-b818-d34fe8df5") it doesn't (the last portion should have 12, instead of 9 digits).
*
* In other fix I added the validate UUID method to the UuidUtil classes.
*/
if (UuidUtils.validateUUID(serviceUuid)) {
/* link the object with the service instance */
buildServiceInstance(controller, serviceUuid);
} else {
// Throw a CloudRuntimeException in case the UUID is not valid.
String message = "Invalid UUID ({0}) given for the service-instance for VM {1}.";
message = MessageFormat.format(message, instance.getId(), serviceUuid);
s_logger.warn(message);
throw new CloudRuntimeException(message);
}
}
}
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class DetachIsoCmd method execute.
@Override
public void execute() {
boolean result = _templateService.detachIso(virtualMachineId);
if (result) {
UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId);
UserVmResponse response = _responseGenerator.createUserVmResponse(ResponseView.Restricted, "virtualmachine", userVm).get(0);
response.setResponseName(DeployVMCmd.getResultObjectName());
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to detach ISO");
}
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method assignToLoadBalancer.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
public boolean assignToLoadBalancer(long loadBalancerId, List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
CallContext ctx = CallContext.current();
Account caller = ctx.getCallingAccount();
final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
if (loadBalancer == null) {
throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
}
if (instanceIds == null && vmIdIpMap.isEmpty()) {
throw new InvalidParameterValueException("Both instanceids and vmidipmap can't be null");
}
// instanceIds and vmIdipmap is passed
if (instanceIds != null && !vmIdIpMap.isEmpty()) {
for (long instanceId : instanceIds) {
if (!vmIdIpMap.containsKey(instanceId)) {
vmIdIpMap.put(instanceId, null);
}
}
}
//only instanceids list passed
if (instanceIds != null && vmIdIpMap.isEmpty()) {
vmIdIpMap = new HashMap<Long, List<String>>();
for (long instanceId : instanceIds) {
vmIdIpMap.put(instanceId, null);
}
}
List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
Set<Long> mappedInstanceIds = new HashSet<Long>();
for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
}
Map<Long, List<String>> existingVmIdIps = new HashMap<Long, List<String>>();
// now get the ips of vm and add it to map
for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
List<String> ipsList = null;
if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
} else {
ipsList = new ArrayList<String>();
}
ipsList.add(mappedInstance.getInstanceIp());
existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
}
final List<UserVm> vmsToAdd = new ArrayList<UserVm>();
// check for conflict
Set<Long> passedInstanceIds = vmIdIpMap.keySet();
for (Long instanceId : passedInstanceIds) {
UserVm vm = _vmDao.findById(instanceId);
if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
InvalidParameterValueException ex = new InvalidParameterValueException("Invalid instance id specified");
if (vm == null) {
ex.addProxyObject(instanceId.toString(), "instanceId");
} else {
ex.addProxyObject(vm.getUuid(), "instanceId");
}
throw ex;
}
_rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);
if (vm.getAccountId() != loadBalancer.getAccountId()) {
throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner.");
}
// Let's check to make sure the vm has a nic in the same network as
// the load balancing rule.
List<? extends Nic> nics = _networkModel.getNics(vm.getId());
Nic nicInSameNetwork = null;
for (Nic nic : nics) {
if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
nicInSameNetwork = nic;
break;
}
}
if (nicInSameNetwork == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("VM with id specified cannot be added because it doesn't belong in the same network.");
ex.addProxyObject(vm.getUuid(), "instanceId");
throw ex;
}
String priIp = nicInSameNetwork.getIPv4Address();
if (existingVmIdIps.containsKey(instanceId)) {
// now check for ip address
List<String> mappedIps = existingVmIdIps.get(instanceId);
List<String> newIps = vmIdIpMap.get(instanceId);
if (newIps == null) {
newIps = new ArrayList<String>();
newIps.add(priIp);
}
for (String newIp : newIps) {
if (mappedIps.contains(newIp)) {
throw new InvalidParameterValueException("VM " + instanceId + " with " + newIp + " is already mapped to load balancer.");
}
}
}
List<String> vmIpsList = vmIdIpMap.get(instanceId);
String vmLbIp = null;
if (vmIpsList != null) {
//check if the ips belongs to nic secondary ip
for (String ip : vmIpsList) {
// skip the primary ip from vm secondary ip comparisions
if (ip.equals(priIp)) {
continue;
}
if (_nicSecondaryIpDao.findByIp4AddressAndNicId(ip, nicInSameNetwork.getId()) == null) {
throw new InvalidParameterValueException("VM ip " + ip + " specified does not belong to " + "nic in network " + nicInSameNetwork.getNetworkId());
}
}
} else {
vmIpsList = new ArrayList<String>();
vmIpsList.add(priIp);
}
// assign for primary ip and ip passed in vmidipmap
if (instanceIds != null) {
if (instanceIds.contains(instanceId)) {
vmIpsList.add(priIp);
}
}
vmIdIpMap.put(instanceId, vmIpsList);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Adding " + vm + " to the load balancer pool");
}
vmsToAdd.add(vm);
}
final Set<Long> vmIds = vmIdIpMap.keySet();
final Map<Long, List<String>> newMap = vmIdIpMap;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (Long vmId : vmIds) {
final Set<String> lbVmIps = new HashSet<String>(newMap.get(vmId));
for (String vmIp : lbVmIps) {
LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
map = _lb2VmMapDao.persist(map);
}
}
}
});
if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
// We can consider the job done.
return true;
}
boolean success = false;
FirewallRule.State backupState = loadBalancer.getState();
try {
loadBalancer.setState(FirewallRule.State.Add);
_lbDao.persist(loadBalancer);
applyLoadBalancerConfig(loadBalancerId);
success = true;
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
success = false;
} finally {
if (!success) {
final List<Long> vmInstanceIds = new ArrayList<Long>();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (Long vmId : vmIds) {
vmInstanceIds.add(vmId);
}
}
});
if (!vmInstanceIds.isEmpty()) {
_lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while attaching VM: " + vmInstanceIds);
}
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + vmInstanceIds);
ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
// right VO object or table name.
throw ex;
}
}
return success;
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method updateLBHealthChecks.
// This method will check the status of services which has monitors created
// by CloudStack and update them in lbvmmap table
@DB
@Override
public void updateLBHealthChecks(Scheme scheme) throws ResourceUnavailableException {
List<LoadBalancerVO> rules = _lbDao.listAll();
List<NetworkVO> networks = _networkDao.listAll();
List<LoadBalancerTO> stateRules = null;
boolean isHandled = false;
for (NetworkVO ntwk : networks) {
Network network = _networkDao.findById(ntwk.getId());
String capability = getLBCapability(network.getId(), Capability.HealthCheckPolicy.getName());
if (capability != null && capability.equalsIgnoreCase("true")) {
/*
* s_logger.debug(
* "HealthCheck Manager :: LB Provider in the Network has the Healthcheck policy capability :: "
* + provider.get(0).getName());
*/
rules = _lbDao.listByNetworkIdAndScheme(network.getId(), scheme);
if (rules != null && rules.size() > 0) {
List<LoadBalancingRule> lbrules = new ArrayList<LoadBalancingRule>();
for (LoadBalancerVO lb : rules) {
List<LbDestination> dstList = getExistingDestinations(lb.getId());
List<LbHealthCheckPolicy> hcPolicyList = getHealthCheckPolicies(lb.getId());
// hashealtChecks
if (hcPolicyList != null && hcPolicyList.size() > 0) {
Ip sourceIp = getSourceIp(lb);
LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, null, hcPolicyList, sourceIp, null, lb.getLbProtocol());
lbrules.add(loadBalancing);
}
}
if (lbrules.size() > 0) {
isHandled = false;
for (LoadBalancingServiceProvider lbElement : _lbProviders) {
stateRules = lbElement.updateHealthChecks(network, lbrules);
if (stateRules != null && stateRules.size() > 0) {
for (LoadBalancerTO lbto : stateRules) {
LoadBalancerVO ulb = _lbDao.findByUuid(lbto.getUuid());
List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(ulb.getId());
for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(ulb.getNetworkId(), vm.getId());
String dstIp = lbVmMap.getInstanceIp() == null ? nic.getIPv4Address() : lbVmMap.getInstanceIp();
for (int i = 0; i < lbto.getDestinations().length; i++) {
LoadBalancerTO.DestinationTO des = lbto.getDestinations()[i];
if (dstIp.equalsIgnoreCase(lbto.getDestinations()[i].getDestIp())) {
lbVmMap.setState(des.getMonitorState());
_lb2VmMapDao.persist(lbVmMap);
s_logger.debug("Updating the LB VM Map table with the service state");
}
}
}
}
isHandled = true;
}
if (isHandled) {
break;
}
}
}
}
} else {
// s_logger.debug("HealthCheck Manager :: LB Provider in the Network DNOT the Healthcheck policy capability ");
}
}
}
Aggregations