Search in sources :

Example 76 with UserVmVO

use of com.cloud.vm.UserVmVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method listLoadBalancerInstances.

@Override
public Pair<List<? extends UserVm>, List<String>> listLoadBalancerInstances(final ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException {
    final Account caller = CallContext.current().getCallingAccount();
    final Long loadBalancerId = cmd.getId();
    Boolean applied = cmd.isApplied();
    if (applied == null) {
        applied = Boolean.TRUE;
    }
    final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        return null;
    }
    _accountMgr.checkAccess(caller, null, true, loadBalancer);
    final List<UserVmVO> loadBalancerInstances = new ArrayList<>();
    final List<String> serviceStates = new ArrayList<>();
    List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null;
    vmLoadBalancerMappings = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
    if (vmLoadBalancerMappings == null) {
        final String msg = "no VM Loadbalancer Mapping found";
        s_logger.error(msg);
        throw new CloudRuntimeException(msg);
    }
    final Map<Long, String> vmServiceState = new HashMap<>(vmLoadBalancerMappings.size());
    final List<Long> appliedInstanceIdList = new ArrayList<>();
    if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) {
        for (final LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) {
            appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId());
            vmServiceState.put(vmLoadBalancerMapping.getInstanceId(), vmLoadBalancerMapping.getState());
        }
    }
    final List<UserVmVO> userVms = _vmDao.listVirtualNetworkInstancesByAcctAndNetwork(loadBalancer.getAccountId(), loadBalancer.getNetworkId());
    for (final UserVmVO userVm : userVms) {
        // an unknown state, skip it
        switch(userVm.getState()) {
            case Destroyed:
            case Expunging:
            case Error:
            case Unknown:
                continue;
        }
        final boolean isApplied = appliedInstanceIdList.contains(userVm.getId());
        if ((isApplied && applied) || (!isApplied && !applied)) {
            loadBalancerInstances.add(userVm);
            serviceStates.add(vmServiceState.get(userVm.getId()));
        }
    }
    return new Pair<>(loadBalancerInstances, serviceStates);
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) Pair(com.cloud.utils.Pair)

Example 77 with UserVmVO

use of com.cloud.vm.UserVmVO in project cosmic by MissionCriticalCloud.

the class CommandSetupHelper method createVmOverviewFromRouter.

public VMOverviewTO createVmOverviewFromRouter(final VirtualRouter router) {
    final VMOverviewTO vmOverviewTO = new VMOverviewTO();
    final Map<UserVmVO, List<NicVO>> vmsAndNicsMap = new HashMap<>();
    final List<NicVO> routerNics = _nicDao.listByVmId(router.getId());
    for (final NicVO routerNic : routerNics) {
        final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
        if (TrafficType.Guest.equals(network.getTrafficType()) && !Network.GuestType.Sync.equals(network.getGuestType())) {
            _userVmDao.listByNetworkIdAndStates(network.getId(), VirtualMachine.State.Starting, VirtualMachine.State.Running, VirtualMachine.State.Paused, VirtualMachine.State.Migrating, VirtualMachine.State.Stopping).forEach(vm -> {
                final NicVO nic = _nicDao.findByNtwkIdAndInstanceId(network.getId(), vm.getId());
                if (nic != null) {
                    if (!vmsAndNicsMap.containsKey(vm)) {
                        vmsAndNicsMap.put(vm, new ArrayList<NicVO>() {

                            {
                                add(nic);
                            }
                        });
                    } else {
                        vmsAndNicsMap.get(vm).add(nic);
                    }
                }
            });
        }
    }
    final List<VMOverviewTO.VMTO> vmsTO = new ArrayList<>();
    vmsAndNicsMap.forEach((vm, nics) -> {
        _userVmDao.loadDetails(vm);
        final VMOverviewTO.VMTO vmTO = new VMOverviewTO.VMTO(vm.getHostName());
        final List<VMOverviewTO.VMTO.InterfaceTO> interfacesTO = new ArrayList<>();
        final ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
        final Zone zone = zoneRepository.findOne(router.getDataCenterId());
        nics.forEach(nic -> {
            final VMOverviewTO.VMTO.InterfaceTO interfaceTO = new VMOverviewTO.VMTO.InterfaceTO(nic.getIPv4Address(), nic.getMacAddress(), nic.isDefaultNic());
            final NetworkVO networkVO = _networkDao.findById(nic.getNetworkId());
            final String vmNameFQDN = networkVO != null ? vm.getHostName() + "." + networkVO.getNetworkDomain() : vm.getHostName();
            final Map<String, String> metadata = interfaceTO.getMetadata();
            metadata.put("service-offering", StringUtils.unicodeEscape(serviceOffering.getDisplayText()));
            metadata.put("availability-zone", StringUtils.unicodeEscape(zone.getName()));
            metadata.put("local-ipv4", nic.getIPv4Address());
            metadata.put("local-hostname", StringUtils.unicodeEscape(vmNameFQDN));
            metadata.put("public-ipv4", router.getPublicIpAddress() != null ? router.getPublicIpAddress() : nic.getIPv4Address());
            metadata.put("public-hostname", router.getPublicIpAddress());
            metadata.put("instance-id", vm.getUuid() != null ? vm.getUuid() : vm.getInstanceName());
            metadata.put("vm-id", vm.getUuid() != null ? vm.getUuid() : String.valueOf(vm.getId()));
            metadata.put("public-keys", vm.getDetail("SSH.PublicKey"));
            final String cloudIdentifier = _configDao.getValue("cloud.identifier");
            metadata.put("cloud-identifier", cloudIdentifier != null ? "CloudStack-{" + cloudIdentifier + "}" : "");
            final Map<String, String> userData = interfaceTO.getUserData();
            userData.put("user-data", vm.getUserData());
            interfacesTO.add(interfaceTO);
        });
        vmTO.setInterfaces(interfacesTO.toArray(new VMOverviewTO.VMTO.InterfaceTO[interfacesTO.size()]));
        vmsTO.add(vmTO);
    });
    vmOverviewTO.setVms(vmsTO.toArray(new VMOverviewTO.VMTO[vmsTO.size()]));
    return vmOverviewTO;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) NetworkVO(com.cloud.network.dao.NetworkVO) HashMap(java.util.HashMap) Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VMOverviewTO(com.cloud.agent.api.to.overviews.VMOverviewTO) Network(com.cloud.network.Network) List(java.util.List) ArrayList(java.util.ArrayList) NicVO(com.cloud.vm.NicVO)

