Search in sources :

Example 76 with Network

use of com.cloud.network.Network in project cloudstack by apache.

the class NetworkACLManagerImpl method applyACLToNetwork.

@Override
public boolean applyACLToNetwork(final long networkId) throws ResourceUnavailableException {
    final Network network = _networkDao.findById(networkId);
    if (network.getNetworkACLId() == null) {
        return true;
    }
    final List<NetworkACLItemVO> rules = _networkACLItemDao.listByACL(network.getNetworkACLId());
    return applyACLItemsToNetwork(networkId, rules);
}
Also used : Network(com.cloud.network.Network)

Example 77 with Network

use of com.cloud.network.Network in project cloudstack by apache.

the class NetworkACLManagerImpl method revokeACLItemsForNetwork.

@Override
public boolean revokeACLItemsForNetwork(final long networkId) throws ResourceUnavailableException {
    final Network network = _networkDao.findById(networkId);
    if (network.getNetworkACLId() == null) {
        return true;
    }
    final List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(network.getNetworkACLId());
    if (aclItems.isEmpty()) {
        s_logger.debug("Found no network ACL Items for network id=" + networkId);
        return true;
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Releasing " + aclItems.size() + " Network ACL Items for network id=" + networkId);
    }
    for (final NetworkACLItemVO aclItem : aclItems) {
        // Mark all Network ACLs rules as Revoke, but don't update in DB
        if (aclItem.getState() == State.Add || aclItem.getState() == State.Active) {
            aclItem.setState(State.Revoke);
        }
    }
    final boolean success = applyACLItemsToNetwork(network.getId(), aclItems);
    if (s_logger.isDebugEnabled() && success) {
        s_logger.debug("Successfully released Network ACLs for network id=" + networkId + " and # of rules now = " + aclItems.size());
    }
    return success;
}
Also used : Network(com.cloud.network.Network)

Example 78 with Network

use of com.cloud.network.Network in project cloudstack by apache.

