Search in sources :

Example 1 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class AssociateIPAddrCmd method getEntityOwnerId.

@Override
public long getEntityOwnerId() {
    final Account caller = CallContext.current().getCallingAccount();
    if (accountName != null && domainId != null) {
        final Account account = _accountService.finalizeOwner(caller, accountName, domainId, projectId);
        return account.getId();
    } else if (projectId != null) {
        final Project project = _projectService.getProject(projectId);
        if (project != null) {
            if (project.getState() == Project.State.Active) {
                return project.getProjectAccountId();
            } else {
                throw new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active");
            }
        } else {
            throw new InvalidParameterValueException("Unable to find project by ID");
        }
    } else if (networkId != null) {
        final Network network = _networkService.getNetwork(networkId);
        if (network == null) {
            throw new InvalidParameterValueException("Unable to find network by network id specified");
        }
        final NetworkOffering offering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
        final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
        if (zone.getNetworkType() == NetworkType.Basic && offering.getElasticIp() && offering.getElasticLb()) {
            // shared network with EIP/ELB service.
            return caller.getAccountId();
        }
        return network.getAccountId();
    } else if (vpcId != null) {
        final Vpc vpc = _entityMgr.findById(Vpc.class, getVpcId());
        if (vpc == null) {
            throw new InvalidParameterValueException("Can't find enabled VPC by ID specified");
        }
        return vpc.getAccountId();
    }
    return caller.getAccountId();
}
Also used : Account(com.cloud.legacymodel.user.Account) Project(com.cloud.projects.Project) DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NetworkOffering(com.cloud.offering.NetworkOffering) Network(com.cloud.legacymodel.network.Network) Vpc(com.cloud.legacymodel.network.vpc.Vpc) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException)

Example 2 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class AssociateIPAddrCmd method getNetworkId.

public Long getNetworkId() {
    if (vpcId != null) {
        return null;
    }
    if (networkId != null) {
        return networkId;
    }
    final Long zoneId = getZoneId();
    final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if (zone.getNetworkType() == NetworkType.Advanced) {
        final List<? extends Network> networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId()));
        if (networks.size() == 0) {
            final String domain = _domainService.getDomain(getDomainId()).getName();
            throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName());
        }
        if (networks.size() < 1) {
            throw new InvalidParameterValueException("Account doesn't have any isolated networks in the zone");
        } else if (networks.size() > 1) {
            throw new InvalidParameterValueException("Account has more than one isolated network in the zone");
        }
        return networks.get(0).getId();
    } else {
        final Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId);
        if (defaultGuestNetwork == null) {
            throw new InvalidParameterValueException("Unable to find a default guest network for account " + getAccountName() + " in domain ID=" + getDomainId());
        } else {
            return defaultGuestNetwork.getId();
        }
    }
}
Also used : DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Network(com.cloud.legacymodel.network.Network)

Example 3 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

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 Zone zone = _zoneRepository.findById(destHost.getDataCenterId()).orElse(null);
    final HostPodVO pod = _podDao.findById(destHost.getPodId());
    final Cluster cluster = _clusterDao.findById(destHost.getClusterId());
    final DeployDestination destination = new DeployDestination(zone, 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 (VirtualMachineType.DomainRouter.equals(vm.getType())) {
        alertType = AlertManager.AlertType.ALERT_TYPE_DOMAIN_ROUTER_MIGRATE;
    } else if (VirtualMachineType.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);
    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
        final Nic defaultNic = _networkModel.getDefaultNic(vm.getId());
        List<String[]> vmData = null;
        if (defaultNic != null) {
            final UserVmVO userVm = _userVmDao.findById(vm.getId());
            final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(vm.getId());
            vm.setDetails(details);
            final 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();
                final 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, network);
                final String vmName = vm.getInstanceName();
                final String configDriveIsoRootFolder = "/tmp";
                final 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.
                final 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 (final 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 " + zone.getName() + " and pod " + zone.getName(), "Migrate Command failed.  Please check logs.");
            try {
                _agentMgr.send(destHostId, new Commands(cleanup(vm.getInstanceName())), null);
                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.legacymodel.exceptions.OperationTimedoutException) StoragePool(com.cloud.legacymodel.storage.StoragePool) HostPodVO(com.cloud.dc.HostPodVO) VirtualMachineTO(com.cloud.legacymodel.to.VirtualMachineTO) HypervisorGuru(com.cloud.hypervisor.HypervisorGuru) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) Commands(com.cloud.agent.manager.Commands) TimeZone(java.util.TimeZone) Zone(com.cloud.db.model.Zone) Cluster(com.cloud.legacymodel.dc.Cluster) Nic(com.cloud.legacymodel.network.Nic) HostVO(com.cloud.host.HostVO) AttachOrDettachConfigDriveCommand(com.cloud.legacymodel.communication.command.AttachOrDettachConfigDriveCommand) Volume(com.cloud.legacymodel.storage.Volume) DeployDestination(com.cloud.deploy.DeployDestination) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException)

