Search in sources :

Example 11 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class RecreatableFencer method fenceOff.

@Override
public Boolean fenceOff(VirtualMachine vm, Host host) {
    VirtualMachine.Type type = vm.getType();
    if (type != VirtualMachine.Type.ConsoleProxy && type != VirtualMachine.Type.DomainRouter && type != VirtualMachine.Type.SecondaryStorageVm) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Don't know how to fence off " + type);
        }
        return null;
    }
    List<VolumeVO> vols = _volsDao.findByInstance(vm.getId());
    for (VolumeVO vol : vols) {
        if (!vol.isRecreatable()) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to fence off volumes that are not recreatable: " + vol);
            }
            return null;
        }
        if (vol.getPoolType().isShared()) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Unable to fence off volumes that are shared: " + vol);
            }
            return null;
        }
    }
    return true;
}
Also used : VolumeVO(com.cloud.storage.VolumeVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 12 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class HighAvailabilityManagerImpl method stopVM.

protected Long stopVM(final HaWorkVO work) throws ConcurrentOperationException {
    VirtualMachine vm = _itMgr.findById(work.getInstanceId());
    if (vm == null) {
        s_logger.info("No longer can find VM " + work.getInstanceId() + ". Throwing away " + work);
        work.setStep(Step.Done);
        return null;
    }
    s_logger.info("Stopping " + vm);
    try {
        if (work.getWorkType() == WorkType.Stop) {
            _itMgr.advanceStop(vm.getUuid(), false);
            s_logger.info("Successfully stopped " + vm);
            return null;
        } else if (work.getWorkType() == WorkType.CheckStop) {
            if ((vm.getState() != work.getPreviousState()) || vm.getUpdated() != work.getUpdateTime() || vm.getHostId() == null || vm.getHostId().longValue() != work.getHostId()) {
                s_logger.info(vm + " is different now.  Scheduled Host: " + work.getHostId() + " Current Host: " + (vm.getHostId() != null ? vm.getHostId() : "none") + " State: " + vm.getState());
                return null;
            }
            _itMgr.advanceStop(vm.getUuid(), false);
            s_logger.info("Stop for " + vm + " was successful");
            return null;
        } else if (work.getWorkType() == WorkType.ForceStop) {
            if ((vm.getState() != work.getPreviousState()) || vm.getUpdated() != work.getUpdateTime() || vm.getHostId() == null || vm.getHostId().longValue() != work.getHostId()) {
                s_logger.info(vm + " is different now.  Scheduled Host: " + work.getHostId() + " Current Host: " + (vm.getHostId() != null ? vm.getHostId() : "none") + " State: " + vm.getState());
                return null;
            }
            _itMgr.advanceStop(vm.getUuid(), true);
            s_logger.info("Stop for " + vm + " was successful");
            return null;
        } else {
            assert false : "Who decided there's other steps but didn't modify the guy who does the work?";
        }
    } catch (final ResourceUnavailableException e) {
        s_logger.debug("Agnet is not available" + e.getMessage());
    } catch (OperationTimedoutException e) {
        s_logger.debug("operation timed out: " + e.getMessage());
    }
    return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
}
Also used : OperationTimedoutException(com.cloud.exception.OperationTimedoutException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 13 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class VirtualNetworkApplianceManagerImpl method finalizeStop.

@Override
public void finalizeStop(final VirtualMachineProfile profile, final Answer answer) {
    if (answer != null) {
        final VirtualMachine vm = profile.getVirtualMachine();
        final DomainRouterVO domR = _routerDao.findById(vm.getId());
        processStopOrRebootAnswer(domR, answer);
        final List<? extends Nic> routerNics = _nicDao.listByVmId(profile.getId());
        for (final Nic nic : routerNics) {
            final Network network = _networkModel.getNetwork(nic.getNetworkId());
            final DataCenterVO dcVO = _dcDao.findById(network.getDataCenterId());
            if (network.getTrafficType() == TrafficType.Guest && nic.getBroadcastUri() != null && nic.getBroadcastUri().getScheme().equals("pvlan")) {
                final NicProfile nicProfile = new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), 0, false, "pvlan-nic");
                final NetworkTopology networkTopology = _networkTopologyContext.retrieveNetworkTopology(dcVO);
                try {
                    networkTopology.setupDhcpForPvlan(false, domR, domR.getHostId(), nicProfile);
                } catch (final ResourceUnavailableException e) {
                    s_logger.debug("ERROR in finalizeStop: ", e);
                }
            }
        }
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Network(com.cloud.network.Network) NetworkTopology(org.apache.cloudstack.network.topology.NetworkTopology) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Nic(com.cloud.vm.Nic) NicProfile(com.cloud.vm.NicProfile) DomainRouterVO(com.cloud.vm.DomainRouterVO) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 14 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class VpcVirtualNetworkApplianceManagerImpl method finalizeCommandsOnStart.

@Override
public boolean finalizeCommandsOnStart(final Commands cmds, final VirtualMachineProfile profile) {
    final DomainRouterVO domainRouterVO = _routerDao.findById(profile.getId());
    Map<String, String> details = new HashMap<String, String>();
    if (profile.getHypervisorType() == Hypervisor.HypervisorType.VMware) {
        HypervisorGuru hvGuru = _hvGuruMgr.getGuru(profile.getHypervisorType());
        VirtualMachineTO vmTO = hvGuru.implement(profile);
        if (vmTO.getDetails() != null) {
            details = vmTO.getDetails();
        }
    }
    final boolean isVpc = domainRouterVO.getVpcId() != null;
    if (!isVpc) {
        return super.finalizeCommandsOnStart(cmds, profile);
    }
    if (domainRouterVO.getState() == State.Starting || domainRouterVO.getState() == State.Running) {
        // 1) FORM SSH CHECK COMMAND
        final NicProfile controlNic = getControlNic(profile);
        if (controlNic == null) {
            s_logger.error("Control network doesn't exist for the router " + domainRouterVO);
            return false;
        }
        finalizeSshAndVersionAndNetworkUsageOnStart(cmds, profile, domainRouterVO, controlNic);
        // 2) FORM PLUG NIC COMMANDS
        final List<Pair<Nic, Network>> guestNics = new ArrayList<Pair<Nic, Network>>();
        final List<Pair<Nic, Network>> publicNics = new ArrayList<Pair<Nic, Network>>();
        final Map<String, String> vlanMacAddress = new HashMap<String, String>();
        final List<? extends Nic> routerNics = _nicDao.listByVmId(profile.getId());
        for (final Nic routerNic : routerNics) {
            final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
            if (network.getTrafficType() == TrafficType.Guest) {
                final Pair<Nic, Network> guestNic = new Pair<Nic, Network>(routerNic, network);
                guestNics.add(guestNic);
            } else if (network.getTrafficType() == TrafficType.Public) {
                final Pair<Nic, Network> publicNic = new Pair<Nic, Network>(routerNic, network);
                publicNics.add(publicNic);
                final String vlanTag = BroadcastDomainType.getValue(routerNic.getBroadcastUri());
                vlanMacAddress.put(vlanTag, routerNic.getMacAddress());
            }
        }
        final List<Command> usageCmds = new ArrayList<Command>();
        // 3) PREPARE PLUG NIC COMMANDS
        try {
            // add VPC router to public networks
            final List<PublicIp> sourceNat = new ArrayList<PublicIp>(1);
            for (final Pair<Nic, Network> nicNtwk : publicNics) {
                final Nic publicNic = nicNtwk.first();
                final Network publicNtwk = nicNtwk.second();
                final IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(publicNtwk.getId(), publicNic.getIPv4Address());
                if (userIp.isSourceNat()) {
                    final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
                    sourceNat.add(publicIp);
                    if (domainRouterVO.getPublicIpAddress() == null) {
                        final DomainRouterVO routerVO = _routerDao.findById(domainRouterVO.getId());
                        routerVO.setPublicIpAddress(publicNic.getIPv4Address());
                        routerVO.setPublicNetmask(publicNic.getIPv4Netmask());
                        routerVO.setPublicMacAddress(publicNic.getMacAddress());
                        _routerDao.update(routerVO.getId(), routerVO);
                    }
                }
                final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, publicNic.getNetworkId(), publicNic.getBroadcastUri().toString()), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
                cmds.addCommand(plugNicCmd);
                final VpcVO vpc = _vpcDao.findById(domainRouterVO.getVpcId());
                final NetworkUsageCommand netUsageCmd = new NetworkUsageCommand(domainRouterVO.getPrivateIpAddress(), domainRouterVO.getInstanceName(), true, publicNic.getIPv4Address(), vpc.getCidr());
                usageCmds.add(netUsageCmd);
                UserStatisticsVO stats = _userStatsDao.findBy(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString());
                if (stats == null) {
                    stats = new UserStatisticsVO(domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString(), publicNtwk.getId());
                    _userStatsDao.persist(stats);
                }
            }
            // create ip assoc for source nat
            if (!sourceNat.isEmpty()) {
                _commandSetupHelper.createVpcAssociatePublicIPCommands(domainRouterVO, sourceNat, cmds, vlanMacAddress);
            }
            // add VPC router to guest networks
            for (final Pair<Nic, Network> nicNtwk : guestNics) {
                final Nic guestNic = nicNtwk.first();
                // plug guest nic
                final PlugNicCommand plugNicCmd = new PlugNicCommand(_nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType(), details);
                cmds.addCommand(plugNicCmd);
                if (!_networkModel.isPrivateGateway(guestNic.getNetworkId())) {
                    // set guest network
                    final VirtualMachine vm = _vmDao.findById(domainRouterVO.getId());
                    final NicProfile nicProfile = _networkModel.getNicProfile(vm, guestNic.getNetworkId(), null);
                    final SetupGuestNetworkCommand setupCmd = _commandSetupHelper.createSetupGuestNetworkCommand(domainRouterVO, true, nicProfile);
                    cmds.addCommand(setupCmd);
                } else {
                    // set private network
                    final PrivateIpVO ipVO = _privateIpDao.findByIpAndSourceNetworkId(guestNic.getNetworkId(), guestNic.getIPv4Address());
                    final Network network = _networkDao.findById(guestNic.getNetworkId());
                    BroadcastDomainType.getValue(network.getBroadcastUri());
                    final String netmask = NetUtils.getCidrNetmask(network.getCidr());
                    final PrivateIpAddress ip = new PrivateIpAddress(ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, guestNic.getMacAddress());
                    final List<PrivateIpAddress> privateIps = new ArrayList<PrivateIpAddress>(1);
                    privateIps.add(ip);
                    _commandSetupHelper.createVpcAssociatePrivateIPCommands(domainRouterVO, privateIps, cmds, true);
                    final Long privateGwAclId = _vpcGatewayDao.getNetworkAclIdForPrivateIp(ipVO.getVpcId(), ipVO.getNetworkId(), ipVO.getIpAddress());
                    if (privateGwAclId != null) {
                        // set network acl on private gateway
                        final List<NetworkACLItemVO> networkACLs = _networkACLItemDao.listByACL(privateGwAclId);
                        s_logger.debug("Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + domainRouterVO + " start for private gateway ip = " + ipVO.getIpAddress());
                        _commandSetupHelper.createNetworkACLsCommands(networkACLs, domainRouterVO, cmds, ipVO.getNetworkId(), true);
                    }
                }
            }
        } catch (final Exception ex) {
            s_logger.warn("Failed to add router " + domainRouterVO + " to network due to exception ", ex);
            return false;
        }
        // 4) RE-APPLY ALL STATIC ROUTE RULES
        final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcId(domainRouterVO.getVpcId());
        final List<StaticRouteProfile> staticRouteProfiles = new ArrayList<StaticRouteProfile>(routes.size());
        final Map<Long, VpcGateway> gatewayMap = new HashMap<Long, VpcGateway>();
        for (final StaticRoute route : routes) {
            VpcGateway gateway = gatewayMap.get(route.getVpcGatewayId());
            if (gateway == null) {
                gateway = _entityMgr.findById(VpcGateway.class, route.getVpcGatewayId());
                gatewayMap.put(gateway.getId(), gateway);
            }
            staticRouteProfiles.add(new StaticRouteProfile(route, gateway));
        }
        s_logger.debug("Found " + staticRouteProfiles.size() + " static routes to apply as a part of vpc route " + domainRouterVO + " start");
        if (!staticRouteProfiles.isEmpty()) {
            _commandSetupHelper.createStaticRouteCommands(staticRouteProfiles, domainRouterVO, cmds);
        }
        // 5) RE-APPLY ALL REMOTE ACCESS VPNs
        final RemoteAccessVpnVO vpn = _vpnDao.findByAccountAndVpc(domainRouterVO.getAccountId(), domainRouterVO.getVpcId());
        if (vpn != null) {
            _commandSetupHelper.createApplyVpnCommands(true, vpn, domainRouterVO, cmds);
        }
        // 6) REPROGRAM GUEST NETWORK
        boolean reprogramGuestNtwks = true;
        if (profile.getParameter(Param.ReProgramGuestNetworks) != null && (Boolean) profile.getParameter(Param.ReProgramGuestNetworks) == false) {
            reprogramGuestNtwks = false;
        }
        final VirtualRouterProvider vrProvider = _vrProviderDao.findById(domainRouterVO.getElementId());
        if (vrProvider == null) {
            throw new CloudRuntimeException("Cannot find related virtual router provider of router: " + domainRouterVO.getHostName());
        }
        final Provider provider = Network.Provider.getProvider(vrProvider.getType().toString());
        if (provider == null) {
            throw new CloudRuntimeException("Cannot find related provider of virtual router provider: " + vrProvider.getType().toString());
        }
        for (final Pair<Nic, Network> nicNtwk : guestNics) {
            final Nic guestNic = nicNtwk.first();
            final AggregationControlCommand startCmd = new AggregationControlCommand(Action.Start, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
            cmds.addCommand(startCmd);
            if (reprogramGuestNtwks) {
                finalizeIpAssocForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId(), vlanMacAddress);
                finalizeNetworkRulesForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId());
            }
            finalizeUserDataAndDhcpOnStart(cmds, domainRouterVO, provider, guestNic.getNetworkId());
            final AggregationControlCommand finishCmd = new AggregationControlCommand(Action.Finish, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork(guestNic.getNetworkId(), domainRouterVO.getId()));
            cmds.addCommand(finishCmd);
        }
        // Add network usage commands
        cmds.addCommands(usageCmds);
    }
    return true;
}
Also used : RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) PrivateIpAddress(com.cloud.network.vpc.PrivateIpAddress) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PrivateIpVO(com.cloud.network.vpc.PrivateIpVO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) NetworkACLItemVO(com.cloud.network.vpc.NetworkACLItemVO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) StaticRouteProfile(com.cloud.network.vpc.StaticRouteProfile) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) AggregationControlCommand(com.cloud.agent.api.routing.AggregationControlCommand) VpcGateway(com.cloud.network.vpc.VpcGateway) PlugNicCommand(com.cloud.agent.api.PlugNicCommand) Pair(com.cloud.utils.Pair) StaticRoute(com.cloud.network.vpc.StaticRoute) PublicIp(com.cloud.network.addr.PublicIp) Nic(com.cloud.vm.Nic) NetworkUsageCommand(com.cloud.agent.api.NetworkUsageCommand) NicProfile(com.cloud.vm.NicProfile) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) Provider(com.cloud.network.Network.Provider) VpcVO(com.cloud.network.vpc.VpcVO) PlugNicCommand(com.cloud.agent.api.PlugNicCommand) SetupGuestNetworkCommand(com.cloud.agent.api.SetupGuestNetworkCommand) AggregationControlCommand(com.cloud.agent.api.routing.AggregationControlCommand) Command(com.cloud.agent.api.Command) NetworkUsageCommand(com.cloud.agent.api.NetworkUsageCommand) VirtualRouterProvider(com.cloud.network.VirtualRouterProvider) IPAddressVO(com.cloud.network.dao.IPAddressVO) DomainRouterVO(com.cloud.vm.DomainRouterVO) UserStatisticsVO(com.cloud.user.UserStatisticsVO) SetupGuestNetworkCommand(com.cloud.agent.api.SetupGuestNetworkCommand) VirtualMachine(com.cloud.vm.VirtualMachine)

