Search in sources :

Example 26 with ReservationContext

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

the class NetworkOrchestrator method destroyNetwork.

@Override
@DB
public boolean destroyNetwork(final long networkId, final ReservationContext context, final boolean forced) {
    final Account callerAccount = context.getAccount();
    NetworkVO network = _networksDao.findById(networkId);
    if (network == null) {
        s_logger.debug("Unable to find network with id: " + networkId);
        return false;
    }
    // Make sure that there are no user vms in the network that are not Expunged/Error
    final List<UserVmVO> userVms = _userVmDao.listByNetworkIdAndStates(networkId);
    for (final UserVmVO vm : userVms) {
        if (!(vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null)) {
            s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state");
            return false;
        }
    }
    // Don't allow to delete network via api call when it has vms assigned to it
    final int nicCount = getActiveNicsInNetwork(networkId);
    if (nicCount > 0) {
        s_logger.debug("The network id=" + networkId + " has active Nics, but shouldn't.");
        // at this point we have already determined that there are no active user vms in network
        // if the op_networks table shows active nics, it's a bug in releasing nics updating op_networks
        _networksDao.changeActiveNicsBy(networkId, -1 * nicCount);
    }
    // In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network
    final Zone zone = _zoneRepository.findOne(network.getDataCenterId());
    if (zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Basic) {
        final List<VMInstanceVO> systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm);
        if (systemVms != null && !systemVms.isEmpty()) {
            s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged");
            return false;
        }
    }
    // Shutdown network first
    shutdownNetwork(networkId, context, false);
    // get updated state for the network
    network = _networksDao.findById(networkId);
    if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) {
        s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState());
        return false;
    }
    boolean success = true;
    if (!cleanupNetworkResources(networkId, callerAccount, context.getCaller().getId())) {
        s_logger.warn("Unable to delete network id=" + networkId + ": failed to cleanup network resources");
        return false;
    }
    // get providers to destroy
    final List<Provider> providersToDestroy = getNetworkProviders(network.getId());
    for (final NetworkElement element : networkElements) {
        if (providersToDestroy.contains(element.getProvider())) {
            try {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Sending destroy to " + element);
                }
                if (!element.destroy(network, context)) {
                    success = false;
                    s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName());
                }
            } catch (final ResourceUnavailableException e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            } catch (final ConcurrentOperationException e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            } catch (final Exception e) {
                s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
                success = false;
            }
        }
    }
    if (success) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now.");
        }
        final NetworkVO networkFinal = network;
        try {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
                    // Deleting sync networks
                    final List<NetworkVO> syncNetworks = _networksDao.listSyncNetworksByRelatedNetwork(networkId);
                    syncNetworks.forEach(syncNetwork -> removeAndShutdownSyncNetwork(syncNetwork.getId()));
                    guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()));
                    if (!deleteVlansInNetwork(networkFinal.getId(), context.getCaller().getId(), callerAccount)) {
                        s_logger.warn("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
                        throw new CloudRuntimeException("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
                    } else {
                        // commit transaction only when ips and vlans for the network are released successfully
                        try {
                            stateTransitTo(networkFinal, Event.DestroyNetwork);
                        } catch (final NoTransitionException e) {
                            s_logger.debug(e.getMessage());
                        }
                        if (_networksDao.remove(networkFinal.getId())) {
                            final NetworkDomainVO networkDomain = _networkDomainDao.getDomainNetworkMapByNetworkId(networkFinal.getId());
                            if (networkDomain != null) {
                                _networkDomainDao.remove(networkDomain.getId());
                            }
                            final NetworkAccountVO networkAccount = _networkAccountDao.getAccountNetworkMapByNetworkId(networkFinal.getId());
                            if (networkAccount != null) {
                                _networkAccountDao.remove(networkAccount.getId());
                            }
                        }
                        final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId());
                        final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType());
                        if (updateResourceCount) {
                            _resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork());
                        }
                    }
                }
            });
            if (_networksDao.findById(network.getId()) == null) {
                // remove its related ACL permission
                final Pair<Class<?>, Long> networkMsg = new Pair<>(Network.class, networkFinal.getId());
                _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
            }
            return true;
        } catch (final CloudRuntimeException e) {
            s_logger.error("Failed to delete network", e);
            return false;
        }
    }
    return success;
}
Also used : PhysicalNetworkTrafficTypeDao(com.cloud.network.dao.PhysicalNetworkTrafficTypeDao) NetworkModel(com.cloud.network.NetworkModel) ConfigKey(com.cloud.framework.config.ConfigKey) HostDao(com.cloud.host.dao.HostDao) VMNetworkMapVO(com.cloud.engine.cloud.entity.api.db.VMNetworkMapVO) ACLType(com.cloud.acl.ControlledEntity.ACLType) PodVlanMapDao(com.cloud.dc.dao.PodVlanMapDao) Scope(com.cloud.framework.config.ConfigKey.Scope) Transaction(com.cloud.utils.db.Transaction) TransactionCallbackWithExceptionNoReturn(com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn) ConnectionException(com.cloud.exception.ConnectionException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) AgentManager(com.cloud.agent.AgentManager) PhysicalNetworkTrafficTypeVO(com.cloud.network.dao.PhysicalNetworkTrafficTypeVO) ReservationContext(com.cloud.vm.ReservationContext) VlanDao(com.cloud.dc.dao.VlanDao) Map(java.util.Map) NetworkServiceMapDao(com.cloud.network.dao.NetworkServiceMapDao) TrafficType(com.cloud.network.Networks.TrafficType) ZoneRepository(com.cloud.db.repository.ZoneRepository) StaticNatRule(com.cloud.network.rules.StaticNatRule) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) Service(com.cloud.network.Network.Service) PhysicalNetworkDao(com.cloud.network.dao.PhysicalNetworkDao) AgentControlCommand(com.cloud.agent.api.AgentControlCommand) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkGuru(com.cloud.network.guru.NetworkGuru) DataCenterVnetVO(com.cloud.dc.DataCenterVnetVO) Network(com.cloud.network.Network) TransactionStatus(com.cloud.utils.db.TransactionStatus) Set(java.util.Set) NetworkElement(com.cloud.network.element.NetworkElement) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) Executors(java.util.concurrent.Executors) GuestType(com.cloud.network.Network.GuestType) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) PortForwardingRulesDao(com.cloud.network.rules.dao.PortForwardingRulesDao) IllegalVirtualMachineException(com.cloud.exception.IllegalVirtualMachineException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StaticNatRuleImpl(com.cloud.network.rules.StaticNatRuleImpl) AccountDao(com.cloud.user.dao.AccountDao) AdapterBase(com.cloud.utils.component.AdapterBase) IpAddressManager(com.cloud.network.IpAddressManager) Event(com.cloud.network.Network.Event) NumbersUtil(com.cloud.utils.NumbersUtil) ManagerBase(com.cloud.utils.component.ManagerBase) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) FirewallRule(com.cloud.network.rules.FirewallRule) CallContext(com.cloud.context.CallContext) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Zone(com.cloud.db.model.Zone) Purpose(com.cloud.network.rules.FirewallRule.Purpose) IpDeployer(com.cloud.network.element.IpDeployer) NetworkOfferingServiceMapDao(com.cloud.offerings.dao.NetworkOfferingServiceMapDao) NicProfile(com.cloud.vm.NicProfile) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) VlanVO(com.cloud.dc.VlanVO) ConfigurationDao(com.cloud.framework.config.dao.ConfigurationDao) DomainRouterVO(com.cloud.vm.DomainRouterVO) User(com.cloud.user.User) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) VMInstanceDao(com.cloud.vm.dao.VMInstanceDao) DomainRouterDao(com.cloud.vm.dao.DomainRouterDao) MessageBus(com.cloud.framework.messagebus.MessageBus) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) Op(com.cloud.utils.db.SearchCriteria.Op) EntityManager(com.cloud.dao.EntityManager) NicTO(com.cloud.agent.api.to.NicTO) Vlan(com.cloud.dc.Vlan) Vpc(com.cloud.network.vpc.Vpc) UserVmDao(com.cloud.vm.dao.UserVmDao) CheckNetworkAnswer(com.cloud.agent.api.CheckNetworkAnswer) NicDao(com.cloud.vm.dao.NicDao) StartupRoutingCommand(com.cloud.agent.api.StartupRoutingCommand) PhysicalNetwork(com.cloud.network.PhysicalNetwork) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) DB(com.cloud.utils.db.DB) Command(com.cloud.agent.api.Command) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) Host(com.cloud.host.Host) GlobalLock(com.cloud.utils.db.GlobalLock) NetworkOfferingDetailsDao(com.cloud.offerings.dao.NetworkOfferingDetailsDao) RulesManager(com.cloud.network.rules.RulesManager) NicSecondaryIpDao(com.cloud.vm.dao.NicSecondaryIpDao) AggregatedCommandExecutor(com.cloud.network.element.AggregatedCommandExecutor) LoggerFactory(org.slf4j.LoggerFactory) NetworkType(com.cloud.model.enumeration.NetworkType) Networks(com.cloud.network.Networks) NetworkAccountVO(com.cloud.network.dao.NetworkAccountVO) AlertManager(com.cloud.alert.AlertManager) CheckNetworkCommand(com.cloud.agent.api.CheckNetworkCommand) ResourceType(com.cloud.configuration.Resource.ResourceType) StartupCommand(com.cloud.agent.api.StartupCommand) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) NetworkMigrationResponder(com.cloud.network.NetworkMigrationResponder) DeploymentPlan(com.cloud.deploy.DeploymentPlan) VMNetworkMapDao(com.cloud.engine.cloud.entity.api.db.dao.VMNetworkMapDao) ResourceLimitService(com.cloud.user.ResourceLimitService) Answer(com.cloud.agent.api.Answer) URI(java.net.URI) NetworkProfile(com.cloud.network.NetworkProfile) PhysicalNetworkSetupInfo(com.cloud.network.PhysicalNetworkSetupInfo) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PublishScope(com.cloud.framework.messagebus.PublishScope) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionCallback(com.cloud.utils.db.TransactionCallback) StateMachine2(com.cloud.utils.fsm.StateMachine2) DeployDestination(com.cloud.deploy.DeployDestination) IpAddress(com.cloud.network.IpAddress) VpcVirtualNetworkApplianceService(com.cloud.network.VpcVirtualNetworkApplianceService) AccountGuestVlanMapVO(com.cloud.network.dao.AccountGuestVlanMapVO) Account(com.cloud.user.Account) Type(com.cloud.vm.VirtualMachine.Type) Pair(com.cloud.utils.Pair) NicVO(com.cloud.vm.NicVO) UUID(java.util.UUID) VpcManager(com.cloud.network.vpc.VpcManager) Scheme(com.cloud.network.rules.LoadBalancerContainer.Scheme) PodVlanMapVO(com.cloud.dc.PodVlanMapVO) Status(com.cloud.host.Status) List(java.util.List) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) NetworkOfferingServiceMapVO(com.cloud.offerings.NetworkOfferingServiceMapVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) NetUtils(com.cloud.utils.net.NetUtils) NetworkServiceMapVO(com.cloud.network.dao.NetworkServiceMapVO) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) Capability(com.cloud.network.Network.Capability) NetworkDomainDao(com.cloud.network.dao.NetworkDomainDao) RedundantState(com.cloud.network.router.VirtualRouter.RedundantState) DataCenterVnetDao(com.cloud.dc.dao.DataCenterVnetDao) VirtualMachine(com.cloud.vm.VirtualMachine) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) BroadcastDomainType(com.cloud.network.Networks.BroadcastDomainType) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ReservationStrategy(com.cloud.vm.Nic.ReservationStrategy) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) SearchBuilder(com.cloud.utils.db.SearchBuilder) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) Configurable(com.cloud.framework.config.Configurable) HashMap(java.util.HashMap) Domain(com.cloud.domain.Domain) NetworkDao(com.cloud.network.dao.NetworkDao) ConfigurationException(javax.naming.ConfigurationException) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) JoinType(com.cloud.utils.db.JoinBuilder.JoinType) Nic(com.cloud.vm.Nic) Inject(javax.inject.Inject) HashSet(java.util.HashSet) Listener(com.cloud.agent.Listener) IPAddressVO(com.cloud.network.dao.IPAddressVO) NetworkVO(com.cloud.network.dao.NetworkVO) PhysicalNetworkServiceProviderDao(com.cloud.network.dao.PhysicalNetworkServiceProviderDao) IPAddressDao(com.cloud.network.dao.IPAddressDao) FirewallRulesDao(com.cloud.network.dao.FirewallRulesDao) NamedThreadFactory(com.cloud.utils.concurrency.NamedThreadFactory) DataCenter(com.cloud.dc.DataCenter) PublicIp(com.cloud.network.addr.PublicIp) ManagedContextRunnable(com.cloud.managed.context.ManagedContextRunnable) ConfigurationManager(com.cloud.configuration.ConfigurationManager) LoadBalancingRulesManager(com.cloud.network.lb.LoadBalancingRulesManager) Logger(org.slf4j.Logger) NetworkACLManager(com.cloud.network.vpc.NetworkACLManager) PrivateIpDao(com.cloud.network.vpc.dao.PrivateIpDao) AccountGuestVlanMapDao(com.cloud.network.dao.AccountGuestVlanMapDao) NetworkOffering(com.cloud.offering.NetworkOffering) TimeUnit(java.util.concurrent.TimeUnit) UserVmVO(com.cloud.vm.UserVmVO) RemoteAccessVpnService(com.cloud.network.vpn.RemoteAccessVpnService) NetworkOfferingDao(com.cloud.offerings.dao.NetworkOfferingDao) NetworkAccountDao(com.cloud.network.dao.NetworkAccountDao) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) Provider(com.cloud.network.Network.Provider) FirewallManager(com.cloud.network.rules.FirewallManager) NicSecondaryIpVO(com.cloud.vm.dao.NicSecondaryIpVO) Comparator(java.util.Comparator) Collections(java.util.Collections) Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkElement(com.cloud.network.element.NetworkElement) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) Zone(com.cloud.db.model.Zone) NetworkGuru(com.cloud.network.guru.NetworkGuru) VMInstanceVO(com.cloud.vm.VMInstanceVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConnectionException(com.cloud.exception.ConnectionException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) IllegalVirtualMachineException(com.cloud.exception.IllegalVirtualMachineException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) UserDataServiceProvider(com.cloud.network.element.UserDataServiceProvider) LoadBalancingServiceProvider(com.cloud.network.element.LoadBalancingServiceProvider) StaticNatServiceProvider(com.cloud.network.element.StaticNatServiceProvider) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) Provider(com.cloud.network.Network.Provider) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkAccountVO(com.cloud.network.dao.NetworkAccountVO) DB(com.cloud.utils.db.DB)

