use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class ApiResponseHelper method showVmInfoForSharedNetworks.
private void showVmInfoForSharedNetworks(boolean forVirtualNetworks, IpAddress ipAddr, IPAddressResponse ipResponse) {
if (!forVirtualNetworks) {
NicVO nic = ApiDBUtils.findByIp4AddressAndNetworkId(ipAddr.getAddress().toString(), ipAddr.getNetworkId());
if (nic == null) {
// find in nic_secondary_ips, user vm only
NicSecondaryIpVO secondaryIp = ApiDBUtils.findSecondaryIpByIp4AddressAndNetworkId(ipAddr.getAddress().toString(), ipAddr.getNetworkId());
if (secondaryIp != null) {
UserVm vm = ApiDBUtils.findUserVmById(secondaryIp.getVmId());
if (vm != null) {
ipResponse.setVirtualMachineId(vm.getUuid());
ipResponse.setVirtualMachineName(vm.getHostName());
if (vm.getDisplayName() != null) {
ipResponse.setVirtualMachineDisplayName(vm.getDisplayName());
} else {
ipResponse.setVirtualMachineDisplayName(vm.getHostName());
}
}
}
} else if (nic.getVmType() == VirtualMachine.Type.User) {
UserVm vm = ApiDBUtils.findUserVmById(nic.getInstanceId());
if (vm != null) {
ipResponse.setVirtualMachineId(vm.getUuid());
ipResponse.setVirtualMachineName(vm.getHostName());
if (vm.getDisplayName() != null) {
ipResponse.setVirtualMachineDisplayName(vm.getDisplayName());
} else {
ipResponse.setVirtualMachineDisplayName(vm.getHostName());
}
}
} else if (nic.getVmType() == VirtualMachine.Type.DomainRouter) {
ipResponse.setIsSystem(true);
}
}
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class ApiResponseHelper method createLoadBalancerContainerReponse.
@Override
public ApplicationLoadBalancerResponse createLoadBalancerContainerReponse(ApplicationLoadBalancerRule lb, Map<Ip, UserVm> lbInstances) {
ApplicationLoadBalancerResponse lbResponse = new ApplicationLoadBalancerResponse();
lbResponse.setId(lb.getUuid());
lbResponse.setName(lb.getName());
lbResponse.setDescription(lb.getDescription());
lbResponse.setAlgorithm(lb.getAlgorithm());
lbResponse.setForDisplay(lb.isDisplay());
Network nw = ApiDBUtils.findNetworkById(lb.getNetworkId());
lbResponse.setNetworkId(nw.getUuid());
populateOwner(lbResponse, lb);
if (lb.getScheme() == Scheme.Internal) {
lbResponse.setSourceIp(lb.getSourceIp().addr());
// TODO - create the view for the load balancer rule to reflect the network uuid
Network network = ApiDBUtils.findNetworkById(lb.getNetworkId());
lbResponse.setSourceIpNetworkId(network.getUuid());
} else {
// for public, populate the ip information from the ip address
IpAddress publicIp = ApiDBUtils.findIpAddressById(lb.getSourceIpAddressId());
lbResponse.setSourceIp(publicIp.getAddress().addr());
Network ntwk = ApiDBUtils.findNetworkById(publicIp.getNetworkId());
lbResponse.setSourceIpNetworkId(ntwk.getUuid());
}
// set load balancer rules information (only one rule per load balancer in this release)
List<ApplicationLoadBalancerRuleResponse> ruleResponses = new ArrayList<ApplicationLoadBalancerRuleResponse>();
ApplicationLoadBalancerRuleResponse ruleResponse = new ApplicationLoadBalancerRuleResponse();
ruleResponse.setInstancePort(lb.getDefaultPortStart());
ruleResponse.setSourcePort(lb.getSourcePortStart());
FirewallRule.State stateToSet = lb.getState();
if (stateToSet.equals(FirewallRule.State.Revoke)) {
stateToSet = FirewallRule.State.Deleting;
}
ruleResponse.setState(stateToSet.toString());
ruleResponse.setObjectName("loadbalancerrule");
ruleResponses.add(ruleResponse);
lbResponse.setLbRules(ruleResponses);
// set Lb instances information
List<ApplicationLoadBalancerInstanceResponse> instanceResponses = new ArrayList<ApplicationLoadBalancerInstanceResponse>();
for (Map.Entry<Ip, UserVm> entry : lbInstances.entrySet()) {
Ip ip = entry.getKey();
UserVm vm = entry.getValue();
ApplicationLoadBalancerInstanceResponse instanceResponse = new ApplicationLoadBalancerInstanceResponse();
instanceResponse.setIpAddress(ip.addr());
instanceResponse.setId(vm.getUuid());
instanceResponse.setName(vm.getInstanceName());
instanceResponse.setObjectName("loadbalancerinstance");
instanceResponses.add(instanceResponse);
}
lbResponse.setLbInstances(instanceResponses);
// set tag information
List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(ResourceObjectType.LoadBalancer, lb.getId());
List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
for (ResourceTag tag : tags) {
ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
CollectionUtils.addIgnoreNull(tagResponses, tagResponse);
}
lbResponse.setTags(tagResponses);
lbResponse.setObjectName("loadbalancer");
return lbResponse;
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class TemplateManagerImpl method detachIso.
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_DETACH, eventDescription = "detaching ISO", async = true)
public boolean detachIso(long vmId, boolean forced) {
Account caller = CallContext.current().getCallingAccount();
Long userId = CallContext.current().getCallingUserId();
// Verify input parameters
UserVmVO vmInstanceCheck = _userVmDao.findById(vmId);
if (vmInstanceCheck == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
UserVm userVM = _userVmDao.findById(vmId);
if (userVM == null) {
throw new InvalidParameterValueException("Please specify a valid VM.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
Long isoId = userVM.getIsoId();
if (isoId == null) {
throw new InvalidParameterValueException("The specified VM has no ISO attached to it.");
}
CallContext.current().setEventDetails("Vm Id: " + userVM.getUuid() + " ISO Id: " + isoId);
State vmState = userVM.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
// attach=false
boolean result = attachISOToVM(vmId, userId, isoId, false, forced);
// => detach
if (result) {
return result;
} else {
throw new CloudRuntimeException("Failed to detach iso");
}
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class UserVmManagerImpl method updateNicIpForVirtualMachine.
@Override
public UserVm updateNicIpForVirtualMachine(UpdateVmNicIpCmd cmd) {
Long nicId = cmd.getNicId();
String ipaddr = cmd.getIpaddress();
Account caller = CallContext.current().getCallingAccount();
// check whether the nic belongs to user vm.
NicVO nicVO = _nicDao.findById(nicId);
if (nicVO == null) {
throw new InvalidParameterValueException("There is no nic for the " + nicId);
}
if (nicVO.getVmType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("The nic is not belongs to user vm");
}
UserVm vm = _vmDao.findById(nicVO.getInstanceId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the nic");
}
Network network = _networkDao.findById(nicVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("There is no network with the nic");
}
// Don't allow to update vm nic ip if network is not in Implemented/Setup/Allocated state
if (!(network.getState() == Network.State.Allocated || network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
throw new InvalidParameterValueException("Network is not in the right state to update vm nic ip. Correct states are: " + Network.State.Allocated + ", " + Network.State.Implemented + ", " + Network.State.Setup);
}
NetworkOfferingVO offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering == null) {
throw new InvalidParameterValueException("There is no network offering with the network");
}
if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && vm.getState() != State.Stopped) {
InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to update the vm nic having the specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
// verify ip address
s_logger.debug("Calling the ip allocation ...");
DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc == null) {
throw new InvalidParameterValueException("There is no dc with the nic");
}
if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
try {
ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
} catch (InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
}
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
if (nicVO.getIPv4Address() != null) {
updatePublicIpDnatVmIp(vm.getId(), network.getId(), nicVO.getIPv4Address(), ipaddr);
updateLoadBalancerRulesVmIp(vm.getId(), network.getId(), nicVO.getIPv4Address(), ipaddr);
updatePortForwardingRulesVmIp(vm.getId(), network.getId(), nicVO.getIPv4Address(), ipaddr);
}
} else if (dc.getNetworkType() == NetworkType.Basic || network.getGuestType() == Network.GuestType.Shared) {
// handle the basic networks here
// for basic zone, need to provide the podId to ensure proper ip alloation
Long podId = null;
if (dc.getNetworkType() == NetworkType.Basic) {
podId = vm.getPodIdToDeployIn();
if (podId == null) {
throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
}
}
try {
ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, ipaddr);
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
final IPAddressVO newIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), ipaddr);
final Vlan vlan = _vlanDao.findById(newIp.getVlanId());
nicVO.setIPv4Gateway(vlan.getVlanGateway());
nicVO.setIPv4Netmask(vlan.getVlanNetmask());
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nicVO.getNetworkId(), nicVO.getIPv4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} catch (InsufficientAddressCapacityException e) {
s_logger.error("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
return null;
}
} else {
throw new InvalidParameterValueException("UpdateVmNicIpCmd is not supported in L2 network");
}
s_logger.debug("Updating IPv4 address of NIC " + nicVO + " to " + ipaddr + "/" + nicVO.getIPv4Netmask() + " with gateway " + nicVO.getIPv4Gateway());
nicVO.setIPv4Address(ipaddr);
_nicDao.persist(nicVO);
return vm;
}
use of com.cloud.uservm.UserVm in project cloudstack by apache.
the class UserVmManagerImpl method updateVirtualMachine.
@Override
public UserVm updateVirtualMachine(long id, String displayName, String group, Boolean ha, Boolean isDisplayVmEnabled, Long osTypeId, String userData, Boolean isDynamicallyScalable, HTTPMethod httpMethod, String customId, String hostName, String instanceName, List<Long> securityGroupIdList, Map<String, Map<Integer, String>> extraDhcpOptionsMap) throws ResourceUnavailableException, InsufficientCapacityException {
UserVmVO vm = _vmDao.findById(id);
if (vm == null) {
throw new CloudRuntimeException("Unable to find virtual machine with id " + id);
}
if (instanceName != null) {
VMInstanceVO vmInstance = _vmInstanceDao.findVMByInstanceName(instanceName);
if (vmInstance != null && vmInstance.getId() != id) {
throw new CloudRuntimeException("Instance name : " + instanceName + " is not unique");
}
}
if (vm.getState() == State.Error || vm.getState() == State.Expunging) {
s_logger.error("vm is not in the right state: " + id);
throw new InvalidParameterValueException("Vm with id " + id + " is not in the right state");
}
if (displayName == null) {
displayName = vm.getDisplayName();
}
if (ha == null) {
ha = vm.isHaEnabled();
}
ServiceOffering offering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
if (!offering.isOfferHA() && ha) {
throw new InvalidParameterValueException("Can't enable ha for the vm as it's created from the Service offering having HA disabled");
}
if (isDisplayVmEnabled == null) {
isDisplayVmEnabled = vm.isDisplayVm();
}
boolean updateUserdata = false;
if (userData != null) {
// check and replace newlines
userData = userData.replace("\\n", "");
userData = validateUserData(userData, httpMethod);
// update userData on domain router.
updateUserdata = true;
} else {
userData = vm.getUserData();
}
if (osTypeId == null) {
osTypeId = vm.getGuestOSId();
}
if (group != null) {
addInstanceToGroup(id, group);
}
if (isDynamicallyScalable == null) {
isDynamicallyScalable = vm.isDynamicallyScalable();
} else {
if (isDynamicallyScalable == true) {
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
if (!template.isDynamicallyScalable()) {
throw new InvalidParameterValueException("Dynamic Scaling cannot be enabled for the VM since its template does not have dynamic scaling enabled");
}
if (!offering.isDynamicScalingEnabled()) {
throw new InvalidParameterValueException("Dynamic Scaling cannot be enabled for the VM since its service offering does not have dynamic scaling enabled");
}
if (!UserVmManager.EnableDynamicallyScaleVm.valueIn(vm.getDataCenterId())) {
s_logger.debug(String.format("Dynamic Scaling cannot be enabled for the VM %s since the global setting enable.dynamic.scale.vm is set to false", vm.getUuid()));
throw new InvalidParameterValueException("Dynamic Scaling cannot be enabled for the VM since corresponding global setting is set to false");
}
}
}
boolean isVMware = (vm.getHypervisorType() == HypervisorType.VMware);
if (securityGroupIdList != null && isVMware) {
throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
} else {
// Get default guest network in Basic zone
Network defaultNetwork = null;
try {
DataCenterVO zone = _dcDao.findById(vm.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Basic) {
// Get default guest network in Basic zone
defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
} else if (zone.isSecurityGroupEnabled()) {
NicVO defaultNic = _nicDao.findDefaultNicForVM(vm.getId());
if (defaultNic != null) {
defaultNetwork = _networkDao.findById(defaultNic.getNetworkId());
}
}
} catch (InvalidParameterValueException e) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(e.getMessage(), e);
}
defaultNetwork = _networkModel.getDefaultNetworkForVm(id);
}
if (securityGroupIdList != null && _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkModel.canAddDefaultSecurityGroup()) {
if (vm.getState() == State.Stopped) {
// Remove instance from security groups
_securityGroupMgr.removeInstanceFromGroups(id);
// Add instance in provided groups
_securityGroupMgr.addInstanceToGroups(id, securityGroupIdList);
} else {
throw new InvalidParameterValueException("Virtual machine must be stopped prior to update security groups ");
}
}
}
List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
if (hostName != null) {
// Check is hostName is RFC compliant
checkNameForRFCCompliance(hostName);
if (vm.getHostName().equalsIgnoreCase(hostName)) {
s_logger.debug("Vm " + vm + " is already set with the hostName specified: " + hostName);
hostName = null;
}
// Verify that vm's hostName is unique
List<NetworkVO> vmNtwks = new ArrayList<NetworkVO>(nics.size());
for (Nic nic : nics) {
vmNtwks.add(_networkDao.findById(nic.getNetworkId()));
}
checkIfHostNameUniqueInNtwkDomain(hostName, vmNtwks);
}
List<NetworkVO> networks = nics.stream().map(nic -> _networkDao.findById(nic.getNetworkId())).collect(Collectors.toList());
verifyExtraDhcpOptionsNetwork(extraDhcpOptionsMap, networks);
for (Nic nic : nics) {
_networkMgr.saveExtraDhcpOptions(networks.stream().filter(network -> network.getId() == nic.getNetworkId()).findFirst().get().getUuid(), nic.getId(), extraDhcpOptionsMap);
}
_vmDao.updateVM(id, displayName, ha, osTypeId, userData, isDisplayVmEnabled, isDynamicallyScalable, customId, hostName, instanceName);
if (updateUserdata) {
updateUserData(vm);
}
if (State.Running == vm.getState()) {
updateDns(vm, hostName);
}
return _vmDao.findById(id);
}
Aggregations