diff --git a/plugins/network-elements/elastic-loadbalancer/pom.xml b/plugins/network-elements/elastic-loadbalancer/pom.xml deleted file mode 100644 index e2b13b7613..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/pom.xml +++ /dev/null @@ -1,11 +0,0 @@ - - 4.0.0 - cloud-plugin-network-elb - Cosmic Plugin - Network Elastic Load Balancer - - cloud.cosmic - cosmic-plugins - 5.1.0.0-SNAPSHOT - ../../pom.xml - - \ No newline at end of file diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/ElasticLbVmMapVO.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/ElasticLbVmMapVO.java deleted file mode 100644 index 835dc5448f..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/ElasticLbVmMapVO.java +++ /dev/null @@ -1,98 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.SecondaryTable; -import javax.persistence.SecondaryTables; -import javax.persistence.Table; - -import org.apache.cloudstack.api.InternalIdentity; - -import com.cloud.utils.net.Ip; - -@Entity -@Table(name = ("elastic_lb_vm_map")) -@SecondaryTables({@SecondaryTable(name = "user_ip_address", pkJoinColumns = {@PrimaryKeyJoinColumn(name = "ip_addr_id", referencedColumnName = "id")})}) -public class ElasticLbVmMapVO implements InternalIdentity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private Long id; - - @Column(name = "lb_id") - private Long lbId; - - @Column(name = "ip_addr_id") - private long ipAddressId; - - @Column(name = "elb_vm_id") - private long elbVmId; - - /*@Column(name = "name", table = "load_balancing_rules", insertable = false, updatable = false) - private String lbName;*/ - - @Column(name = "public_ip_address", table = "user_ip_address", insertable = false, updatable = false) - @Enumerated(value = EnumType.STRING) - private Ip address = null; - - public ElasticLbVmMapVO() { - } - - public ElasticLbVmMapVO(long ipId, long elbVmId, long lbId) { - this.ipAddressId = ipId; - this.elbVmId = elbVmId; - this.lbId = lbId; - } - - @Override - public long getId() { - return id; - } - - public long getLbId() { - return lbId; - } - - public long getElbVmId() { - return elbVmId; - } - -// public String getLbName() { -// return lbName; -// } - - public long getIpAddressId() { - return ipAddressId; - } - - public void setLbId(Long lbId) { - this.lbId = lbId; - } - - public Ip getAddress() { - return address; - } - -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/element/ElasticLoadBalancerElement.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/element/ElasticLoadBalancerElement.java deleted file mode 100644 index db15717d88..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/element/ElasticLoadBalancerElement.java +++ /dev/null @@ -1,225 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.element; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; - -import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.configuration.Config; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.IllegalVirtualMachineException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.PublicIpAddress; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.lb.ElasticLoadBalancerManager; -import com.cloud.network.lb.LoadBalancingRule; -import com.cloud.network.rules.LoadBalancerContainer; -import com.cloud.offering.NetworkOffering; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.utils.component.AdapterBase; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -@Component -public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalancingServiceProvider, IpDeployer { - private static final Logger s_logger = Logger.getLogger(ElasticLoadBalancerElement.class); - private static final Map> capabilities = setCapabilities(); - @Inject - NetworkModel _networkManager; - @Inject - ElasticLoadBalancerManager _lbMgr; - @Inject - ConfigurationDao _configDao; - @Inject - NetworkOfferingDao _networkOfferingDao; - @Inject - NetworkDao _networksDao; - - boolean _enabled; - TrafficType _frontEndTrafficType = TrafficType.Guest; - - private boolean canHandle(Network network, List rules) { - if (network.getGuestType() != Network.GuestType.Shared || network.getTrafficType() != TrafficType.Guest) { - s_logger.debug("Not handling network with type " + network.getGuestType() + " and traffic type " + network.getTrafficType()); - return false; - } - - Map lbCaps = this.getCapabilities().get(Service.Lb); - if (!lbCaps.isEmpty()) { - String schemeCaps = lbCaps.get(Capability.LbSchemes); - if (schemeCaps != null) { - for (LoadBalancingRule rule : rules) { - if (!schemeCaps.contains(rule.getScheme().toString())) { - s_logger.debug("Scheme " + rules.get(0).getScheme() + " is not supported by the provider " + this.getName()); - return false; - } - } - } - } - - return true; - } - - @Override - public Provider getProvider() { - return Provider.ElasticLoadBalancerVm; - } - - @Override - public Map> getCapabilities() { - return capabilities; - } - - private static Map> setCapabilities() { - Map> capabilities = new HashMap>(); - - Map lbCapabilities = new HashMap(); - lbCapabilities.put(Capability.SupportedLBAlgorithms, "roundrobin,leastconn,source"); - lbCapabilities.put(Capability.SupportedLBIsolation, "shared"); - lbCapabilities.put(Capability.SupportedProtocols, "tcp, udp"); - lbCapabilities.put(Capability.LbSchemes, LoadBalancerContainer.Scheme.Public.toString()); - - capabilities.put(Service.Lb, lbCapabilities); - return capabilities; - } - - @Override - public boolean implement(Network network, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException, InsufficientCapacityException { - - return true; - } - - @Override - public boolean prepare(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) - throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException, IllegalVirtualMachineException { - - return true; - } - - @Override - public boolean release(Network network, NicProfile nic, VirtualMachineProfile vm, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - - return true; - } - - @Override - public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO kill all loadbalancer vms by calling the ElasticLoadBalancerManager - return false; - } - - @Override - public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - // TODO kill all loadbalancer vms by calling the ElasticLoadBalancerManager - return false; - } - - @Override - public boolean validateLBRule(Network network, LoadBalancingRule rule) { - return true; - } - - @Override - public boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException { - if (!canHandle(network, rules)) { - return false; - } - - return _lbMgr.applyLoadBalancerRules(network, rules); - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - - super.configure(name, params); - String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); - _enabled = (enabled == null) ? false : Boolean.parseBoolean(enabled); - if (_enabled) { - String traffType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key()); - if ("guest".equalsIgnoreCase(traffType)) { - _frontEndTrafficType = TrafficType.Guest; - } else if ("public".equalsIgnoreCase(traffType)) { - _frontEndTrafficType = TrafficType.Public; - } else - throw new ConfigurationException("Traffic type for front end of load balancer has to be guest or public; found : " + traffType); - } - return true; - } - - @Override - public boolean isReady(PhysicalNetworkServiceProvider provider) { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean shutdownProviderInstances(PhysicalNetworkServiceProvider provider, ReservationContext context) throws ConcurrentOperationException, - ResourceUnavailableException { - // TODO Auto-generated method stub - return true; - } - - @Override - public boolean canEnableIndividualServices() { - return false; - } - - @Override - public boolean verifyServicesCombination(Set services) { - return true; - } - - @Override - public boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException { - // TODO Auto-generated method stub - return false; - } - - @Override - public IpDeployer getIpDeployer(Network network) { - return this; - } - - @Override - public List updateHealthChecks(Network network, List lbrules) { - return null; - } - -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManager.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManager.java deleted file mode 100644 index f885f7e101..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManager.java +++ /dev/null @@ -1,40 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.lb; - -import java.util.List; - -import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; - -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.Network; -import com.cloud.network.rules.LoadBalancer; -import com.cloud.user.Account; - -public interface ElasticLoadBalancerManager { - public static final int DEFAULT_ELB_VM_RAMSIZE = 128; // 512 MB - public static final int DEFAULT_ELB_VM_CPU_MHZ = 256; // 500 MHz - - public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException; - - public LoadBalancer handleCreateLoadBalancerRule(CreateLoadBalancerRuleCmd lb, Account caller, long networkId) throws InsufficientAddressCapacityException, - NetworkRuleConflictException; - - public void handleDeleteLoadBalancerRule(LoadBalancer lb, long callerUserId, Account caller); -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java deleted file mode 100644 index d3894cad6e..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ /dev/null @@ -1,576 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.lb; - -import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; -import org.apache.cloudstack.framework.config.dao.ConfigurationDao; -import org.apache.cloudstack.managed.context.ManagedContextRunnable; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import javax.inject.Inject; -import javax.naming.ConfigurationException; - -import com.cloud.agent.AgentManager; -import com.cloud.agent.api.Answer; -import com.cloud.agent.api.Command; -import com.cloud.agent.api.check.CheckSshAnswer; -import com.cloud.agent.api.check.CheckSshCommand; -import com.cloud.agent.api.routing.LoadBalancerConfigCommand; -import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.agent.manager.Commands; -import com.cloud.configuration.Config; -import com.cloud.dc.DataCenter; -import com.cloud.dc.DataCenter.NetworkType; -import com.cloud.dc.DataCenterVO; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.AgentUnavailableException; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.exception.OperationTimedoutException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ElasticLbVmMapVO; -import com.cloud.network.Network; -import com.cloud.network.NetworkModel; -import com.cloud.network.Networks.TrafficType; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.LoadBalancerVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.lb.LoadBalancingRule.LbDestination; -import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy; -import com.cloud.network.lb.LoadBalancingRule.LbSslCert; -import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; -import com.cloud.network.lb.dao.ElasticLbVmMapDao; -import com.cloud.network.router.VirtualRouter; -import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.LoadBalancer; -import com.cloud.offering.NetworkOffering; -import com.cloud.offering.ServiceOffering; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.Storage; -import com.cloud.user.Account; -import com.cloud.user.AccountService; -import com.cloud.utils.NumbersUtil; -import com.cloud.utils.component.ManagerBase; -import com.cloud.utils.concurrency.NamedThreadFactory; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.utils.net.Ip; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.NicProfile; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.VirtualMachineGuru; -import com.cloud.vm.VirtualMachineManager; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.dao.DomainRouterDao; -import com.cloud.vm.dao.NicDao; - -@Component -public class ElasticLoadBalancerManagerImpl extends ManagerBase implements ElasticLoadBalancerManager, VirtualMachineGuru { - private static final Logger s_logger = Logger.getLogger(ElasticLoadBalancerManagerImpl.class); - - @Inject - private AgentManager _agentMgr; - @Inject - private NetworkModel _networkModel; - @Inject - private LoadBalancingRulesManager _lbMgr; - @Inject - private final DomainRouterDao _routerDao = null; - @Inject - protected HostPodDao _podDao = null; - @Inject - protected ClusterDao _clusterDao; - @Inject - private final DataCenterDao _dcDao = null; - @Inject - protected NetworkDao _networkDao; - @Inject - protected NetworkOfferingDao _networkOfferingDao; - @Inject - private VirtualMachineManager _itMgr; - @Inject - private ConfigurationDao _configDao; - @Inject - private final ServiceOfferingDao _serviceOfferingDao = null; - @Inject - private AccountService _accountService; - @Inject - private LoadBalancerDao _lbDao; - @Inject - private ElasticLbVmMapDao _elbVmMapDao; - @Inject - private NicDao _nicDao; - - String _instance; - - static final private String SystemVmType = "elbvm"; - - boolean _enabled; - TrafficType _frontendTrafficType = TrafficType.Guest; - - Account _systemAcct; - ScheduledExecutorService _gcThreadPool; - String _mgmtCidr; - - Set _gcCandidateElbVmIds = Collections.newSetFromMap(new ConcurrentHashMap()); - - int _elasticLbVmRamSize; - int _elasticLbvmCpuMHz; - int _elasticLbvmNumCpu; - - private LoadBalanceRuleHandler loadBalanceRuleHandler; - - private boolean sendCommandsToRouter(final DomainRouterVO elbVm, Commands cmds) throws AgentUnavailableException { - Answer[] answers = null; - try { - answers = _agentMgr.send(elbVm.getHostId(), cmds); - } catch (final OperationTimedoutException e) { - s_logger.warn("ELB: Timed Out", e); - throw new AgentUnavailableException("Unable to send commands to virtual elbVm ", elbVm.getHostId(), e); - } - - if (answers == null) { - return false; - } - - if (answers.length != cmds.size()) { - return false; - } - - // FIXME: Have to return state for individual command in the future - if (answers.length > 0) { - final Answer ans = answers[0]; - return ans.getResult(); - } - return true; - } - - private void createApplyLoadBalancingRulesCommands(List rules, DomainRouterVO elbVm, Commands cmds, long guestNetworkId) { - - /* XXX: cert */ - final LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()]; - int i = 0; - for (final LoadBalancingRule rule : rules) { - final boolean revoked = rule.getState().equals(FirewallRule.State.Revoke); - final String protocol = rule.getProtocol(); - final String algorithm = rule.getAlgorithm(); - - final String elbIp = rule.getSourceIp().addr(); - final int srcPort = rule.getSourcePortStart(); - final String uuid = rule.getUuid(); - final List destinations = rule.getDestinations(); - final LoadBalancerTO lb = new LoadBalancerTO(uuid, elbIp, srcPort, protocol, algorithm, revoked, false, false, destinations); - lbs[i++] = lb; - } - - final NetworkOffering offering = _networkOfferingDao.findById(guestNetworkId); - String maxconn = null; - if (offering.getConcurrentConnections() == null) { - maxconn = _configDao.getValue(Config.NetworkLBHaproxyMaxConn.key()); - } else { - maxconn = offering.getConcurrentConnections().toString(); - } - final LoadBalancerConfigCommand cmd = new LoadBalancerConfigCommand(lbs, elbVm.getPublicIpAddress(), _nicDao.getIpAddress(guestNetworkId, elbVm.getId()), - elbVm.getPrivateIpAddress(), null, null, maxconn, offering.isKeepAliveEnabled()); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_IP, elbVm.getPrivateIpAddress()); - cmd.setAccessDetail(NetworkElementCommand.ROUTER_NAME, elbVm.getInstanceName()); - //FIXME: why are we setting attributes directly? Ick!! There should be accessors and - //the constructor should set defaults. - cmd.lbStatsVisibility = _configDao.getValue(Config.NetworkLBHaproxyStatsVisbility.key()); - cmd.lbStatsUri = _configDao.getValue(Config.NetworkLBHaproxyStatsUri.key()); - cmd.lbStatsAuth = _configDao.getValue(Config.NetworkLBHaproxyStatsAuth.key()); - cmd.lbStatsPort = _configDao.getValue(Config.NetworkLBHaproxyStatsPort.key()); - - cmds.addCommand(cmd); - - } - - protected boolean applyLBRules(DomainRouterVO elbVm, List rules, long guestNetworkId) throws ResourceUnavailableException { - final Commands cmds = new Commands(Command.OnError.Continue); - createApplyLoadBalancingRulesCommands(rules, elbVm, cmds, guestNetworkId); - // Send commands to elbVm - return sendCommandsToRouter(elbVm, cmds); - } - - protected DomainRouterVO findElbVmForLb(LoadBalancingRule lb) {//TODO: use a table to lookup - final Network ntwk = _networkModel.getNetwork(lb.getNetworkId()); - final long sourceIpId = _networkModel.getPublicIpAddress(lb.getSourceIp().addr(), ntwk.getDataCenterId()).getId(); - final ElasticLbVmMapVO map = _elbVmMapDao.findOneByIp(sourceIpId); - if (map == null) { - return null; - } - final DomainRouterVO elbVm = _routerDao.findById(map.getElbVmId()); - return elbVm; - } - - @Override - public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException { - if (rules == null || rules.isEmpty()) { - return true; - } - - final DomainRouterVO elbVm = findElbVmForLb(rules.get(0)); - - if (elbVm == null) { - s_logger.warn("Unable to apply lb rules, ELB vm doesn't exist in the network " + network.getId()); - throw new ResourceUnavailableException("Unable to apply lb rules", DataCenter.class, network.getDataCenterId()); - } - - if (elbVm.getState() == State.Running) { - //resend all rules for the public ip - final long sourceIpId = _networkModel.getPublicIpAddress(rules.get(0).getSourceIp().addr(), network.getDataCenterId()).getId(); - final List lbs = _lbDao.listByIpAddress(sourceIpId); - final List lbRules = new ArrayList(); - for (final LoadBalancerVO lb : lbs) { - final List dstList = _lbMgr.getExistingDestinations(lb.getId()); - final List policyList = _lbMgr.getStickinessPolicies(lb.getId()); - final List hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId()); - final Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress(); - final LbSslCert sslCert = _lbMgr.getLbSslCert(lb.getId()); - final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp, sslCert, lb.getLbProtocol()); - lbRules.add(loadBalancing); - } - return applyLBRules(elbVm, lbRules, network.getId()); - } else if (elbVm.getState() == State.Stopped || elbVm.getState() == State.Stopping) { - s_logger.debug("ELB VM is in " + elbVm.getState() + ", so not sending apply LoadBalancing rules commands to the backend"); - return true; - } else { - s_logger.warn("Unable to apply loadbalancing rules, ELB VM is not in the right state " + elbVm.getState()); - throw new ResourceUnavailableException("Unable to apply loadbalancing rules, ELB VM is not in the right state", VirtualRouter.class, elbVm.getId()); - } - } - - @Override - public boolean configure(String name, Map params) throws ConfigurationException { - final Map configs = _configDao.getConfiguration("AgentManager", params); - _systemAcct = _accountService.getSystemAccount(); - _instance = configs.get("instance.name"); - if (_instance == null) { - _instance = "VM"; - } - _mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key()); - - _elasticLbVmRamSize = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmMemory.key()), DEFAULT_ELB_VM_RAMSIZE); - _elasticLbvmCpuMHz = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmCpuMhz.key()), DEFAULT_ELB_VM_CPU_MHZ); - _elasticLbvmNumCpu = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmNumVcpu.key()), 1); - final List offerings = _serviceOfferingDao.createSystemServiceOfferings("System Offering For Elastic LB VM", - ServiceOffering.elbVmDefaultOffUniqueName, _elasticLbvmNumCpu, _elasticLbVmRamSize, _elasticLbvmCpuMHz, 0, 0, true, null, - Storage.ProvisioningType.THIN, true, null, true, VirtualMachine.Type.ElasticLoadBalancerVm, true); - // this can sometimes happen, if DB is manually or programmatically manipulated - if (offerings == null || offerings.size() < 2) { - final String msg = "Data integrity problem : System Offering For Elastic LB VM has been removed?"; - s_logger.error(msg); - throw new ConfigurationException(msg); - } - - final String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); - _enabled = enabled == null ? false : Boolean.parseBoolean(enabled); - s_logger.info("Elastic Load balancer enabled: " + _enabled); - if (_enabled) { - final String traffType = _configDao.getValue(Config.ElasticLoadBalancerNetwork.key()); - if ("guest".equalsIgnoreCase(traffType)) { - _frontendTrafficType = TrafficType.Guest; - } else if ("public".equalsIgnoreCase(traffType)) { - _frontendTrafficType = TrafficType.Public; - } else { - throw new ConfigurationException("ELB: Traffic type for front end of load balancer has to be guest or public; found : " + traffType); - } - s_logger.info("ELB: Elastic Load Balancer: will balance on " + traffType); - int gcIntervalMinutes = NumbersUtil.parseInt(configs.get(Config.ElasticLoadBalancerVmGcInterval.key()), 5); - if (gcIntervalMinutes < 5) { - gcIntervalMinutes = 5; - } - s_logger.info("ELB: Elastic Load Balancer: scheduling GC to run every " + gcIntervalMinutes + " minutes"); - _gcThreadPool = Executors.newScheduledThreadPool(1, new NamedThreadFactory("ELBVM-GC")); - _gcThreadPool.scheduleAtFixedRate(new CleanupThread(), gcIntervalMinutes, gcIntervalMinutes, TimeUnit.MINUTES); - _itMgr.registerGuru(VirtualMachine.Type.ElasticLoadBalancerVm, this); - } - - loadBalanceRuleHandler = new LoadBalanceRuleHandler(_instance, _systemAcct); - - return true; - } - - private DomainRouterVO stop(DomainRouterVO elbVm, boolean forced) throws ConcurrentOperationException, ResourceUnavailableException { - s_logger.debug("Stopping ELB vm " + elbVm); - try { - _itMgr.advanceStop(elbVm.getUuid(), forced); - return _routerDao.findById(elbVm.getId()); - } catch (final OperationTimedoutException e) { - throw new CloudRuntimeException("Unable to stop " + elbVm, e); - } - } - - @Override - public LoadBalancer handleCreateLoadBalancerRule(CreateLoadBalancerRuleCmd lb, Account account, long networkId) throws InsufficientAddressCapacityException, - NetworkRuleConflictException { - return loadBalanceRuleHandler.handleCreateLoadBalancerRule(lb, account, networkId); - } - - void garbageCollectUnusedElbVms() { - final List unusedElbVms = _elbVmMapDao.listUnusedElbVms(); - if (unusedElbVms != null) { - if (unusedElbVms.size() > 0) { - s_logger.info("Found " + unusedElbVms.size() + " unused ELB vms"); - } - final Set currentGcCandidates = new HashSet(); - for (final DomainRouterVO elbVm : unusedElbVms) { - currentGcCandidates.add(elbVm.getId()); - } - _gcCandidateElbVmIds.retainAll(currentGcCandidates); - currentGcCandidates.removeAll(_gcCandidateElbVmIds); - for (final Long elbVmId : _gcCandidateElbVmIds) { - final DomainRouterVO elbVm = _routerDao.findById(elbVmId); - boolean gceed = false; - - try { - s_logger.info("Attempting to stop ELB VM: " + elbVm); - stop(elbVm, true); - gceed = true; - } catch (final ConcurrentOperationException e) { - s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e); - } catch (final ResourceUnavailableException e) { - s_logger.warn("Unable to stop unused ELB vm " + elbVm + " due to ", e); - continue; - } - if (gceed) { - try { - s_logger.info("Attempting to destroy ELB VM: " + elbVm); - _itMgr.expunge(elbVm.getUuid()); - _routerDao.remove(elbVm.getId()); - } catch (final ResourceUnavailableException e) { - s_logger.warn("Unable to destroy unused ELB vm " + elbVm + " due to ", e); - gceed = false; - } - } - if (!gceed) { - currentGcCandidates.add(elbVm.getId()); - } - - } - _gcCandidateElbVmIds = currentGcCandidates; - } - } - - public class CleanupThread extends ManagedContextRunnable { - @Override - protected void runInContext() { - garbageCollectUnusedElbVms(); - - } - - CleanupThread() { - - } - } - - @Override - public void handleDeleteLoadBalancerRule(LoadBalancer lb, long userId, Account caller) { - if (!_enabled) { - return; - } - loadBalanceRuleHandler.handleDeleteLoadBalancerRule(lb, userId, caller); - } - - @Override - public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { - - final List elbNics = profile.getNics(); - Long guestNtwkId = null; - for (final NicProfile routerNic : elbNics) { - if (routerNic.getTrafficType() == TrafficType.Guest) { - guestNtwkId = routerNic.getNetworkId(); - break; - } - } - - final NetworkVO guestNetwork = _networkDao.findById(guestNtwkId); - - dest.getDataCenter(); - - final StringBuilder buf = profile.getBootArgsBuilder(); - buf.append(" template=domP type=" + SystemVmType); - buf.append(" name=").append(profile.getHostName()); - NicProfile controlNic = null; - String defaultDns1 = null; - String defaultDns2 = null; - - for (final NicProfile nic : profile.getNics()) { - final int deviceId = nic.getDeviceId(); - buf.append(" eth").append(deviceId).append("ip=").append(nic.getIPv4Address()); - buf.append(" eth").append(deviceId).append("mask=").append(nic.getIPv4Netmask()); - if (nic.isDefaultNic()) { - buf.append(" gateway=").append(nic.getIPv4Gateway()); - defaultDns1 = nic.getIPv4Dns1(); - defaultDns2 = nic.getIPv4Dns2(); - } - if (nic.getTrafficType() == TrafficType.Management) { - buf.append(" localgw=").append(dest.getPod().getGateway()); - } else if (nic.getTrafficType() == TrafficType.Control) { - controlNic = nic; - } - } - final String domain = guestNetwork.getNetworkDomain(); - if (domain != null) { - buf.append(" domain=" + domain); - } - - buf.append(" dns1=").append(defaultDns1); - if (defaultDns2 != null) { - buf.append(" dns2=").append(defaultDns2); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Boot Args for " + profile + ": " + buf.toString()); - } - - if (controlNic == null) { - throw new CloudRuntimeException("Didn't start a control port"); - } - - return true; - } - - @Override - public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException { - final DomainRouterVO elbVm = _routerDao.findById(profile.getVirtualMachine().getId()); - - final List nics = profile.getNics(); - for (final NicProfile nic : nics) { - if (nic.getTrafficType() == TrafficType.Public) { - elbVm.setPublicIpAddress(nic.getIPv4Address()); - elbVm.setPublicNetmask(nic.getIPv4Netmask()); - elbVm.setPublicMacAddress(nic.getMacAddress()); - } else if (nic.getTrafficType() == TrafficType.Control) { - elbVm.setPrivateIpAddress(nic.getIPv4Address()); - elbVm.setPrivateMacAddress(nic.getMacAddress()); - } - } - _routerDao.update(elbVm.getId(), elbVm); - - finalizeCommandsOnStart(cmds, profile); - return true; - } - - @Override - public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Commands cmds, ReservationContext context) { - final CheckSshAnswer answer = (CheckSshAnswer)cmds.getAnswer("checkSsh"); - if (answer == null || !answer.getResult()) { - s_logger.warn("Unable to ssh to the ELB VM: " + (answer != null ? answer.getDetails() : "No answer (answer for \"checkSsh\" was null)")); - return false; - } - - return true; - } - - @Override - public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) { - final DomainRouterVO elbVm = _routerDao.findById(profile.getVirtualMachine().getId()); - final DataCenterVO dcVo = _dcDao.findById(elbVm.getDataCenterId()); - - NicProfile controlNic = null; - Long guestNetworkId = null; - - if (dcVo.getNetworkType() == NetworkType.Basic) { - // for basic network mode, we will use the guest NIC for control NIC - for (final NicProfile nic : profile.getNics()) { - if (nic.getTrafficType() == TrafficType.Guest && nic.getIPv4Address() != null) { - controlNic = nic; - guestNetworkId = nic.getNetworkId(); - } - } - } else { - for (final NicProfile nic : profile.getNics()) { - if (nic.getTrafficType() == TrafficType.Control && nic.getIPv4Address() != null) { - controlNic = nic; - } else if (nic.getTrafficType() == TrafficType.Guest) { - guestNetworkId = nic.getNetworkId(); - } - } - } - - if (controlNic == null) { - s_logger.error("Control network doesn't exist for the ELB vm " + elbVm); - return false; - } - - cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIPv4Address(), 3922)); - - // Re-apply load balancing rules - final List lbs = _elbVmMapDao.listLbsForElbVm(elbVm.getId()); - final List lbRules = new ArrayList(); - for (final LoadBalancerVO lb : lbs) { - final List dstList = _lbMgr.getExistingDestinations(lb.getId()); - final List policyList = _lbMgr.getStickinessPolicies(lb.getId()); - final List hcPolicyList = _lbMgr.getHealthCheckPolicies(lb.getId()); - final Ip sourceIp = _networkModel.getPublicIpAddress(lb.getSourceIpAddressId()).getAddress(); - final LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList, sourceIp); - lbRules.add(loadBalancing); - } - - s_logger.debug("Found " + lbRules.size() + " load balancing rule(s) to apply as a part of ELB vm " + elbVm + " start."); - if (!lbRules.isEmpty()) { - createApplyLoadBalancingRulesCommands(lbRules, elbVm, cmds, guestNetworkId); - } - - return true; - } - - @Override - public void finalizeStop(VirtualMachineProfile profile, Answer answer) { - if (answer != null) { - final DomainRouterVO elbVm = _routerDao.findById(profile.getVirtualMachine().getId()); - processStopOrRebootAnswer(elbVm, answer); - } - } - - @SuppressWarnings("unused") - public void processStopOrRebootAnswer(final DomainRouterVO elbVm, Answer answer) { - //TODO: process network usage stats - } - - @Override - public void finalizeExpunge(VirtualMachine vm) { - // no-op - } - - @Override - public void prepareStop(VirtualMachineProfile profile) { - } - -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/LoadBalanceRuleHandler.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/LoadBalanceRuleHandler.java deleted file mode 100644 index f5046b6a7b..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/LoadBalanceRuleHandler.java +++ /dev/null @@ -1,483 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.network.lb; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import javax.inject.Inject; - -import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; -import org.apache.cloudstack.context.CallContext; -import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; -import org.apache.log4j.Logger; - -import com.cloud.configuration.ConfigurationManagerImpl; -import com.cloud.dc.DataCenter; -import com.cloud.dc.Pod; -import com.cloud.dc.PodVlanMapVO; -import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.dao.ClusterDao; -import com.cloud.dc.dao.DataCenterDao; -import com.cloud.dc.dao.HostPodDao; -import com.cloud.dc.dao.PodVlanMapDao; -import com.cloud.deploy.DataCenterDeployment; -import com.cloud.deploy.DeployDestination; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientAddressCapacityException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; -import com.cloud.network.ElasticLbVmMapVO; -import com.cloud.network.IpAddressManager; -import com.cloud.network.Network; -import com.cloud.network.Network.Provider; -import com.cloud.network.Network.Service; -import com.cloud.network.NetworkModel; -import com.cloud.network.PhysicalNetworkServiceProvider; -import com.cloud.network.VirtualRouterProvider; -import com.cloud.network.VirtualRouterProvider.Type; -import com.cloud.network.addr.PublicIp; -import com.cloud.network.dao.IPAddressDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.LoadBalancerVO; -import com.cloud.network.dao.NetworkDao; -import com.cloud.network.dao.NetworkVO; -import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; -import com.cloud.network.dao.VirtualRouterProviderDao; -import com.cloud.network.lb.dao.ElasticLbVmMapDao; -import com.cloud.network.router.VirtualRouter.RedundantState; -import com.cloud.network.router.VirtualRouter.Role; -import com.cloud.network.rules.LoadBalancer; -import com.cloud.offering.NetworkOffering; -import com.cloud.offering.ServiceOffering; -import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.service.ServiceOfferingVO; -import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.VMTemplateVO; -import com.cloud.storage.dao.VMTemplateDao; -import com.cloud.user.Account; -import com.cloud.user.AccountService; -import com.cloud.user.UserVO; -import com.cloud.user.dao.AccountDao; -import com.cloud.user.dao.UserDao; -import com.cloud.utils.db.DB; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.utils.db.Transaction; -import com.cloud.utils.db.TransactionCallbackWithException; -import com.cloud.utils.db.TransactionStatus; -import com.cloud.utils.exception.CloudRuntimeException; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.NicProfile; -import com.cloud.vm.VirtualMachine.State; -import com.cloud.vm.VirtualMachineManager; -import com.cloud.vm.VirtualMachineName; -import com.cloud.vm.VirtualMachineProfile; -import com.cloud.vm.VirtualMachineProfile.Param; -import com.cloud.vm.dao.DomainRouterDao; - -public class LoadBalanceRuleHandler { - - private static final Logger s_logger = Logger.getLogger(LoadBalanceRuleHandler.class); - - @Inject - private IPAddressDao _ipAddressDao; - @Inject - private NetworkModel _networkModel; - @Inject - private NetworkOrchestrationService _networkMgr; - @Inject - private final LoadBalancerDao _loadBalancerDao = null; - @Inject - private LoadBalancingRulesManager _lbMgr; - @Inject - private final DomainRouterDao _routerDao = null; - @Inject - protected HostPodDao _podDao = null; - @Inject - protected ClusterDao _clusterDao; - @Inject - private final DataCenterDao _dcDao = null; - @Inject - private IpAddressManager _ipAddrMgr; - @Inject - protected NetworkDao _networkDao; - @Inject - protected NetworkOfferingDao _networkOfferingDao; - @Inject - private final VMTemplateDao _templateDao = null; - @Inject - private VirtualMachineManager _itMgr; - @Inject - private AccountService _accountService; - @Inject - private LoadBalancerDao _lbDao; - @Inject - private PodVlanMapDao _podVlanMapDao; - @Inject - private ElasticLbVmMapDao _elbVmMapDao; - @Inject - private AccountDao _accountDao; - @Inject - private PhysicalNetworkServiceProviderDao _physicalProviderDao; - @Inject - private VirtualRouterProviderDao _vrProviderDao; - @Inject - private ServiceOfferingDao _serviceOfferingDao; - @Inject - private UserDao _userDao; - - static final private String ELB_VM_NAME_PREFIX = "l"; - - private final String _instance; - private final Account _systemAcct; - - public LoadBalanceRuleHandler(String instance, Account systemAcct) { - _instance = instance; - _systemAcct = systemAcct; - } - - public void handleDeleteLoadBalancerRule(final LoadBalancer lb, final long userId, final Account caller) { - final List remainingLbs = _loadBalancerDao.listByIpAddress(lb.getSourceIpAddressId()); - if (remainingLbs.size() == 0) { - s_logger.debug("ELB mgr: releasing ip " + lb.getSourceIpAddressId() + " since no LB rules remain for this ip address"); - releaseIp(lb.getSourceIpAddressId(), userId, caller); - } - } - - public LoadBalancer handleCreateLoadBalancerRule(final CreateLoadBalancerRuleCmd lb, Account account, final long networkId) throws InsufficientAddressCapacityException, - NetworkRuleConflictException { - //this part of code is executed when the LB provider is Elastic Load Balancer vm - if (!_networkModel.isProviderSupportServiceInNetwork(lb.getNetworkId(), Service.Lb, Provider.ElasticLoadBalancerVm)) { - return null; - } - - final Long ipId = lb.getSourceIpAddressId(); - if (ipId != null) { - return null; - } - - account = _accountDao.acquireInLockTable(account.getId()); - if (account == null) { - s_logger.warn("ELB: CreateLoadBalancer: Failed to acquire lock on account"); - throw new CloudRuntimeException("Failed to acquire lock on account"); - } - try { - return handleCreateLoadBalancerRuleWithLock(lb, account, networkId); - } finally { - if (account != null) { - _accountDao.releaseFromLockTable(account.getId()); - } - } - } - - private DomainRouterVO deployLoadBalancerVM(final Long networkId, final IPAddressVO ipAddr) { - final NetworkVO network = _networkDao.findById(networkId); - final DataCenter dc = _dcDao.findById(network.getDataCenterId()); - final Long podId = getPodIdForDirectIp(ipAddr); - final Pod pod = podId == null ? null : _podDao.findById(podId); - final Map params = new HashMap(1); - params.put(VirtualMachineProfile.Param.ReProgramGuestNetworks, true); - final Account owner = _accountService.getActiveAccountByName("system", new Long(1)); - final DeployDestination dest = new DeployDestination(dc, pod, null, null); - s_logger.debug("About to deploy ELB vm "); - - try { - final DomainRouterVO elbVm = deployELBVm(network, dest, owner, params); - if (elbVm == null) { - throw new InvalidParameterValueException("Could not deploy or find existing ELB VM"); - } - s_logger.debug("Deployed ELB vm = " + elbVm); - - return elbVm; - - } catch (final Throwable t) { - s_logger.warn("Error while deploying ELB VM: ", t); - return null; - } - - } - - private DomainRouterVO deployELBVm(Network guestNetwork, final DeployDestination dest, Account owner, final Map params) throws ConcurrentOperationException, - InsufficientCapacityException { - final long dcId = dest.getDataCenter().getId(); - - // lock guest network - final Long guestNetworkId = guestNetwork.getId(); - guestNetwork = _networkDao.acquireInLockTable(guestNetworkId); - - if (guestNetwork == null) { - throw new ConcurrentOperationException("Unable to acquire network lock: " + guestNetworkId); - } - - try { - - if (_networkModel.isNetworkSystem(guestNetwork) || guestNetwork.getGuestType() == Network.GuestType.Shared) { - owner = _accountService.getSystemAccount(); - } - - if (s_logger.isDebugEnabled()) { - s_logger.debug("Starting a ELB vm for network configurations: " + guestNetwork + " in " + dest); - } - assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " - + guestNetwork; - - DataCenterDeployment plan = null; - DomainRouterVO elbVm = null; - - plan = new DataCenterDeployment(dcId, dest.getPod().getId(), null, null, null, null); - - if (elbVm == null) { - final long id = _routerDao.getNextInSequence(Long.class, "id"); - if (s_logger.isDebugEnabled()) { - s_logger.debug("Creating the ELB vm " + id); - } - - final List offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork); - final NetworkOffering controlOffering = offerings.get(0); - final Network controlConfig = _networkMgr.setupNetwork(_systemAcct, controlOffering, plan, null, null, false).get(0); - - final LinkedHashMap> networks = new LinkedHashMap>(2); - final NicProfile guestNic = new NicProfile(); - guestNic.setDefaultNic(true); - networks.put(controlConfig, new ArrayList()); - networks.put(guestNetwork, new ArrayList(Arrays.asList(guestNic))); - - final VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId); - - final String typeString = "ElasticLoadBalancerVm"; - final Long physicalNetworkId = _networkModel.getPhysicalNetworkId(guestNetwork); - final PhysicalNetworkServiceProvider provider = _physicalProviderDao.findByServiceProvider(physicalNetworkId, typeString); - if (provider == null) { - throw new CloudRuntimeException("Cannot find service provider " + typeString + " in physical network " + physicalNetworkId); - } - final VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), Type.ElasticLoadBalancerVm); - if (vrProvider == null) { - throw new CloudRuntimeException("Cannot find virtual router provider " + typeString + " as service provider " + provider.getId()); - } - - long userId = CallContext.current().getCallingUserId(); - if (CallContext.current().getCallingAccount().getId() != owner.getId()) { - List userVOs = _userDao.listByAccount(owner.getAccountId()); - if (!userVOs.isEmpty()) { - userId = userVOs.get(0).getId(); - } - } - - ServiceOfferingVO elasticLbVmOffering = _serviceOfferingDao.findDefaultSystemOffering(ServiceOffering.elbVmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dest.getDataCenter().getId())); - elbVm = new DomainRouterVO(id, elasticLbVmOffering.getId(), vrProvider.getId(), VirtualMachineName.getSystemVmName(id, _instance, ELB_VM_NAME_PREFIX), - template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, false, RedundantState.UNKNOWN, - elasticLbVmOffering.getOfferHA(), false, null); - elbVm.setRole(Role.LB); - elbVm = _routerDao.persist(elbVm); - _itMgr.allocate(elbVm.getInstanceName(), template, elasticLbVmOffering, networks, plan, null); - elbVm = _routerDao.findById(elbVm.getId()); - //TODO: create usage stats - } - - final State state = elbVm.getState(); - if (state != State.Running) { - elbVm = start(elbVm, params); - } - - return elbVm; - } finally { - _networkDao.releaseFromLockTable(guestNetworkId); - } - } - - private void releaseIp(final long ipId, final long userId, final Account caller) { - s_logger.info("ELB: Release public IP for loadbalancing " + ipId); - final IPAddressVO ipvo = _ipAddressDao.findById(ipId); - ipvo.setAssociatedWithNetworkId(null); - _ipAddressDao.update(ipvo.getId(), ipvo); - _ipAddrMgr.disassociatePublicIpAddress(ipId, userId, caller); - _ipAddressDao.unassignIpAddress(ipId); - } - - protected Long getPodIdForDirectIp(final IPAddressVO ipAddr) { - final PodVlanMapVO podVlanMaps = _podVlanMapDao.listPodVlanMapsByVlan(ipAddr.getVlanId()); - if (podVlanMaps == null) { - return null; - } else { - return podVlanMaps.getPodId(); - } - } - - private LoadBalancer handleCreateLoadBalancerRuleWithLock(final CreateLoadBalancerRuleCmd lb, final Account account, final long networkId) throws InsufficientAddressCapacityException, - NetworkRuleConflictException { - Long ipId = null; - boolean newIp = false; - List existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), lb.getSourcePortStart()); - if (existingLbs == null) { - existingLbs = findExistingLoadBalancers(lb.getName(), lb.getSourceIpAddressId(), lb.getAccountId(), lb.getDomainId(), null); - if (existingLbs == null) { - if (lb.getSourceIpAddressId() != null) { - throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(lb); - } else { - s_logger.debug("Could not find any existing frontend ips for this account for this LB rule, acquiring a new frontent IP for ELB"); - final PublicIp ip = allocDirectIp(account, networkId); - ipId = ip.getId(); - newIp = true; - } - } else { - ipId = existingLbs.get(0).getSourceIpAddressId(); - s_logger.debug("ELB: Found existing frontend ip for this account for this LB rule " + ipId); - } - } else { - s_logger.warn("ELB: Found existing load balancers matching requested new LB"); - throw new NetworkRuleConflictException("ELB: Found existing load balancers matching requested new LB"); - } - - final IPAddressVO ipAddr = _ipAddressDao.findById(ipId); - - LoadBalancer result = null; - try { - lb.setSourceIpAddressId(ipId); - - result = _lbMgr.createPublicLoadBalancer(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourcePortStart(), lb.getDefaultPortStart(), ipId.longValue(), - lb.getProtocol(), lb.getAlgorithm(), false, CallContext.current(), lb.getLbProtocol(), true); - } catch (final NetworkRuleConflictException e) { - s_logger.warn("Failed to create LB rule, not continuing with ELB deployment"); - if (newIp) { - releaseIp(ipId, CallContext.current().getCallingUserId(), account); - } - throw e; - } - - DomainRouterVO elbVm = null; - - if (existingLbs == null) { - elbVm = findElbVmWithCapacity(ipAddr); - if (elbVm == null) { - elbVm = deployLoadBalancerVM(networkId, ipAddr); - if (elbVm == null) { - final Network network = _networkModel.getNetwork(networkId); - s_logger.warn("Failed to deploy a new ELB vm for ip " + ipAddr + " in network " + network + "lb name=" + lb.getName()); - if (newIp) { - releaseIp(ipId, CallContext.current().getCallingUserId(), account); - } - } - } - - } else { - final ElasticLbVmMapVO elbVmMap = _elbVmMapDao.findOneByIp(ipId); - if (elbVmMap != null) { - elbVm = _routerDao.findById(elbVmMap.getElbVmId()); - } - } - - if (elbVm == null) { - s_logger.warn("No ELB VM can be found or deployed"); - s_logger.warn("Deleting LB since we failed to deploy ELB VM"); - _lbDao.remove(result.getId()); - return null; - } - - final ElasticLbVmMapVO mapping = new ElasticLbVmMapVO(ipId, elbVm.getId(), result.getId()); - _elbVmMapDao.persist(mapping); - return result; - } - - private void throwExceptionIfSuppliedlLbNameIsNotAssociatedWithIpAddress(final CreateLoadBalancerRuleCmd lb) { - final List existingLbs = findExistingLoadBalancers(lb.getName(), null, lb.getAccountId(), lb.getDomainId(), null); - if (existingLbs != null) { - throw new InvalidParameterValueException("Supplied LB name " + lb.getName() + " is not associated with IP " + lb.getSourceIpAddressId()); - } - } - - protected List findExistingLoadBalancers(final String lbName, final Long ipId, final Long accountId, final Long domainId, final Integer publicPort) { - final SearchBuilder sb = _lbDao.createSearchBuilder(); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); - sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ); - if (ipId != null) { - sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ); - } - if (domainId != null) { - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - } - if (publicPort != null) { - sb.and("publicPort", sb.entity().getSourcePortStart(), SearchCriteria.Op.EQ); - } - final SearchCriteria sc = sb.create(); - sc.setParameters("name", lbName); - sc.setParameters("accountId", accountId); - if (ipId != null) { - sc.setParameters("sourceIpAddress", ipId); - } - if (domainId != null) { - sc.setParameters("domainId", domainId); - } - if (publicPort != null) { - sc.setParameters("publicPort", publicPort); - } - final List lbs = _lbDao.search(sc, null); - - return lbs == null || lbs.size() == 0 ? null : lbs; - } - - @DB - private PublicIp allocDirectIp(final Account account, final long guestNetworkId) throws InsufficientAddressCapacityException { - return Transaction.execute(new TransactionCallbackWithException() { - @Override - public PublicIp doInTransaction(final TransactionStatus status) throws InsufficientAddressCapacityException { - final Network frontEndNetwork = _networkModel.getNetwork(guestNetworkId); - - final PublicIp ip = _ipAddrMgr.assignPublicIpAddress(frontEndNetwork.getDataCenterId(), null, account, VlanType.DirectAttached, frontEndNetwork.getId(), null, true); - final IPAddressVO ipvo = _ipAddressDao.findById(ip.getId()); - ipvo.setAssociatedWithNetworkId(frontEndNetwork.getId()); - _ipAddressDao.update(ipvo.getId(), ipvo); - s_logger.info("Acquired frontend IP for ELB " + ip); - - return ip; - } - }); - } - - protected DomainRouterVO findElbVmWithCapacity(final IPAddressVO ipAddr) { - final List unusedElbVms = _elbVmMapDao.listUnusedElbVms(); - if (unusedElbVms.size() > 0) { - final List candidateVms = new ArrayList(); - for (final DomainRouterVO candidateVm : unusedElbVms) { - addCandidateVmIsPodIpMatches(candidateVm, getPodIdForDirectIp(ipAddr), candidateVms); - } - return candidateVms.size() == 0 ? null : candidateVms.get(new Random().nextInt(candidateVms.size())); - } - return null; - } - - protected static void addCandidateVmIsPodIpMatches(final DomainRouterVO candidateVm, final Long podIdForDirectIp, final List candidateVms) { - if (candidateVm.getPodIdToDeployIn().equals(podIdForDirectIp)) { - candidateVms.add(candidateVm); - } - } - - protected DomainRouterVO start(final DomainRouterVO elbVm, final Map params) throws ConcurrentOperationException { - s_logger.debug("Starting ELB VM " + elbVm); - _itMgr.start(elbVm.getUuid(), params); - return _routerDao.findById(elbVm.getId()); - } -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDao.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDao.java deleted file mode 100644 index 83aa6118a6..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDao.java +++ /dev/null @@ -1,43 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.lb.dao; - -import java.util.List; - -import com.cloud.network.ElasticLbVmMapVO; -import com.cloud.network.dao.LoadBalancerVO; -import com.cloud.utils.db.GenericDao; -import com.cloud.vm.DomainRouterVO; - -public interface ElasticLbVmMapDao extends GenericDao { - ElasticLbVmMapVO findOneByLbIdAndElbVmId(long lbId, long elbVmId); - - ElasticLbVmMapVO findOneByIpIdAndElbVmId(long ipId, long elbVmId); - - ElasticLbVmMapVO findOneByIp(long ipId); - - List listByElbVmId(long elbVmId); - - List listByLbId(long lbId); - - int deleteLB(long lbId); - - List listUnusedElbVms(); - - List listLbsForElbVm(long elbVmId); - -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDaoImpl.java b/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDaoImpl.java deleted file mode 100644 index bbe79ef310..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/java/com/cloud/network/lb/dao/ElasticLbVmMapDaoImpl.java +++ /dev/null @@ -1,139 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -package com.cloud.network.lb.dao; - -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.inject.Inject; - -import org.springframework.stereotype.Component; - -import com.cloud.network.ElasticLbVmMapVO; -import com.cloud.network.dao.LoadBalancerDao; -import com.cloud.network.dao.LoadBalancerVO; -import com.cloud.network.router.VirtualRouter.Role; -import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.JoinBuilder.JoinType; -import com.cloud.utils.db.SearchBuilder; -import com.cloud.utils.db.SearchCriteria; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.dao.DomainRouterDao; - -@Component -public class ElasticLbVmMapDaoImpl extends GenericDaoBase implements ElasticLbVmMapDao { - @Inject - protected DomainRouterDao _routerDao; - @Inject - protected LoadBalancerDao _loadbalancerDao; - - protected SearchBuilder AllFieldsSearch; - protected SearchBuilder UnusedVmSearch; - protected SearchBuilder LoadBalancersForElbVmSearch; - - protected SearchBuilder ElbVmSearch; - - protected SearchBuilder LoadBalancerSearch; - - public ElasticLbVmMapDaoImpl() { - } - - @PostConstruct - protected void init() { - AllFieldsSearch = createSearchBuilder(); - AllFieldsSearch.and("ipId", AllFieldsSearch.entity().getIpAddressId(), SearchCriteria.Op.EQ); - AllFieldsSearch.and("lbId", AllFieldsSearch.entity().getLbId(), SearchCriteria.Op.EQ); - AllFieldsSearch.and("elbVmId", AllFieldsSearch.entity().getElbVmId(), SearchCriteria.Op.EQ); - AllFieldsSearch.done(); - - ElbVmSearch = _routerDao.createSearchBuilder(); - ElbVmSearch.and("role", ElbVmSearch.entity().getRole(), SearchCriteria.Op.EQ); - UnusedVmSearch = createSearchBuilder(); - UnusedVmSearch.and("elbVmId", UnusedVmSearch.entity().getElbVmId(), SearchCriteria.Op.NULL); - ElbVmSearch.join("UnusedVmSearch", UnusedVmSearch, ElbVmSearch.entity().getId(), UnusedVmSearch.entity().getElbVmId(), JoinType.LEFTOUTER); - ElbVmSearch.done(); - UnusedVmSearch.done(); - - LoadBalancerSearch = _loadbalancerDao.createSearchBuilder(); - LoadBalancersForElbVmSearch = createSearchBuilder(); - LoadBalancersForElbVmSearch.and("elbVmId", LoadBalancersForElbVmSearch.entity().getElbVmId(), SearchCriteria.Op.EQ); - LoadBalancerSearch.join("LoadBalancersForElbVm", LoadBalancersForElbVmSearch, LoadBalancerSearch.entity().getId(), - LoadBalancersForElbVmSearch.entity().getLbId(), JoinType.INNER); - LoadBalancersForElbVmSearch.done(); - LoadBalancerSearch.done(); - - } - - @Override - public ElasticLbVmMapVO findOneByLbIdAndElbVmId(long lbId, long elbVmId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("lbId", lbId); - sc.setParameters("elbVmId", elbVmId); - return findOneBy(sc); - } - - @Override - public List listByLbId(long lbId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("lbId", lbId); - return listBy(sc); - } - - @Override - public List listByElbVmId(long elbVmId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("elbVmId", elbVmId); - return listBy(sc); - } - - @Override - public int deleteLB(long lbId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("lbId", lbId); - return super.expunge(sc); - } - - @Override - public ElasticLbVmMapVO findOneByIpIdAndElbVmId(long ipId, long elbVmId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("ipId", ipId); - sc.setParameters("elbVmId", elbVmId); - return findOneBy(sc); - } - - @Override - public ElasticLbVmMapVO findOneByIp(long ipId) { - SearchCriteria sc = AllFieldsSearch.create(); - sc.setParameters("ipId", ipId); - return findOneBy(sc); - } - - @Override - public List listUnusedElbVms() { - SearchCriteria sc = ElbVmSearch.create(); - sc.setParameters("role", Role.LB); - return _routerDao.search(sc, null); - } - - @Override - public List listLbsForElbVm(long elbVmId) { - SearchCriteria sc = LoadBalancerSearch.create(); - sc.setJoinParameters("LoadBalancersForElbVm", "elbVmId", elbVmId); - return _loadbalancerDao.search(sc, null); - } - -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/module.properties b/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/module.properties deleted file mode 100644 index a8e3b9c866..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/module.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -name=elb -parent=network \ No newline at end of file diff --git a/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/spring-elb-context.xml b/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/spring-elb-context.xml deleted file mode 100644 index 247153c455..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/main/resources/META-INF/cloudstack/elb/spring-elb-context.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - diff --git a/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/ElasticLoadBalancerManagerImplTest.java b/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/ElasticLoadBalancerManagerImplTest.java deleted file mode 100644 index 8928fd9997..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/ElasticLoadBalancerManagerImplTest.java +++ /dev/null @@ -1,101 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.network.lb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.internal.util.reflection.Whitebox; -import org.mockito.runners.MockitoJUnitRunner; - -import com.cloud.agent.api.check.CheckSshAnswer; -import com.cloud.agent.manager.Commands; -import com.cloud.network.lb.dao.ElasticLbVmMapDao; -import com.cloud.vm.ReservationContext; -import com.cloud.vm.VirtualMachineProfile; - -@RunWith(MockitoJUnitRunner.class) -public class ElasticLoadBalancerManagerImplTest { - - @InjectMocks - private ElasticLoadBalancerManagerImpl elasticLoadBalancerManagerImpl; - - @Test - public void testFinalizeStartWhenCmdsAnswerIsNull() throws Exception { - VirtualMachineProfile profileMock = mock(VirtualMachineProfile.class); - long hostId = 1L; - Commands cmds = mock(Commands.class); - when(cmds.getAnswer("checkSsh")).thenReturn(null); - ReservationContext context = mock(ReservationContext.class); - - boolean expected = false; - boolean actual = elasticLoadBalancerManagerImpl.finalizeStart(profileMock, hostId, cmds, context); - - assertEquals(expected, actual); - } - - @Test - public void testFinalizeStartWhenCmdsAnswerIsNotNullButAnswerResultIsFalse() throws Exception { - CheckSshAnswer answerMock = mock(CheckSshAnswer.class); - when(answerMock.getResult()).thenReturn(false); - VirtualMachineProfile profileMock = mock(VirtualMachineProfile.class); - long hostId = 1L; - Commands cmds = mock(Commands.class); - when(cmds.getAnswer("checkSsh")).thenReturn(answerMock); - ReservationContext context = mock(ReservationContext.class); - - boolean expected = false; - boolean actual = elasticLoadBalancerManagerImpl.finalizeStart(profileMock, hostId, cmds, context); - - assertEquals(expected, actual); - } - - @Test - public void testFinalizeStartWhenCmdsAnswerIsNotNullAndAnswerResultIsTrue() throws Exception { - CheckSshAnswer answerMock = mock(CheckSshAnswer.class); - when(answerMock.getResult()).thenReturn(true); - VirtualMachineProfile profileMock = mock(VirtualMachineProfile.class); - long hostId = 1L; - Commands cmds = mock(Commands.class); - when(cmds.getAnswer("checkSsh")).thenReturn(answerMock); - ReservationContext context = mock(ReservationContext.class); - - boolean expected = true; - boolean actual = elasticLoadBalancerManagerImpl.finalizeStart(profileMock, hostId, cmds, context); - - assertEquals(expected, actual); - } - - @Test - public void testGarbageCollectUnusedElbVmsWhenVariableUnusedElbVmsIsNull() throws Exception { - ElasticLbVmMapDao elasticLbVmMapDaoMock = mock(ElasticLbVmMapDao.class); - when(elasticLbVmMapDaoMock.listUnusedElbVms()).thenReturn(null); - Whitebox.setInternalState(elasticLoadBalancerManagerImpl, "_elbVmMapDao", elasticLbVmMapDaoMock); - - try { - elasticLoadBalancerManagerImpl.garbageCollectUnusedElbVms(); - } catch (NullPointerException e) { - fail(); - } - } -} diff --git a/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/LoadBalanceRuleHandlerTest.java b/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/LoadBalanceRuleHandlerTest.java deleted file mode 100644 index 17bae63568..0000000000 --- a/plugins/network-elements/elastic-loadbalancer/src/test/java/com/cloud/network/lb/LoadBalanceRuleHandlerTest.java +++ /dev/null @@ -1,215 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -package com.cloud.network.lb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.internal.util.reflection.Whitebox; -import org.mockito.runners.MockitoJUnitRunner; - -import com.cloud.dc.PodVlanMapVO; -import com.cloud.dc.dao.PodVlanMapDao; -import com.cloud.network.dao.IPAddressVO; -import com.cloud.network.lb.dao.ElasticLbVmMapDao; -import com.cloud.vm.DomainRouterVO; -import com.cloud.vm.VirtualMachineManager; -import com.cloud.vm.VirtualMachineProfile.Param; -import com.cloud.vm.dao.DomainRouterDao; - -@RunWith(MockitoJUnitRunner.class) -public class LoadBalanceRuleHandlerTest { - - @InjectMocks - private LoadBalanceRuleHandler loadBalanceRuleHandler; - - @Mock - private VirtualMachineManager virtualMachineManagerMock; - - @Mock - private DomainRouterDao domainRouterDaoMock; - - @Mock - private ElasticLbVmMapDao elasticLbVmMapDao; - - @Mock - private PodVlanMapDao podVlanMapDao; - - @Before - public void setup() { - Whitebox.setInternalState(loadBalanceRuleHandler, "_itMgr", virtualMachineManagerMock); - Whitebox.setInternalState(loadBalanceRuleHandler, "_routerDao", domainRouterDaoMock); - Whitebox.setInternalState(loadBalanceRuleHandler, "_elbVmMapDao", elasticLbVmMapDao); - Whitebox.setInternalState(loadBalanceRuleHandler, "_podVlanMapDao", podVlanMapDao); - } - - @Test - public void testAddCandidateVmIsPodIpMatchesWhenIdsHaveSameValue() throws Exception { - DomainRouterVO candidateVmMock = mock(DomainRouterVO.class); - when(candidateVmMock.getPodIdToDeployIn()).thenReturn(new Long(1)); - Long podIdForDirectIp = new Long(1); - List candidateVms = new ArrayList(); - - LoadBalanceRuleHandler.addCandidateVmIsPodIpMatches(candidateVmMock, podIdForDirectIp, candidateVms); - - assertEquals(1, candidateVms.size()); - } - - @Test - public void testAddCandidateVmIsPodIpMatchesWhenPodIdForDirectIpIsNull() throws Exception { - DomainRouterVO candidateVmMock = mock(DomainRouterVO.class); - when(candidateVmMock.getPodIdToDeployIn()).thenReturn(new Long(1)); - Long podIdForDirectIp = null; - List candidateVms = new ArrayList(); - - LoadBalanceRuleHandler.addCandidateVmIsPodIpMatches(candidateVmMock, podIdForDirectIp, candidateVms); - - assertEquals(0, candidateVms.size()); - } - - // PodIdToDeployIn should not be null according to column specification in DomainRouterVO - @Test(expected = NullPointerException.class) - public void testAddCandidateVmIsPodIpMatchesWhenPodIdToDeployInIsNull() throws Exception { - DomainRouterVO candidateVmMock = mock(DomainRouterVO.class); - when(candidateVmMock.getPodIdToDeployIn()).thenReturn(null); - Long podIdForDirectIp = new Long(1); - List candidateVms = new ArrayList(); - - LoadBalanceRuleHandler.addCandidateVmIsPodIpMatches(candidateVmMock, podIdForDirectIp, candidateVms); - } - - @Test(expected = NullPointerException.class) - public void testAddCandidateVmIsPodIpMatchesWhenCandidateVmsIsNull() throws Exception { - DomainRouterVO candidateVmMock = mock(DomainRouterVO.class); - when(candidateVmMock.getPodIdToDeployIn()).thenReturn(new Long(1)); - Long podIdForDirectIp = new Long(1); - List candidateVms = null; - - LoadBalanceRuleHandler.addCandidateVmIsPodIpMatches(candidateVmMock, podIdForDirectIp, candidateVms); - } - - @Test(expected = NullPointerException.class) - public void testStartWhenElbVmIsNull() throws Exception { - DomainRouterVO elbVm = null; - Map params = new HashMap(); - - loadBalanceRuleHandler.start(elbVm, params); - } - - @Test - public void testStartWhenParamsIsNull() throws Exception { - DomainRouterVO elbVmMock = mock(DomainRouterVO.class); - String uuid = "uuid"; - when(elbVmMock.getUuid()).thenReturn(uuid); - long id = 1L; - when(elbVmMock.getId()).thenReturn(id); - Map params = null; - - loadBalanceRuleHandler.start(elbVmMock, params); - - verify(virtualMachineManagerMock, times(1)).start(uuid, params); - verify(domainRouterDaoMock, times(1)).findById(id); - } - - @Test - public void testStartWhenParamsIsEmpty() throws Exception { - DomainRouterVO elbVmMock = mock(DomainRouterVO.class); - String uuid = "uuid"; - when(elbVmMock.getUuid()).thenReturn(uuid); - long id = 1L; - when(elbVmMock.getId()).thenReturn(id); - Map params = new HashMap(); - - loadBalanceRuleHandler.start(elbVmMock, params); - - verify(virtualMachineManagerMock, times(1)).start(uuid, params); - verify(domainRouterDaoMock, times(1)).findById(id); - } - - @Test - public void testStart() throws Exception { - DomainRouterVO elbVmMock = mock(DomainRouterVO.class); - String uuid = "uuid"; - when(elbVmMock.getUuid()).thenReturn(uuid); - long id = 1L; - when(elbVmMock.getId()).thenReturn(id); - Map params = new HashMap(); - params.put(mock(Param.class), new Object()); - - loadBalanceRuleHandler.start(elbVmMock, params); - - verify(virtualMachineManagerMock, times(1)).start(uuid, params); - verify(domainRouterDaoMock, times(1)).findById(id); - } - - @Test - public void testFindElbVmWithCapacityWhenIpAddrIsNull() throws Exception { - IPAddressVO ipAddr = null; - - DomainRouterVO actual = loadBalanceRuleHandler.findElbVmWithCapacity(ipAddr); - - assertNull(actual); - } - - @Test - public void testFindElbVmWithCapacityWhenThereAreNoUnusedElbVms() throws Exception { - IPAddressVO ipAddr = mock(IPAddressVO.class); - when(this.elasticLbVmMapDao.listUnusedElbVms()).thenReturn(new ArrayList(1)); - - DomainRouterVO actual = loadBalanceRuleHandler.findElbVmWithCapacity(ipAddr); - - assertNull(actual); - } - - @Test - public void testFindElbVmWithCapacityWhenThereAreUnusedElbVmsAndOneMatchesThePodId() throws Exception { - Long podId = 1L; - IPAddressVO ipAddrMock = mock(IPAddressVO.class); - when(ipAddrMock.getVlanId()).thenReturn(podId); - PodVlanMapVO podVlanMapVoMock = mock(PodVlanMapVO.class); - when(podVlanMapVoMock.getPodId()).thenReturn(podId); - when(podVlanMapDao.listPodVlanMapsByVlan(podId)).thenReturn(podVlanMapVoMock); - DomainRouterVO unusedElbVmThatMatchesPodId = mock(DomainRouterVO.class); - when(unusedElbVmThatMatchesPodId.getPodIdToDeployIn()).thenReturn(podId); - List unusedElbVms = Arrays.asList(new DomainRouterVO[] {unusedElbVmThatMatchesPodId, mock(DomainRouterVO.class)}); - when(this.elasticLbVmMapDao.listUnusedElbVms()).thenReturn(unusedElbVms); - - DomainRouterVO expected = unusedElbVmThatMatchesPodId; - DomainRouterVO actual = loadBalanceRuleHandler.findElbVmWithCapacity(ipAddrMock); - - assertNotNull(actual); - assertEquals(expected, actual); - } - -} diff --git a/plugins/pom.xml b/plugins/pom.xml index c3e80ad6bd..748e8f0f94 100755 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -24,7 +24,6 @@ host-allocators/random dedicated-resources hypervisors/baremetal - network-elements/elastic-loadbalancer network-elements/nicira-nvp storage-allocators/random storage/image/s3 diff --git a/server/src/test/resources/network-mgr-component.xml b/server/src/test/resources/network-mgr-component.xml index 3451847c25..b79ec418d6 100644 --- a/server/src/test/resources/network-mgr-component.xml +++ b/server/src/test/resources/network-mgr-component.xml @@ -140,13 +140,11 @@ under the License. - -