the class NicPlugInOutRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    Pair<Map<String, PublicIpAddress>, Map<String, PublicIpAddress>> nicsToChange = getNicsToChangeOnRouter(visitor);
    Map<String, PublicIpAddress> nicsToPlug = nicsToChange.first();
    Map<String, PublicIpAddress> nicsToUnplug = nicsToChange.second();
    NetworkModel networkModel = visitor.getVirtualNetworkApplianceFactory().getNetworkModel();
    VirtualMachineManager itMgr = visitor.getVirtualNetworkApplianceFactory().getItMgr();
    // 1) Unplug the nics
    for (Entry<String, PublicIpAddress> entry : nicsToUnplug.entrySet()) {
        Network publicNtwk = null;
        try {
            publicNtwk = networkModel.getNetwork(entry.getValue().getNetworkId());
            URI broadcastUri = BroadcastDomainType.Vlan.toUri(entry.getKey());
            itMgr.removeVmFromNetwork(_router, publicNtwk, broadcastUri);
        } catch (ConcurrentOperationException e) {
            s_logger.warn("Failed to remove router " + _router + " from vlan " + entry.getKey() + " in public network " + publicNtwk + " due to ", e);
            return false;
        }
    }
    _netUsageCommands = new Commands(Command.OnError.Continue);
    VpcDao vpcDao = visitor.getVirtualNetworkApplianceFactory().getVpcDao();
    VpcVO vpc = vpcDao.findById(_router.getVpcId());
    // 2) Plug the nics
    for (String vlanTag : nicsToPlug.keySet()) {
        PublicIpAddress ip = nicsToPlug.get(vlanTag);
        // have to plug the nic(s)
        NicProfile defaultNic = new NicProfile();
        if (ip.isSourceNat()) {
            defaultNic.setDefaultNic(true);
        }
        defaultNic.setIPv4Address(ip.getAddress().addr());
        defaultNic.setIPv4Gateway(ip.getGateway());
        defaultNic.setIPv4Netmask(ip.getNetmask());
        defaultNic.setMacAddress(ip.getMacAddress());
        defaultNic.setBroadcastType(BroadcastDomainType.Vlan);
        defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag()));
        defaultNic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
        NicProfile publicNic = null;
        Network publicNtwk = null;
        try {
            publicNtwk = networkModel.getNetwork(ip.getNetworkId());
            publicNic = itMgr.addVmToNetwork(_router, publicNtwk, defaultNic);
        } catch (ConcurrentOperationException e) {
            s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk + " due to ", e);
        } catch (InsufficientCapacityException e) {
            s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk + " due to ", e);
        } finally {
            if (publicNic == null) {
                s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk);
                return false;
            }
        }
        // Create network usage commands. Send commands to router after
        // IPAssoc
        NetworkUsageCommand netUsageCmd = new NetworkUsageCommand(_router.getPrivateIpAddress(), _router.getInstanceName(), true, defaultNic.getIPv4Address(), vpc.getCidr());
        _netUsageCommands.addCommand(netUsageCmd);
        UserStatisticsDao userStatsDao = visitor.getVirtualNetworkApplianceFactory().getUserStatsDao();
        UserStatisticsVO stats = userStatsDao.findBy(_router.getAccountId(), _router.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), _router.getId(), _router.getType().toString());
        if (stats == null) {
            stats = new UserStatisticsVO(_router.getAccountId(), _router.getDataCenterId(), publicNic.getIPv4Address(), _router.getId(), _router.getType().toString(), publicNtwk.getId());
            userStatsDao.persist(stats);
        }
    }
    // VpcIpAssociation is done.
    return true;
}
Also used : NetworkUsageCommand(com.cloud.agent.api.NetworkUsageCommand) NicProfile(com.cloud.vm.NicProfile) URI(java.net.URI) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UserStatisticsDao(com.cloud.user.dao.UserStatisticsDao) PublicIpAddress(com.cloud.network.PublicIpAddress) VpcDao(com.cloud.network.vpc.dao.VpcDao) VpcVO(com.cloud.network.vpc.VpcVO) Network(com.cloud.network.Network) Commands(com.cloud.agent.manager.Commands) NetworkModel(com.cloud.network.NetworkModel) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) HashMap(java.util.HashMap) Map(java.util.Map) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Example 79 with Network

use of com.cloud.network.Network in project cloudstack by apache.

the class RulesManagerImpl method getSystemIpAndEnableStaticNatForVm.

@Override
public void getSystemIpAndEnableStaticNatForVm(VirtualMachine vm, boolean getNewIp) throws InsufficientAddressCapacityException {
    boolean success = true;
    // enable static nat if eIp capability is supported
    List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
    for (Nic nic : nics) {
        Network guestNetwork = _networkModel.getNetwork(nic.getNetworkId());
        NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, guestNetwork.getNetworkOfferingId());
        if (offering.getElasticIp()) {
            boolean isSystemVM = (vm.getType() == Type.ConsoleProxy || vm.getType() == Type.SecondaryStorageVm);
            // for user VM's associate public IP only if offering is marked to associate a public IP by default on start of VM
            if (!isSystemVM && !offering.getAssociatePublicIP()) {
                continue;
            }
            // check if there is already static nat enabled
            if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
                s_logger.debug("Vm " + vm + " already has ip associated with it in guest network " + guestNetwork);
                continue;
            }
            s_logger.debug("Allocating system ip and enabling static nat for it for the vm " + vm + " in guest network " + guestNetwork);
            IpAddress ip = _ipAddrMgr.assignSystemIp(guestNetwork.getId(), _accountMgr.getAccount(vm.getAccountId()), false, true);
            if (ip == null) {
                throw new CloudRuntimeException("Failed to allocate system ip for vm " + vm + " in guest network " + guestNetwork);
            }
            s_logger.debug("Allocated system ip " + ip + ", now enabling static nat on it for vm " + vm);
            try {
                success = enableStaticNat(ip.getId(), vm.getId(), guestNetwork.getId(), isSystemVM, null);
            } catch (NetworkRuleConflictException ex) {
                s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
                success = false;
            } catch (ResourceUnavailableException ex) {
                s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
                success = false;
            }
            if (!success) {
                s_logger.warn("Failed to enable static nat on system ip " + ip + " for the vm " + vm + ", releasing the ip...");
                _ipAddrMgr.handleSystemIpRelease(ip);
                throw new CloudRuntimeException("Failed to enable static nat on system ip for the vm " + vm);
            } else {
                s_logger.warn("Succesfully enabled static nat on system ip " + ip + " for the vm " + vm);
            }
        }
    }
}
Also used : NetworkOffering(com.cloud.offering.NetworkOffering) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Nic(com.cloud.vm.Nic) IpAddress(com.cloud.network.IpAddress) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException)