Example 15 with VirtualMachine

use of com.cloud.vm.VirtualMachine in project cloudstack by apache.

the class AssignToLoadBalancerRuleCmd method getVmIdIpListMap.

public Map<Long, List<String>> getVmIdIpListMap() {
    Map<Long, List<String>> vmIdIpsMap = new HashMap<Long, List<String>>();
    if (vmIdIpMap != null && !vmIdIpMap.isEmpty()) {
        Collection idIpsCollection = vmIdIpMap.values();
        Iterator iter = idIpsCollection.iterator();
        while (iter.hasNext()) {
            HashMap<String, String> idIpsMap = (HashMap<String, String>) iter.next();
            String vmId = idIpsMap.get("vmid");
            String vmIp = idIpsMap.get("vmip");
            VirtualMachine lbvm = _entityMgr.findByUuid(VirtualMachine.class, vmId);
            if (lbvm == null) {
                throw new InvalidParameterValueException("Unable to find virtual machine ID: " + vmId);
            }
            //check wether the given ip is valid ip or not
            if (vmIp == null || !NetUtils.isValidIp(vmIp)) {
                throw new InvalidParameterValueException("Invalid ip address " + vmIp + " passed in vmidipmap for " + "vmid " + vmId);
            }
            Long longVmId = lbvm.getId();
            List<String> ipsList = null;
            if (vmIdIpsMap.containsKey(longVmId)) {
                ipsList = vmIdIpsMap.get(longVmId);
            } else {
                ipsList = new ArrayList<String>();
            }
            ipsList.add(vmIp);
            vmIdIpsMap.put(longVmId, ipsList);
        }
    }
    return vmIdIpsMap;
}
Also used : HashMap(java.util.HashMap) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Iterator(java.util.Iterator) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) VirtualMachine(com.cloud.vm.VirtualMachine)

Aggregations

VirtualMachine (com.cloud.vm.VirtualMachine)65 ArrayList (java.util.ArrayList)17 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)16 HostVO (com.cloud.host.HostVO)15 DataCenter (com.cloud.dc.DataCenter)10 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)10 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)10 ServiceOffering (com.cloud.offering.ServiceOffering)9 HashMap (java.util.HashMap)9 List (java.util.List)9 ServerApiException (org.apache.cloudstack.api.ServerApiException)9 Test (org.junit.Test)9 Host (com.cloud.host.Host)8 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 ServerApiException (com.cloud.api.ServerApiException)7 NicProfile (com.cloud.vm.NicProfile)7 VMInstanceVO (com.cloud.vm.VMInstanceVO)7 SystemVmResponse (org.apache.cloudstack.api.response.SystemVmResponse)7 SystemVmResponse (com.cloud.api.response.SystemVmResponse)6 ManagementServerException (com.cloud.exception.ManagementServerException)6