Search in sources :

Example 36 with ConsoleProxyVO

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

the class ConsoleProxyManagerImpl method startNew.

public ConsoleProxyVO startNew(long dataCenterId) throws ConcurrentOperationException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Assign console proxy from a newly started instance for request from data center : " + dataCenterId);
    }
    if (!allowToLaunchNew(dataCenterId)) {
        String configKey = Config.ConsoleProxyLaunchMax.key();
        s_logger.warn(String.format("The number of launched console proxys on zone [%s] has reached the limit [%s]. Limit set in [%s].", dataCenterId, configurationDao.getValue(configKey), configKey));
        return null;
    }
    HypervisorType availableHypervisor = resourceManager.getAvailableHypervisor(dataCenterId);
    VMTemplateVO template = vmTemplateDao.findSystemVMReadyTemplate(dataCenterId, availableHypervisor);
    if (template == null) {
        throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
    }
    Map<String, Object> context = createProxyInstance(dataCenterId, template);
    long proxyVmId = (Long) context.get("proxyVmId");
    if (proxyVmId == 0) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(String.format("Unable to create proxy instance in zone [%s].", dataCenterId));
        }
        return null;
    }
    ConsoleProxyVO proxy = consoleProxyDao.findById(proxyVmId);
    if (proxy != null) {
        SubscriptionMgr.getInstance().notifySubscribers(ConsoleProxyManager.ALERT_SUBJECT, this, new ConsoleProxyAlertEventArgs(ConsoleProxyAlertEventArgs.PROXY_CREATED, dataCenterId, proxy.getId(), proxy, null));
        return proxy;
    } else {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to allocate console proxy storage, remove the console proxy record from DB, proxy id: " + proxyVmId);
        }
    }
    return null;
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VMTemplateVO(com.cloud.storage.VMTemplateVO) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO)

Example 37 with ConsoleProxyVO

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

the class ConsoleProxyManagerImpl method assignProxyFromRunningPool.