Example 78 with UserVmVO

use of com.cloud.vm.UserVmVO in project cosmic by MissionCriticalCloud.

the class FirewallManagerImpl method revokeFirewallRulesForVm.

@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRulesForVm(final long vmId) {
    boolean success = true;
    final UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId);
    if (vm == null) {
        return false;
    }
    final List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId);
    final List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId());
    final List<FirewallRuleVO> firewallRules = new ArrayList<>();
    // Make a list of firewall rules to reprogram
    for (final PortForwardingRuleVO pfRule : pfRules) {
        final FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId());
        if (relatedRule != null) {
            firewallRules.add(relatedRule);
        }
    }
    for (final FirewallRuleVO staticNatRule : staticNatRules) {
        final FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId());
        if (relatedRule != null) {
            firewallRules.add(relatedRule);
        }
    }
    final Set<Long> ipsToReprogram = new HashSet<>();
    if (firewallRules.isEmpty()) {
        s_logger.debug("No firewall rules are found for vm id=" + vmId);
        return true;
    } else {
        s_logger.debug("Found " + firewallRules.size() + " to cleanup for vm id=" + vmId);
    }
    for (final FirewallRuleVO rule : firewallRules) {
        // Mark firewall rules as Revoked, but don't revoke it yet (apply=false)
        revokeFirewallRule(rule.getId(), false, _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM);
        ipsToReprogram.add(rule.getSourceIpAddressId());
    }
    // apply rules for all ip addresses
    for (final Long ipId : ipsToReprogram) {
        s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge");
        try {
            success = success && applyIngressFirewallRules(ipId, _accountMgr.getSystemAccount());
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
            success = false;
        }
    }
    return success;
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) ArrayList(java.util.ArrayList) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) HashSet(java.util.HashSet) ActionEvent(com.cloud.event.ActionEvent)

Example 79 with UserVmVO

use of com.cloud.vm.UserVmVO in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method listNics.

@Override
public List<? extends Nic> listNics(final ListNicsCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    final Long nicId = cmd.getNicId();
    final long vmId = cmd.getVmId();
    final Long networkId = cmd.getNetworkId();
    final UserVmVO userVm = _userVmDao.findById(vmId);
    if (userVm == null || !userVm.isDisplayVm() && caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Virtual mahine id does not exist");
        ex.addProxyObject(Long.valueOf(vmId).toString(), "vmId");
        throw ex;
    }
    _accountMgr.checkAccess(caller, null, true, userVm);
    return _networkMgr.listVmNics(vmId, nicId, networkId);
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException)

Example 80 with UserVmVO

use of com.cloud.vm.UserVmVO in project cosmic by MissionCriticalCloud.

the class VirtualRouterElement method rollbackMigration.

@Override
public void rollbackMigration(final NicProfile nic, final Network network, final VirtualMachineProfile vm, final ReservationContext src, final ReservationContext dst) {
    if (nic.getBroadcastType() != Networks.BroadcastDomainType.Pvlan) {
        return;
    }
    if (vm.getType() == VirtualMachine.Type.DomainRouter) {
        assert vm instanceof DomainRouterVO;
        final DomainRouterVO router = (DomainRouterVO) vm.getVirtualMachine();
        final Zone zone = zoneRepository.findOne(network.getDataCenterId());
        final NetworkTopology networkTopology = networkTopologyContext.retrieveNetworkTopology(zone);
        try {
            networkTopology.setupDhcpForPvlan(true, router, router.getHostId(), nic);
        } catch (final ResourceUnavailableException e) {
            s_logger.warn("Timed Out", e);
        }
    } else if (vm.getType() == VirtualMachine.Type.User) {
        assert vm instanceof UserVmVO;
        final UserVmVO userVm = (UserVmVO) vm.getVirtualMachine();
        _userVmMgr.setupVmForPvlan(true, userVm.getHostId(), nic);
    }
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) Zone(com.cloud.db.model.Zone) NetworkTopology(com.cloud.network.topology.NetworkTopology) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Aggregations

UserVmVO (com.cloud.vm.UserVmVO)190 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)79 Account (com.cloud.user.Account)50 ArrayList (java.util.ArrayList)45 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)39 HostVO (com.cloud.host.HostVO)34 VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)33 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)31 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)30 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)28 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)25 VolumeVO (com.cloud.storage.VolumeVO)25 VMInstanceVO (com.cloud.vm.VMInstanceVO)24 ActionEvent (com.cloud.event.ActionEvent)23 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)22 GuestOSVO (com.cloud.storage.GuestOSVO)20 HashMap (java.util.HashMap)19 ConfigurationException (javax.naming.ConfigurationException)19 Test (org.junit.Test)19 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)18