Example 80 with Network

use of com.cloud.network.Network in project cloudstack by apache.

the class VirtualMachineManagerImpl method orchestrateMigrateWithStorage.

private void orchestrateMigrateWithStorage(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException {
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final HostVO srcHost = _hostDao.findById(srcHostId);
    final HostVO destHost = _hostDao.findById(destHostId);
    final VirtualMachineGuru vmGuru = getVmGuru(vm);
    final DataCenterVO dc = _dcDao.findById(destHost.getDataCenterId());
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(dc, pod, cluster, destHost);
    // Create a map of which volume should go in which storage pool.
    final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
    final Map<Volume, StoragePool> volumeToPoolMap = getPoolListForVolumesForMigration(profile, destHost, volumeToPool);
    // a vm and not migrating a vm with storage.
    if (volumeToPoolMap == null || volumeToPoolMap.isEmpty()) {
        throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destHost + " doesn't involve migrating the volumes.");
    }
    AlertManager.AlertType alertType = AlertManager.AlertType.ALERT_TYPE_USERVM_MIGRATE;
    if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY_MIGRATE;
    }
    _networkMgr.prepareNicForMigration(profile, destination);
    volumeMgr.prepareForMigration(profile, destination);
    final HypervisorGuru hvGuru = _hvGuruMgr.getGuru(vm.getHypervisorType());
    final VirtualMachineTO to = hvGuru.implement(profile);
    ItWorkVO work = new ItWorkVO(UUID.randomUUID().toString(), _nodeId, State.Migrating, vm.getType(), vm.getId());
    work.setStep(Step.Prepare);
    work.setResourceType(ItWorkVO.ResourceType.Host);
    work.setResourceId(destHostId);
    work = _workDao.persist(work);
    // Put the vm in migrating state.
    vm.setLastHostId(srcHostId);
    vm.setPodIdToDeployIn(destHost.getPodId());
    moveVmToMigratingState(vm, destHostId, work);
    boolean migrated = false;
    try {
        // config drive: Detach the config drive at source host
        // After migration successful attach the config drive in destination host
        // On migration failure VM will be stopped, So configIso will be deleted
        Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            UserVmVO userVm = _userVmDao.findById(vm.getId());
            Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            Network network = _networkModel.getNetwork(defaultNic.getNetworkId());
            if (_networkModel.isSharedNetworkWithoutServices(network.getId())) {
                final String serviceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId()).getDisplayText();
                final String zoneName = _dcDao.findById(vm.getDataCenterId()).getName();
                boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(vm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows");
                vmData = _networkModel.generateVmData(userVm.getUserData(), serviceOffering, zoneName, vm.getInstanceName(), vm.getId(), (String) profile.getParameter(VirtualMachineProfile.Param.VmSshPubKey), (String) profile.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows);
                String vmName = vm.getInstanceName();
                String configDriveIsoRootFolder = "/tmp";
                String isoFile = configDriveIsoRootFolder + "/" + vmName + "/configDrive/" + vmName + ".iso";
                profile.setVmData(vmData);
                profile.setConfigDriveLabel(VmConfigDriveLabel.value());
                profile.setConfigDriveIsoRootFolder(configDriveIsoRootFolder);
                profile.setConfigDriveIsoFile(isoFile);
                // At source host detach the config drive iso.
                AttachOrDettachConfigDriveCommand dettachCommand = new AttachOrDettachConfigDriveCommand(vm.getInstanceName(), vmData, VmConfigDriveLabel.value(), false);
                try {
                    _agentMgr.send(srcHost.getId(), dettachCommand);
                    s_logger.debug("Deleted config drive ISO for  vm " + vm.getInstanceName() + " In host " + srcHost);
                } catch (OperationTimedoutException e) {
                    s_logger.debug("TIme out occured while exeuting command AttachOrDettachConfigDrive " + e.getMessage());
                }
            }
        }
        // Migrate the vm and its volume.
        volumeMgr.migrateVolumes(vm, to, srcHost, destHost, volumeToPoolMap);
        // Put the vm back to running state.
        moveVmOutofMigratingStateOnSuccess(vm, destHost.getId(), work);
        try {
            if (!checkVmOnHost(vm, destHostId)) {
                s_logger.error("Vm not found on destination host. Unable to complete migration for " + vm);
                try {
                    _agentMgr.send(srcHostId, new Commands(cleanup(vm.getInstanceName())), null);
                } catch (final AgentUnavailableException e) {
                    s_logger.error("AgentUnavailableException while cleanup on source host: " + srcHostId);
                }
                cleanup(vmGuru, new VirtualMachineProfileImpl(vm), work, Event.AgentReportStopped, true);
                throw new CloudRuntimeException("VM not found on desintation host. Unable to complete migration for " + vm);
            }
        } catch (final OperationTimedoutException e) {
            s_logger.warn("Error while checking the vm " + vm + " is on host " + destHost, e);
        }
        migrated = true;
    } finally {
        if (!migrated) {
            s_logger.info("Migration was unsuccessful.  Cleaning up: " + vm);
            _alertMgr.sendAlert(alertType, srcHost.getDataCenterId(), srcHost.getPodId(), "Unable to migrate vm " + vm.getInstanceName() + " from host " + srcHost.getName() + " in zone " + dc.getName() + " and pod " + dc.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                vm.setPodIdToDeployIn(srcHost.getPodId());
                stateTransitTo(vm, Event.OperationFailed, srcHostId);
            } catch (final AgentUnavailableException e) {
                s_logger.warn("Looks like the destination Host is unavailable for cleanup.", e);
            } catch (final NoTransitionException e) {
                s_logger.error("Error while transitioning vm from migrating to running state.", e);
            }
        }
        work.setStep(Step.Done);
        _workDao.update(work.getId(), work);
    }
}
Also used : AlertManager(com.cloud.alert.AlertManager) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) StoragePool(com.cloud.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.agent.api.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) Commands(com.cloud.agent.manager.Commands) DataCenterVO(com.cloud.dc.DataCenterVO) Cluster(com.cloud.org.Cluster) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.agent.api.AttachOrDettachConfigDriveCommand) Volume(com.cloud.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.utils.fsm.NoTransitionException)

Aggregations

Network (com.cloud.network.Network)235 ArrayList (java.util.ArrayList)86 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)63 Account (com.cloud.user.Account)60 Test (org.junit.Test)55 NetworkOffering (com.cloud.offering.NetworkOffering)52 PhysicalNetwork (com.cloud.network.PhysicalNetwork)50 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)50 NetworkVO (com.cloud.network.dao.NetworkVO)38 DataCenter (com.cloud.dc.DataCenter)34 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)31 NicProfile (com.cloud.vm.NicProfile)31 HostVO (com.cloud.host.HostVO)27 DB (com.cloud.utils.db.DB)27 List (java.util.List)27 DataCenterVO (com.cloud.dc.DataCenterVO)26 IPAddressVO (com.cloud.network.dao.IPAddressVO)25 HashMap (java.util.HashMap)24 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)23 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)20