public ConsoleProxyVO assignProxyFromRunningPool(long dataCenterId) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Assign console proxy from running pool for request from data center : " + dataCenterId);
    }
    ConsoleProxyAllocator allocator = getCurrentAllocator();
    assert (allocator != null);
    List<ConsoleProxyVO> runningList = consoleProxyDao.getProxyListInStates(dataCenterId, State.Running);
    if (runningList != null && runningList.size() > 0) {
        Iterator<ConsoleProxyVO> it = runningList.iterator();
        while (it.hasNext()) {
            ConsoleProxyVO proxy = it.next();
            if (proxy.getActiveSession() >= capacityPerProxy) {
                it.remove();
            }
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(String.format("Running [%s] proxy instances [%s].", runningList.size(), runningList.stream().map(proxy -> proxy.toString()).collect(Collectors.joining(", "))));
        }
        List<Pair<Long, Integer>> l = consoleProxyDao.getProxyLoadMatrix();
        Map<Long, Integer> loadInfo = new HashMap<>();
        if (l != null) {
            for (Pair<Long, Integer> p : l) {
                Long proxyId = p.first();
                Integer countRunningVms = p.second();
                loadInfo.put(proxyId, countRunningVms);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug(String.format("Running proxy instance allocation {\"proxyId\": %s, \"countRunningVms\": %s}.", proxyId, countRunningVms));
                }
            }
        }
        Long allocated = allocator.allocProxy(runningList, loadInfo, dataCenterId);
        if (allocated == null) {
            s_logger.debug(String.format("Console proxy not found, unable to assign console proxy from running pool for request from zone [%s].", dataCenterId));
            return null;
        }
        return consoleProxyDao.findById(allocated);
    } else {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Empty running proxy pool for now in data center : " + dataCenterId);
        }
    }
    return null;
}
Also used : RunningHostInfoAgregator(com.cloud.info.RunningHostInfoAgregator) NetworkModel(com.cloud.network.NetworkModel) Arrays(java.util.Arrays) HostDao(com.cloud.host.dao.HostDao) Transaction(com.cloud.utils.db.Transaction) TemplateDataStoreDao(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreDao) ConsoleProxyLoadAnswer(com.cloud.agent.api.proxy.ConsoleProxyLoadAnswer) AgentManager(com.cloud.agent.AgentManager) GsonBuilder(com.google.gson.GsonBuilder) ServiceOfferingDao(com.cloud.service.dao.ServiceOfferingDao) ReservationContext(com.cloud.vm.ReservationContext) Map(java.util.Map) TrafficType(com.cloud.network.Networks.TrafficType) Storage(com.cloud.storage.Storage) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) CheckSshCommand(com.cloud.agent.api.check.CheckSshCommand) SubscriptionMgr(com.cloud.utils.events.SubscriptionMgr) CallContext(org.apache.cloudstack.context.CallContext) ResourceManager(com.cloud.resource.ResourceManager) Network(com.cloud.network.Network) TransactionStatus(com.cloud.utils.db.TransactionStatus) Set(java.util.Set) KeystoreManager(org.apache.cloudstack.framework.security.keystore.KeystoreManager) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) ConsoleProxyConnectionInfo(com.cloud.info.ConsoleProxyConnectionInfo) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServiceOffering(com.cloud.offering.ServiceOffering) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) NumbersUtil(com.cloud.utils.NumbersUtil) ManagerBase(com.cloud.utils.component.ManagerBase) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VMTemplateDao(com.cloud.storage.dao.VMTemplateDao) DataCenterVO(com.cloud.dc.DataCenterVO) BooleanUtils(org.apache.commons.lang3.BooleanUtils) SystemVmLoadScanner(com.cloud.vm.SystemVmLoadScanner) ArrayList(java.util.ArrayList) NicProfile(com.cloud.vm.NicProfile) LinkedHashMap(java.util.LinkedHashMap) ConsoleProxyLoadInfo(com.cloud.info.ConsoleProxyLoadInfo) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO) NetworkType(com.cloud.dc.DataCenter.NetworkType) ConfigurationManagerImpl(com.cloud.configuration.ConfigurationManagerImpl) VMInstanceDao(com.cloud.vm.dao.VMInstanceDao) KeystoreDao(org.apache.cloudstack.framework.security.keystore.KeystoreDao) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) QueryBuilder(com.cloud.utils.db.QueryBuilder) Op(com.cloud.utils.db.SearchCriteria.Op) DB(com.cloud.utils.db.DB) ClusterManager(com.cloud.cluster.ClusterManager) StartupProxyCommand(com.cloud.agent.api.StartupProxyCommand) HostPodDao(com.cloud.dc.dao.HostPodDao) Host(com.cloud.host.Host) AccountManager(com.cloud.user.AccountManager) GlobalLock(com.cloud.utils.db.GlobalLock) ConsoleProxyDao(com.cloud.vm.dao.ConsoleProxyDao) ConfigurationDao(org.apache.cloudstack.framework.config.dao.ConfigurationDao) RulesManager(com.cloud.network.rules.RulesManager) Date(java.util.Date) StoragePoolStatus(com.cloud.storage.StoragePoolStatus) ResourceStateAdapter(com.cloud.resource.ResourceStateAdapter) ServerResource(com.cloud.resource.ServerResource) Logger(org.apache.log4j.Logger) StartupCommand(com.cloud.agent.api.StartupCommand) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) Gson(com.google.gson.Gson) Answer(com.cloud.agent.api.Answer) ZoneConfig(com.cloud.configuration.ZoneConfig) ConsoleProxyStatus(com.cloud.info.ConsoleProxyStatus) ConsoleProxyInfo(com.cloud.info.ConsoleProxyInfo) Config(com.cloud.configuration.Config) StringUtils(com.cloud.utils.StringUtils) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PrimaryDataStoreDao(org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao) VirtualMachineGuru(com.cloud.vm.VirtualMachineGuru) RunningHostCountInfo(com.cloud.info.RunningHostCountInfo) VMInstanceVO(com.cloud.vm.VMInstanceVO) State(com.cloud.vm.VirtualMachine.State) DeployDestination(com.cloud.deploy.DeployDestination) Commands(com.cloud.agent.manager.Commands) KeystoreVO(org.apache.cloudstack.framework.security.keystore.KeystoreVO) Account(com.cloud.user.Account) Pair(com.cloud.utils.Pair) Collectors(java.util.stream.Collectors) ConsoleProxyLoadReportCommand(com.cloud.agent.api.ConsoleProxyLoadReportCommand) List(java.util.List) KeysManager(org.apache.cloudstack.framework.security.keys.KeysManager) DataCenterDao(com.cloud.dc.dao.DataCenterDao) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) NetUtils(com.cloud.utils.net.NetUtils) AfterScanAction(com.cloud.vm.SystemVmLoadScanner.AfterScanAction) Status(com.cloud.storage.VMTemplateStorageResourceAssoc.Status) JsonParseException(com.google.gson.JsonParseException) VirtualMachine(com.cloud.vm.VirtualMachine) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) RebootCommand(com.cloud.agent.api.RebootCommand) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) VirtualMachineName(com.cloud.vm.VirtualMachineName) HashMap(java.util.HashMap) ConfigurationException(javax.naming.ConfigurationException) NetworkDao(com.cloud.network.dao.NetworkDao) Inject(javax.inject.Inject) ConfigKey(org.apache.cloudstack.framework.config.ConfigKey) HashSet(java.util.HashSet) SystemVmLoadScanHandler(com.cloud.vm.SystemVmLoadScanHandler) Charset(java.nio.charset.Charset) CollectionUtils(org.apache.commons.collections.CollectionUtils) IPAddressVO(com.cloud.network.dao.IPAddressVO) UserVmDetailsDao(com.cloud.vm.dao.UserVmDetailsDao) NetworkVO(com.cloud.network.dao.NetworkVO) Configurable(org.apache.cloudstack.framework.config.Configurable) IPAddressDao(com.cloud.network.dao.IPAddressDao) IndirectAgentLB(org.apache.cloudstack.agent.lb.IndirectAgentLB) ZoneHostInfo(com.cloud.info.RunningHostInfoAgregator.ZoneHostInfo) DataCenter(com.cloud.dc.DataCenter) HostVO(com.cloud.host.HostVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) Iterator(java.util.Iterator) Type(com.cloud.host.Host.Type) DateUtil(com.cloud.utils.DateUtil) NetworkOffering(com.cloud.offering.NetworkOffering) HostPodVO(com.cloud.dc.HostPodVO) DataStoreRole(com.cloud.storage.DataStoreRole) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) NetworkOfferingDao(com.cloud.offerings.dao.NetworkOfferingDao) UnableDeleteHostException(com.cloud.resource.UnableDeleteHostException) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) Pair(com.cloud.utils.Pair)