Example 27 with ReservationContext

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

the class NiciraNvpGuestNetworkGuruTest method testImplement.

@Test
public void testImplement() throws InsufficientVirtualNetworkCapacityException {
    final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
    when(physnetdao.findById((Long) any())).thenReturn(physnet);
    when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "STT", "VXLAN" }));
    when(physnet.getId()).thenReturn(NETWORK_ID);
    final NiciraNvpDeviceVO device = mock(NiciraNvpDeviceVO.class);
    when(nvpdao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(Arrays.asList(new NiciraNvpDeviceVO[] { device }));
    when(device.getId()).thenReturn(1L);
    final NetworkOffering offering = mock(NetworkOffering.class);
    when(offering.getId()).thenReturn(NETWORK_ID);
    when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
    when(offering.getGuestType()).thenReturn(GuestType.Isolated);
    when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
    mock(DeploymentPlan.class);
    final NetworkVO network = mock(NetworkVO.class);
    when(network.getName()).thenReturn("testnetwork");
    when(network.getState()).thenReturn(Network.State.Implementing);
    when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
    final DeployDestination dest = mock(DeployDestination.class);
    final Zone zone = mock(Zone.class);
    when(dest.getZone()).thenReturn(zone);
    final HostVO niciraHost = mock(HostVO.class);
    when(hostdao.findById(anyLong())).thenReturn(niciraHost);
    when(niciraHost.getDetail("transportzoneuuid")).thenReturn("aaaa");
    when(niciraHost.getDetail("transportzoneisotype")).thenReturn("stt");
    when(niciraHost.getId()).thenReturn(NETWORK_ID);
    when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
    final Domain dom = mock(Domain.class);
    when(dom.getName()).thenReturn("domain");
    final Account acc = mock(Account.class);
    when(acc.getAccountName()).thenReturn("accountname");
    final ReservationContext res = mock(ReservationContext.class);
    when(res.getDomain()).thenReturn(dom);
    when(res.getAccount()).thenReturn(acc);
    final CreateLogicalSwitchAnswer answer = mock(CreateLogicalSwitchAnswer.class);
    when(answer.getResult()).thenReturn(true);
    when(answer.getLogicalSwitchUuid()).thenReturn("aaaaa");
    when(agentmgr.easySend(eq(NETWORK_ID), any())).thenReturn(answer);
    final Network implementednetwork = guru.implement(network, offering, dest, res);
    assertTrue(implementednetwork != null);
    verify(agentmgr, times(1)).easySend(eq(NETWORK_ID), any());
}
Also used : Account(com.cloud.user.Account) NetworkVO(com.cloud.network.dao.NetworkVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) CreateLogicalSwitchAnswer(com.cloud.agent.api.CreateLogicalSwitchAnswer) NetworkOffering(com.cloud.offering.NetworkOffering) Zone(com.cloud.db.model.Zone) NiciraNvpDeviceVO(com.cloud.network.NiciraNvpDeviceVO) HostVO(com.cloud.host.HostVO) ReservationContext(com.cloud.vm.ReservationContext) DeployDestination(com.cloud.deploy.DeployDestination) Network(com.cloud.network.Network) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) Domain(com.cloud.domain.Domain) Test(org.junit.Test)