Example 4 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method orchestrateAddVmToNetwork.

@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateAddVmToNetwork(final VmWorkAddVmToNetwork work) throws Exception {
    final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId());
    if (vm == null) {
        s_logger.info("Unable to find vm " + work.getVmId());
    }
    assert vm != null;
    final Network network = _networkDao.findById(work.getNetworkId());
    final NicProfile nic = orchestrateAddVmToNetwork(vm, network, work.getRequestedNicProfile());
    return new Pair<>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(nic));
}
Also used : Network(com.cloud.legacymodel.network.Network) Pair(com.cloud.legacymodel.utils.Pair) ReflectionUse(com.cloud.utils.ReflectionUse)

Example 5 with Network

use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.

the class DomainChecker method checkAccess.

@Override
public boolean checkAccess(final Account caller, final ControlledEntity entity, final AccessType accessType) throws PermissionDeniedException {
    if (entity instanceof VirtualMachineTemplate) {
        final VirtualMachineTemplate template = (VirtualMachineTemplate) entity;
        final Account owner = _accountDao.findById(template.getAccountId());
        // validate that the template is usable by the account
        if (!template.isPublicTemplate()) {
            if (_accountService.isRootAdmin(caller.getId()) || (owner.getId() == caller.getId())) {
                return true;
            }
            // special handling for the project case
            if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT && _projectMgr.canAccessProjectAccount(caller, owner.getId())) {
                return true;
            }
            // since the current account is not the owner of the template, check the launch permissions table to see if the
            // account can launch a VM from this template
            final LaunchPermissionVO permission = _launchPermissionDao.findByTemplateAndAccount(template.getId(), caller.getId());
            if (permission == null) {
                throw new PermissionDeniedException(caller + " does not have permission to launch instances from " + template);
            }
        } else {
            // Domain admin and regular user can delete/modify only templates created by them
            if (accessType != null && accessType == AccessType.OperateEntry) {
                if (!_accountService.isRootAdmin(caller.getId()) && owner.getId() != caller.getId()) {
                    // For projects check if the caller account can access the project account
                    if (owner.getType() != Account.ACCOUNT_TYPE_PROJECT || !(_projectMgr.canAccessProjectAccount(caller, owner.getId()))) {
                        throw new PermissionDeniedException("Domain Admin and regular users can modify only their own Public templates");
                    }
                }
            }
        }
        return true;
    } else if (entity instanceof Network && accessType != null && accessType == AccessType.UseEntry) {
        _networkMgr.checkNetworkPermissions(caller, (Network) entity);
    } else if (entity instanceof AffinityGroup) {
        return false;
    } else {
        if (_accountService.isNormalUser(caller.getId())) {
            final Account account = _accountDao.findById(entity.getAccountId());
            if (account != null && account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
                // only project owner can delete/modify the project
                if (accessType != null && accessType == AccessType.ModifyProject) {
                    if (!_projectMgr.canModifyProjectAccount(caller, account.getId())) {
                        throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity);
                    }
                } else if (!_projectMgr.canAccessProjectAccount(caller, account.getId())) {
                    throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity);
                }
            } else {
                if (caller.getId() != entity.getAccountId()) {
                    throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity);
                }
            }
        }
    }
    return true;
}
Also used : Account(com.cloud.legacymodel.user.Account) VirtualMachineTemplate(com.cloud.legacymodel.storage.VirtualMachineTemplate) Network(com.cloud.legacymodel.network.Network) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) AffinityGroup(com.cloud.affinity.AffinityGroup) LaunchPermissionVO(com.cloud.storage.LaunchPermissionVO)

Aggregations

Network (com.cloud.legacymodel.network.Network)160 ArrayList (java.util.ArrayList)57 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)56 Account (com.cloud.legacymodel.user.Account)46 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)42 NetworkOffering (com.cloud.offering.NetworkOffering)36 PhysicalNetwork (com.cloud.network.PhysicalNetwork)34 IPAddressVO (com.cloud.network.dao.IPAddressVO)32 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)30 NetworkVO (com.cloud.network.dao.NetworkVO)28 List (java.util.List)28 Zone (com.cloud.db.model.Zone)27 DB (com.cloud.utils.db.DB)27 NicProfile (com.cloud.vm.NicProfile)26 Nic (com.cloud.legacymodel.network.Nic)21 DataCenter (com.cloud.legacymodel.dc.DataCenter)20 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)20 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)19 DomainRouterVO (com.cloud.vm.DomainRouterVO)18 ActionEvent (com.cloud.event.ActionEvent)17