Example 38 with ConsoleProxyVO

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

the class ApiResponseHelper method createSystemVmResponse.

@Override
public SystemVmResponse createSystemVmResponse(VirtualMachine vm) {
    SystemVmResponse vmResponse = new SystemVmResponse();
    if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy || vm.getType() == Type.DomainRouter || vm.getType() == Type.NetScalerVm) {
        vmResponse.setId(vm.getUuid());
        vmResponse.setSystemVmType(vm.getType().toString().toLowerCase());
        vmResponse.setName(vm.getHostName());
        if (vm.getPodIdToDeployIn() != null) {
            HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn());
            if (pod != null) {
                vmResponse.setPodId(pod.getUuid());
                vmResponse.setPodName(pod.getName());
            }
        }
        VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId());
        if (template != null) {
            vmResponse.setTemplateId(template.getUuid());
            vmResponse.setTemplateName(template.getName());
        }
        vmResponse.setCreated(vm.getCreated());
        if (vm.getHostId() != null) {
            Host host = ApiDBUtils.findHostById(vm.getHostId());
            if (host != null) {
                vmResponse.setHostId(host.getUuid());
                vmResponse.setHostName(host.getName());
                vmResponse.setHypervisor(host.getHypervisorType().toString());
            }
        } else if (vm.getLastHostId() != null) {
            Host lastHost = ApiDBUtils.findHostById(vm.getLastHostId());
            if (lastHost != null) {
                vmResponse.setHypervisor(lastHost.getHypervisorType().toString());
            }
        }
        if (VirtualMachine.systemVMs.contains(vm.getType())) {
            Host systemVmHost = ApiDBUtils.findHostByTypeNameAndZoneId(vm.getDataCenterId(), vm.getHostName(), Type.SecondaryStorageVm.equals(vm.getType()) ? Host.Type.SecondaryStorageVM : Host.Type.ConsoleProxy);
            if (systemVmHost != null) {
                vmResponse.setAgentState(systemVmHost.getStatus());
                vmResponse.setDisconnectedOn(systemVmHost.getDisconnectedOn());
                vmResponse.setVersion(systemVmHost.getVersion());
            }
        }
        if (vm.getState() != null) {
            vmResponse.setState(vm.getState().toString());
        }
        vmResponse.setDynamicallyScalable(vm.isDynamicallyScalable());
        // for console proxies, add the active sessions
        if (vm.getType() == Type.ConsoleProxy) {
            ConsoleProxyVO proxy = ApiDBUtils.findConsoleProxy(vm.getId());
            // proxy can be already destroyed
            if (proxy != null) {
                vmResponse.setActiveViewerSessions(proxy.getActiveSession());
            }
        }
        DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterId());
        if (zone != null) {
            vmResponse.setZoneId(zone.getUuid());
            vmResponse.setZoneName(zone.getName());
            vmResponse.setDns1(zone.getDns1());
            vmResponse.setDns2(zone.getDns2());
        }
        vmResponse.setHasAnnotation(annotationDao.hasAnnotations(vm.getUuid(), AnnotationService.EntityType.SYSTEM_VM.name(), _accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())));
        List<NicProfile> nicProfiles = ApiDBUtils.getNics(vm);
        for (NicProfile singleNicProfile : nicProfiles) {
            Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId());
            if (network != null) {
                if (network.getTrafficType() == TrafficType.Management) {
                    vmResponse.setPrivateIp(singleNicProfile.getIPv4Address());
                    vmResponse.setPrivateMacAddress(singleNicProfile.getMacAddress());
                    vmResponse.setPrivateNetmask(singleNicProfile.getIPv4Netmask());
                } else if (network.getTrafficType() == TrafficType.Control) {
                    vmResponse.setLinkLocalIp(singleNicProfile.getIPv4Address());
                    vmResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress());
                    vmResponse.setLinkLocalNetmask(singleNicProfile.getIPv4Netmask());
                } else if (network.getTrafficType() == TrafficType.Public) {
                    vmResponse.setPublicIp(singleNicProfile.getIPv4Address());
                    vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress());
                    vmResponse.setPublicNetmask(singleNicProfile.getIPv4Netmask());
                    vmResponse.setGateway(singleNicProfile.getIPv4Gateway());
                } else if (network.getTrafficType() == TrafficType.Guest) {
                    /*
                          * In basic zone, public ip has TrafficType.Guest in case EIP service is not enabled.
                          * When EIP service is enabled in the basic zone, system VM by default get the public
                          * IP allocated for EIP. So return the guest/public IP accordingly.
                          * */
                    NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId());
                    if (networkOffering.isElasticIp()) {
                        IpAddress ip = ApiDBUtils.findIpByAssociatedVmId(vm.getId());
                        if (ip != null) {
                            Vlan vlan = ApiDBUtils.findVlanById(ip.getVlanId());
                            vmResponse.setPublicIp(ip.getAddress().addr());
                            vmResponse.setPublicNetmask(vlan.getVlanNetmask());
                            vmResponse.setGateway(vlan.getVlanGateway());
                        }
                    } else {
                        vmResponse.setPublicIp(singleNicProfile.getIPv4Address());
                        vmResponse.setPublicMacAddress(singleNicProfile.getMacAddress());
                        vmResponse.setPublicNetmask(singleNicProfile.getIPv4Netmask());
                        vmResponse.setGateway(singleNicProfile.getIPv4Gateway());
                    }
                }
            }
        }
    }
    vmResponse.setObjectName("systemvm");
    return vmResponse;
}
Also used : SystemVmResponse(org.apache.cloudstack.api.response.SystemVmResponse) DataCenter(com.cloud.dc.DataCenter) NetworkOffering(com.cloud.offering.NetworkOffering) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) VMTemplateVO(com.cloud.storage.VMTemplateVO) ManagementServerHost(org.apache.cloudstack.management.ManagementServerHost) Host(com.cloud.host.Host) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) IpAddress(com.cloud.network.IpAddress) Vlan(com.cloud.dc.Vlan) GuestVlan(com.cloud.network.GuestVlan) NicProfile(com.cloud.vm.NicProfile) HostPodVO(com.cloud.dc.HostPodVO)