Example 28 with ReservationContext

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

the class VirtualNetworkApplianceManagerImpl method startRouter.

@Override
public VirtualRouter startRouter(final long routerId, final boolean reprogramNetwork) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException {
    final Account caller = CallContext.current().getCallingAccount();
    final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    // verify parameters
    DomainRouterVO router = _routerDao.findById(routerId);
    if (router == null) {
        throw new InvalidParameterValueException("Unable to find router by id " + routerId + ".");
    }
    _accountMgr.checkAccess(caller, null, true, router);
    final Account owner = _accountMgr.getAccount(router.getAccountId());
    // Check if all networks are implemented for the domR; if not -
    // implement them
    final Zone zone = zoneRepository.findOne(router.getDataCenterId());
    HostPodVO pod = null;
    if (router.getPodIdToDeployIn() != null) {
        pod = _podDao.findById(router.getPodIdToDeployIn());
    }
    final DeployDestination dest = new DeployDestination(zone, pod, null, null);
    final ReservationContext context = new ReservationContextImpl(null, null, callerUser, owner);
    final List<NicVO> nics = _nicDao.listByVmId(routerId);
    for (final NicVO nic : nics) {
        if (!_networkMgr.startNetwork(nic.getNetworkId(), dest, context)) {
            s_logger.warn("Failed to start network id=" + nic.getNetworkId() + " as a part of domR start");
            throw new CloudRuntimeException("Failed to start network id=" + nic.getNetworkId() + " as a part of domR start");
        }
    }
    // After start network, check if it's already running
    router = _routerDao.findById(routerId);
    if (router.getState() == VirtualMachine.State.Running) {
        return router;
    }
    final UserVO user = _userDao.findById(CallContext.current().getCallingUserId());
    final Map<Param, Object> params = new HashMap<>();
    if (reprogramNetwork) {
        params.put(Param.ReProgramGuestNetworks, true);
    } else {
        params.put(Param.ReProgramGuestNetworks, false);
    }
    final VirtualRouter virtualRouter = _nwHelper.startVirtualRouter(router, user, caller, params);
    if (virtualRouter == null) {
        throw new CloudRuntimeException("Failed to start router with id " + routerId);
    }
    return virtualRouter;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) HashMap(java.util.HashMap) Zone(com.cloud.db.model.Zone) TimeZone(java.util.TimeZone) HostPodVO(com.cloud.dc.HostPodVO) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) UserVO(com.cloud.user.UserVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Param(com.cloud.vm.VirtualMachineProfile.Param) NicVO(com.cloud.vm.NicVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 29 with ReservationContext

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

the class VpcManagerImpl method restartVpc.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_RESTART, eventDescription = "restarting vpc")
public boolean restartVpc(final long vpcId, final boolean cleanUp) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final Account callerAccount = CallContext.current().getCallingAccount();
    final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    final ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
    // Verify input parameters
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    _accountMgr.checkAccess(callerAccount, null, false, vpc);
    s_logger.debug("Restarting VPC " + vpc);
    boolean restartRequired = false;
    try {
        if (cleanUp) {
            List<DomainRouterVO> routers = _routerDao.listByVpcId(vpc.getId());
            if (routers != null && !routers.isEmpty()) {
                s_logger.debug("Shutting down VPC " + vpc + " as a part of VPC restart process");
                // Get rid of any non-Running routers
                for (final DomainRouterVO router : routers) {
                    if (router.getState() != VirtualMachine.State.Running) {
                        s_logger.debug("Destroying " + router + " as it is not in Running state anyway");
                        _routerMgr.destroyRouter(router.getId(), context.getAccount(), context.getCaller().getId());
                    }
                }
                // Refresh the list of routers
                routers = _routerDao.listByVpcId(vpc.getId());
                if (routers != null && !routers.isEmpty()) {
                    if (!rollingRestartVpc(vpc, routers, context)) {
                        s_logger.warn("Failed to execute a rolling restart as a part of VPC " + vpc + " restart process");
                        restartRequired = true;
                        return false;
                    }
                }
            }
        } else {
            s_logger.info("Will not shutdown vpc as a part of VPC " + vpc + " restart process.");
        }
        s_logger.debug("Starting VPC " + vpc + " as a part of VPC restart process");
        if (!startVpc(vpcId, false)) {
            s_logger.warn("Failed to start vpc as a part of VPC " + vpc + " restart process");
            restartRequired = true;
            return false;
        }
        s_logger.debug("VPC " + vpc + " was restarted successfully");
        return true;
    } finally {
        s_logger.debug("Updating VPC " + vpc + " with restartRequired=" + restartRequired);
        final VpcVO vo = _vpcDao.findById(vpcId);
        vo.setRestartRequired(restartRequired);
        _vpcDao.update(vpc.getId(), vo);
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) DomainRouterVO(com.cloud.vm.DomainRouterVO) ReservationContext(com.cloud.vm.ReservationContext) ActionEvent(com.cloud.event.ActionEvent)

Example 30 with ReservationContext

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

the class VpcManagerImpl method startVpc.

@Override
public boolean startVpc(final long vpcId, final boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final User callerUser = _accountMgr.getActiveUser(ctx.getCallingUserId());
    // check if vpc exists
    final Vpc vpc = getActiveVpc(vpcId);
    if (vpc == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find Enabled VPC by id specified");
        ex.addProxyObject(String.valueOf(vpcId), "VPC");
        throw ex;
    }
    // permission check
    _accountMgr.checkAccess(caller, null, false, vpc);
    final Zone zone = zoneRepository.findOne(vpc.getZoneId());
    final DeployDestination dest = new DeployDestination(zone, null, null, null);
    final ReservationContext context = new ReservationContextImpl(null, null, callerUser, _accountMgr.getAccount(vpc.getAccountId()));
    boolean result = true;
    try {
        if (!startVpc(vpc, dest, context)) {
            s_logger.warn("Failed to start vpc " + vpc);
            result = false;
        }
    } catch (final Exception ex) {
        s_logger.warn("Failed to start vpc " + vpc + " due to ", ex);
        result = false;
    } finally {
        // do cleanup
        if (!result && destroyOnFailure) {
            s_logger.debug("Destroying vpc " + vpc + " that failed to start");
            if (destroyVpc(vpc, caller, callerUser.getId())) {
                s_logger.warn("Successfully destroyed vpc " + vpc + " that failed to start");
            } else {
                s_logger.warn("Failed to destroy vpc " + vpc + " that failed to start");
            }
        }
    }
    return result;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) Zone(com.cloud.db.model.Zone) DeployDestination(com.cloud.deploy.DeployDestination) CallContext(com.cloud.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ServerApiException(com.cloud.api.ServerApiException) ReservationContext(com.cloud.vm.ReservationContext)

Aggregations

ReservationContext (com.cloud.vm.ReservationContext)72 Account (com.cloud.user.Account)45 ReservationContextImpl (com.cloud.vm.ReservationContextImpl)42 DeployDestination (com.cloud.deploy.DeployDestination)41 NetworkVO (com.cloud.network.dao.NetworkVO)41 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)38 Test (org.junit.Test)33 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)28 NetworkOffering (com.cloud.offering.NetworkOffering)27 Network (com.cloud.network.Network)24 Domain (com.cloud.domain.Domain)23 HostVO (com.cloud.host.HostVO)22 DataCenter (com.cloud.dc.DataCenter)21 URI (java.net.URI)19 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)17 NicProfile (com.cloud.vm.NicProfile)17 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)14 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)14 User (com.cloud.user.User)14 NicVO (com.cloud.vm.NicVO)14