Example 39 with ConsoleProxyVO

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

the class ConsoleProxyAlertAdapter method onProxyAlert.

public void onProxyAlert(Object sender, ConsoleProxyAlertEventArgs args) {
    if (s_logger.isDebugEnabled())
        s_logger.debug("received console proxy alert");
    DataCenterVO dc = _dcDao.findById(args.getZoneId());
    ConsoleProxyVO proxy = args.getProxy();
    // FIXME - Proxy can be null in case of creation failure. Have a better fix than checking for != 0
    if (proxy == null && args.getProxyId() != 0)
        proxy = _consoleProxyDao.findById(args.getProxyId());
    if (proxy == null && args.getType() != ConsoleProxyAlertEventArgs.PROXY_CREATE_FAILURE) {
        throw new CloudRuntimeException("Invalid alert arguments, proxy must be set");
    }
    switch(args.getType()) {
        case ConsoleProxyAlertEventArgs.PROXY_CREATED:
            if (s_logger.isDebugEnabled())
                s_logger.debug("New console proxy created, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + proxy.getPrivateIpAddress());
            break;
        case ConsoleProxyAlertEventArgs.PROXY_UP:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy is up, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + proxy.getPrivateIpAddress());
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy up in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy up (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_DOWN:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy is down, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()));
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy down in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy down (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_REBOOTED:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy is rebooted, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()));
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy rebooted in zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy rebooted (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_CREATE_FAILURE:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy creation failure, zone: " + dc.getName());
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), null, "Console proxy creation failure. zone: " + dc.getName() + ", error details: " + args.getMessage(), "Console proxy creation failure (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_START_FAILURE:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy startup failure, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()));
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy startup failure. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()) + ", error details: " + args.getMessage(), "Console proxy startup failure (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_FIREWALL_ALERT:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy firewall alert, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()));
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_CONSOLE_PROXY, args.getZoneId(), proxy.getPodIdToDeployIn(), "Failed to open console proxy firewall port. zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + (proxy.getPrivateIpAddress() == null ? "N/A" : proxy.getPrivateIpAddress()), "Console proxy alert (zone " + dc.getName() + ")");
            break;
        case ConsoleProxyAlertEventArgs.PROXY_STORAGE_ALERT:
            if (s_logger.isDebugEnabled())
                s_logger.debug("Console proxy storage alert, zone: " + dc.getName() + ", proxy: " + proxy.getHostName() + ", public IP: " + proxy.getPublicIpAddress() + ", private IP: " + proxy.getPrivateIpAddress() + ", message: " + args.getMessage());
            _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_STORAGE_MISC, args.getZoneId(), proxy.getPodIdToDeployIn(), "Console proxy storage issue. zone: " + dc.getName() + ", message: " + args.getMessage(), "Console proxy alert (zone " + dc.getName() + ")");
            break;
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO)

Example 40 with ConsoleProxyVO

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

the class StoragePoolAutomationImpl method maintain.

@Override
public boolean maintain(DataStore store) {
    Long userId = CallContext.current().getCallingUserId();
    User user = _userDao.findById(userId);
    Account account = CallContext.current().getCallingAccount();
    StoragePoolVO pool = primaryDataStoreDao.findById(store.getId());
    try {
        List<StoragePoolVO> spes = null;
        // if the storage is ZONE wide then we pass podid and cluster id as null as they will be empty for ZWPS
        if (pool.getScope() == ScopeType.ZONE) {
            spes = primaryDataStoreDao.listBy(pool.getDataCenterId(), null, null, ScopeType.ZONE);
        } else {
            spes = primaryDataStoreDao.listBy(pool.getDataCenterId(), pool.getPodId(), pool.getClusterId(), ScopeType.CLUSTER);
        }
        for (StoragePoolVO sp : spes) {
            if (sp.getParent() != pool.getParent() && sp.getId() != pool.getParent()) {
                // If Datastore cluster is tried to prepare for maintenance then child storage pools are also kept in PrepareForMaintenance mode
                if (sp.getStatus() == StoragePoolStatus.PrepareForMaintenance) {
                    throw new CloudRuntimeException("Only one storage pool in a cluster can be in PrepareForMaintenance mode, " + sp.getId() + " is already in  PrepareForMaintenance mode ");
                }
            }
        }
        StoragePool storagePool = (StoragePool) store;
        // Handeling the Zone wide and cluster wide primay storage
        List<HostVO> hosts = new ArrayList<HostVO>();
        // TODO: if it's zone wide, this code will list a lot of hosts in the zone, which may cause performance/OOM issue.
        if (pool.getScope().equals(ScopeType.ZONE)) {
            if (HypervisorType.Any.equals(pool.getHypervisor())) {
                hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZone(pool.getDataCenterId());
            } else {
                hosts = _resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(pool.getHypervisor(), pool.getDataCenterId());
            }
        } else {
            hosts = _resourceMgr.listHostsInClusterByStatus(pool.getClusterId(), Status.Up);
        }
        if (hosts == null || hosts.size() == 0) {
            pool.setStatus(StoragePoolStatus.Maintenance);
            primaryDataStoreDao.update(pool.getId(), pool);
            return true;
        } else {
            // set the pool state to prepare for maintenance
            pool.setStatus(StoragePoolStatus.PrepareForMaintenance);
            primaryDataStoreDao.update(pool.getId(), pool);
        }
        // remove heartbeat
        for (HostVO host : hosts) {
            ModifyStoragePoolCommand cmd = new ModifyStoragePoolCommand(false, storagePool);
            final Answer answer = agentMgr.easySend(host.getId(), cmd);
            if (answer == null || !answer.getResult()) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("ModifyStoragePool false failed due to " + ((answer == null) ? "answer null" : answer.getDetails()));
                }
            } else {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("ModifyStoragePool false succeeded");
                }
                if (pool.getPoolType() == Storage.StoragePoolType.DatastoreCluster) {
                    s_logger.debug(String.format("Started synchronising datastore cluster storage pool %s with vCenter", pool.getUuid()));
                    storageManager.syncDatastoreClusterStoragePool(pool.getId(), ((ModifyStoragePoolAnswer) answer).getDatastoreClusterChildren(), host.getId());
                }
            }
        }
        // check to see if other ps exist
        // if they do, then we can migrate over the system vms to them
        // if they dont, then just stop all vms on this one
        List<StoragePoolVO> upPools = primaryDataStoreDao.listByStatusInZone(pool.getDataCenterId(), StoragePoolStatus.Up);
        boolean restart = true;
        if (upPools == null || upPools.size() == 0) {
            restart = false;
        }
        // 2. Get a list of all the ROOT volumes within this storage pool
        List<VolumeVO> allVolumes = volumeDao.findByPoolId(pool.getId());
        // 3. Enqueue to the work queue
        for (VolumeVO volume : allVolumes) {
            VMInstanceVO vmInstance = vmDao.findById(volume.getInstanceId());
            if (vmInstance == null) {
                continue;
            }
            // enqueue sp work
            if (vmInstance.getState().equals(State.Running) || vmInstance.getState().equals(State.Starting) || vmInstance.getState().equals(State.Stopping)) {
                try {
                    StoragePoolWorkVO work = new StoragePoolWorkVO(vmInstance.getId(), pool.getId(), false, false, server.getId());
                    _storagePoolWorkDao.persist(work);
                } catch (Exception e) {
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Work record already exists, re-using by re-setting values");
                    }
                    StoragePoolWorkVO work = _storagePoolWorkDao.findByPoolIdAndVmId(pool.getId(), vmInstance.getId());
                    work.setStartedAfterMaintenance(false);
                    work.setStoppedForMaintenance(false);
                    work.setManagementServerId(server.getId());
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
        }
        // 4. Process the queue
        List<StoragePoolWorkVO> pendingWork = _storagePoolWorkDao.listPendingWorkForPrepareForMaintenanceByPoolId(pool.getId());
        for (StoragePoolWorkVO work : pendingWork) {
            // shut down the running vms
            VMInstanceVO vmInstance = vmDao.findById(work.getVmId());
            if (vmInstance == null) {
                continue;
            }
            // proxy
            if (vmInstance.getType().equals(VirtualMachine.Type.ConsoleProxy)) {
                // call the consoleproxymanager
                ConsoleProxyVO consoleProxy = _consoleProxyDao.findById(vmInstance.getId());
                vmMgr.advanceStop(consoleProxy.getUuid(), false);
                // update work status
                work.setStoppedForMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
                if (restart) {
                    vmMgr.advanceStart(consoleProxy.getUuid(), null, null);
                    // update work status
                    work.setStartedAfterMaintenance(true);
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
            // if the instance is of type uservm, call the user vm manager
            if (vmInstance.getType() == VirtualMachine.Type.User) {
                UserVmVO userVm = userVmDao.findById(vmInstance.getId());
                vmMgr.advanceStop(userVm.getUuid(), false);
                // update work status
                work.setStoppedForMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
            }
            // secondary storage vm manager
            if (vmInstance.getType().equals(VirtualMachine.Type.SecondaryStorageVm)) {
                SecondaryStorageVmVO secStrgVm = _secStrgDao.findById(vmInstance.getId());
                vmMgr.advanceStop(secStrgVm.getUuid(), false);
                // update work status
                work.setStoppedForMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
                if (restart) {
                    vmMgr.advanceStart(secStrgVm.getUuid(), null, null);
                    // update work status
                    work.setStartedAfterMaintenance(true);
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
            // manager
            if (vmInstance.getType().equals(VirtualMachine.Type.DomainRouter)) {
                DomainRouterVO domR = _domrDao.findById(vmInstance.getId());
                vmMgr.advanceStop(domR.getUuid(), false);
                // update work status
                work.setStoppedForMaintenance(true);
                _storagePoolWorkDao.update(work.getId(), work);
                if (restart) {
                    vmMgr.advanceStart(domR.getUuid(), null, null);
                    // update work status
                    work.setStartedAfterMaintenance(true);
                    _storagePoolWorkDao.update(work.getId(), work);
                }
            }
        }
    } catch (Exception e) {
        s_logger.error("Exception in enabling primary storage maintenance:", e);
        pool.setStatus(StoragePoolStatus.ErrorInMaintenance);
        primaryDataStoreDao.update(pool.getId(), pool);
        throw new CloudRuntimeException(e.getMessage());
    }
    return true;
}
Also used : Account(com.cloud.user.Account) SecondaryStorageVmVO(com.cloud.vm.SecondaryStorageVmVO) UserVmVO(com.cloud.vm.UserVmVO) User(com.cloud.user.User) ArrayList(java.util.ArrayList) VMInstanceVO(com.cloud.vm.VMInstanceVO) HostVO(com.cloud.host.HostVO) ModifyStoragePoolCommand(com.cloud.agent.api.ModifyStoragePoolCommand) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ModifyStoragePoolAnswer(com.cloud.agent.api.ModifyStoragePoolAnswer) Answer(com.cloud.agent.api.Answer) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ConsoleProxyVO(com.cloud.vm.ConsoleProxyVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Aggregations

ConsoleProxyVO (com.cloud.vm.ConsoleProxyVO)41 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)15 NicProfile (com.cloud.vm.NicProfile)9 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)8 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)8 HostVO (com.cloud.host.HostVO)8 Answer (com.cloud.agent.api.Answer)7 Account (com.cloud.user.Account)7 VMInstanceVO (com.cloud.vm.VMInstanceVO)7 ArrayList (java.util.ArrayList)7 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)6 CheckSshAnswer (com.cloud.agent.api.check.CheckSshAnswer)5 HostPodVO (com.cloud.dc.HostPodVO)5 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)5 Network (com.cloud.network.Network)5 NetworkOffering (com.cloud.offering.NetworkOffering)5 VMTemplateVO (com.cloud.storage.VMTemplateVO)5 ModifyStoragePoolCommand (com.cloud.agent.api.ModifyStoragePoolCommand)4 Zone (com.cloud.db.model.Zone)4 DataCenter (com.cloud.dc.DataCenter)4