2 * Copyright IBM Corporation, 2013. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.samples.loadbalancer.internal;
10 import java.net.InetAddress;
11 import java.net.UnknownHostException;
12 import java.util.ArrayList;
13 import java.util.Dictionary;
14 import java.util.List;
17 import org.apache.felix.dm.Component;
18 import org.opendaylight.controller.forwardingrulesmanager.FlowEntry;
19 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
20 import org.opendaylight.controller.hosttracker.IfIptoHost;
21 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
22 import org.opendaylight.controller.sal.action.Action;
23 import org.opendaylight.controller.sal.action.Output;
24 import org.opendaylight.controller.sal.action.SetDlDst;
25 import org.opendaylight.controller.sal.action.SetDlSrc;
26 import org.opendaylight.controller.sal.action.SetNwDst;
27 import org.opendaylight.controller.sal.action.SetNwSrc;
28 import org.opendaylight.controller.sal.core.Node;
29 import org.opendaylight.controller.sal.core.NodeConnector;
30 import org.opendaylight.controller.sal.core.Path;
31 import org.opendaylight.controller.sal.flowprogrammer.Flow;
32 import org.opendaylight.controller.sal.match.Match;
33 import org.opendaylight.controller.sal.match.MatchType;
34 import org.opendaylight.controller.sal.packet.Ethernet;
35 import org.opendaylight.controller.sal.packet.IDataPacketService;
36 import org.opendaylight.controller.sal.packet.IListenDataPacket;
37 import org.opendaylight.controller.sal.packet.IPv4;
38 import org.opendaylight.controller.sal.packet.Packet;
39 import org.opendaylight.controller.sal.packet.PacketResult;
40 import org.opendaylight.controller.sal.packet.RawPacket;
41 import org.opendaylight.controller.sal.routing.IRouting;
42 import org.opendaylight.controller.sal.utils.EtherTypes;
43 import org.opendaylight.controller.sal.utils.GlobalConstants;
44 import org.opendaylight.controller.sal.utils.IPProtocols;
45 import org.opendaylight.controller.samples.loadbalancer.ConfigManager;
46 import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
47 import org.opendaylight.controller.samples.loadbalancer.LBConst;
48 import org.opendaylight.controller.samples.loadbalancer.LBUtil;
49 import org.opendaylight.controller.samples.loadbalancer.entities.Client;
50 import org.opendaylight.controller.samples.loadbalancer.entities.Pool;
51 import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember;
52 import org.opendaylight.controller.samples.loadbalancer.entities.VIP;
53 import org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy;
54 import org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * This class is the main class that represents the load balancer service.
60 * This is a sample load balancer application that balances traffic to backend servers
61 * based on the source address and source port on each incoming packet. The service
62 * reactively installs OpenFlow rules to direct all packets with a specific source address
63 * and source port to one of the appropriate backend servers. The servers may be chosen
64 * using a round robin policy or a random policy. This service can be configured via a
65 * REST APIs which are similar to the OpenStack Quantum LBaaS (Load-balancer-as-a-Service)
66 * v1.0 API proposal (http://wiki.openstack.org/Quantum/LBaaS)
68 * To use this service, a virtual IP (or VIP) should be exposed to the clients of this service
69 * and used as the destination address. A VIP is a entity that comprises of a virtual IP, port
70 * and protocol (TCP or UDP).
72 * 1. One or more VIPs may be mapped to the same server pool. All VIPs that share the same
73 * pool must also share the same load balancing policy (random or round robin).
75 * 2. Only one server pool can be be assigned to a VIP.
77 * 3. All flow rules are installed with an idle timeout of 5 seconds.
79 * 4. Packets to a VIP must leave the OpenFlow cluster from the same switch from where
82 * 5. When you delete a VIP or a server pool or a server from a pool, the service does not
83 * delete the flow rules it has already installed. The flow rules should automatically
84 * time out after the idle timeout of 5 seconds.
87 public class LoadBalancerService implements IListenDataPacket, IConfigManager{
92 private static Logger lbsLogger = LoggerFactory.getLogger(LoadBalancerService.class);
95 * Single instance of the configuration manager. Application passes this reference to all
96 * the new policies implemented for load balancing.
98 private static ConfigManager configManager = new ConfigManager();
101 * Round robing policy instance. Need to implement factory patterns to get
104 private static RoundRobinLBPolicy rrLBMethod= new RoundRobinLBPolicy(configManager);
107 * Random policy instance.
109 private static RandomLBPolicy ranLBMethod= new RandomLBPolicy(configManager);
112 * Reference to the data packet service
114 private IDataPacketService dataPacketService = null;
117 * Reference to the host tracker service
119 private IfIptoHost hostTracker;
122 * Reference to the forwarding manager
124 private IForwardingRulesManager ruleManager;
127 * Reference to the routing service
129 private IRouting routing;
132 * Load balancer application installs all flows with priority 2.
134 private static short LB_IPSWITCH_PRIORITY = 2;
137 * Name of the container where this application will register.
139 private String containerName = null;
142 * Set/unset methods for the service instance that load balancer
145 public String getContainerName() {
146 if (containerName == null)
147 return GlobalConstants.DEFAULT.toString();
148 return containerName;
151 void setDataPacketService(IDataPacketService s) {
152 this.dataPacketService = s;
155 void unsetDataPacketService(IDataPacketService s) {
156 if (this.dataPacketService == s) {
157 this.dataPacketService = null;
161 public void setRouting(IRouting routing) {
162 this.routing = routing;
165 public void unsetRouting(IRouting routing) {
166 if (this.routing == routing) {
171 public void setHostTracker(IfIptoHost hostTracker) {
172 lbsLogger.debug("Setting HostTracker");
173 this.hostTracker = hostTracker;
176 public void unsetHostTracker(IfIptoHost hostTracker) {
177 if (this.hostTracker == hostTracker) {
178 this.hostTracker = null;
182 public void setForwardingRulesManager(
183 IForwardingRulesManager forwardingRulesManager) {
184 lbsLogger.debug("Setting ForwardingRulesManager");
185 this.ruleManager = forwardingRulesManager;
188 public void unsetForwardingRulesManager(
189 IForwardingRulesManager forwardingRulesManager) {
190 if (this.ruleManager == forwardingRulesManager) {
191 this.ruleManager = null;
196 * This method receives first packet of flows for which there is no
197 * matching flow rule installed on the switch. IP addresses used for VIPs
198 * are not supposed to be used by any real/virtual host in the network.
199 * Hence, any forwarding/routing service will not install any flows rules matching
200 * these VIPs. This ensures that all the flows destined for VIPs will not find a match
201 * in the switch and will be forwarded to the load balancing service.
202 * Service will decide where to route this traffic based on the load balancing
203 * policy of the VIP's attached pool and will install appropriate flow rules
204 * in a reactive manner.
207 public PacketResult receiveDataPacket(RawPacket inPkt){
210 return PacketResult.IGNORED;
213 Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
215 if (formattedPak instanceof Ethernet) {
216 byte[] vipMacAddr = ((Ethernet) formattedPak).getDestinationMACAddress();
217 Object ipPkt = formattedPak.getPayload();
219 if (ipPkt instanceof IPv4) {
221 lbsLogger.debug("Packet recieved from switch : {}",inPkt.getIncomingNodeConnector().getNode().toString());
222 IPv4 ipv4Pkt = (IPv4)ipPkt;
223 if(IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.TCP.toString())
224 || IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.UDP.toString())){
226 lbsLogger.debug("Packet protocol : {}",IPProtocols.getProtocolName(ipv4Pkt.getProtocol()));
227 Client client = new LBUtil().getClientFromPacket(ipv4Pkt);
228 VIP vip = new LBUtil().getVIPFromPacket(ipv4Pkt);
230 if(configManager.vipExists(vip)){
231 VIP vipWithPoolName = configManager.getVIPWithPoolName(vip);
232 String poolMemberIp = null;
233 if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.ROUND_ROBIN_LB_METHOD)){
235 poolMemberIp = rrLBMethod.getPoolMemberForClient(client,vipWithPoolName);
238 if(configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod().equalsIgnoreCase(LBConst.RANDOM_LB_METHOD)){
239 poolMemberIp = ranLBMethod.getPoolMemberForClient(client,vipWithPoolName);
244 Node clientNode = inPkt.getIncomingNodeConnector().getNode();
245 HostNodeConnector hnConnector = this.hostTracker.hostFind(InetAddress.getByName(poolMemberIp));
247 Node destNode = hnConnector.getnodeconnectorNode();
249 lbsLogger.debug("Client is connected to switch : {}",clientNode.toString());
250 lbsLogger.debug("Destination pool machine is connected to switch : {}",destNode.toString());
252 //Get path between both the nodes
253 Path route = this.routing.getRoute(clientNode, destNode);
255 lbsLogger.info("Path between source (client) and destination switch nodes : {}",route.toString());
257 NodeConnector forwardPort = route.getEdges().get(0).getTailNodeConnector();
259 if(installLoadBalancerFlow(client,
263 hnConnector.getDataLayerAddressBytes(),
265 LBConst.FORWARD_DIRECTION_LB_FLOW)){
266 lbsLogger.info("Traffic from client : {} will be routed " +
267 "to pool machine : {}",client,poolMemberIp);
269 lbsLogger.error("Not able to route traffic from client : {}",client );
272 if(installLoadBalancerFlow(client,
277 inPkt.getIncomingNodeConnector(),
278 LBConst.REVERSE_DIRECTION_LB_FLOW)){
279 lbsLogger.info("Flow rule installed to change the source ip/mac from " +
280 "pool machine ip {} to VIP {} for traffic coming pool machine",poolMemberIp,vip);
282 lbsLogger.error("Not able to route traffic from client : {}",client );
284 }catch (UnknownHostException e) {
285 lbsLogger.error("Pool member not found in the network : {}",e.getMessage());
286 lbsLogger.error("",e);
292 return PacketResult.IGNORED;
296 * This method installs the flow rule for routing the traffic between two hosts.
297 * @param source Traffic is sent by this source
298 * @param dest Traffic is destined to this destination (VIP)
299 * @param sourceSwitch Switch from where controller received the packet
300 * @param destMachineIp IP address of the pool member where traffic needs to be routed
301 * @param destMachineMac MAC address of the pool member where traffic needs to be routed
302 * @param outport Use this port to send out traffic
303 * @param flowDirection FORWARD_DIRECTION_LB_FLOW or REVERSE_DIRECTION_LB_FLOW
304 * @return true If flow installation was successful
306 * @throws UnknownHostException
308 private boolean installLoadBalancerFlow(Client source,
311 String destMachineIp,
312 byte[] destMachineMac,
313 NodeConnector outport,
314 int flowDirection) throws UnknownHostException{
316 Match match = new Match();
317 List<Action> actions = new ArrayList<Action>();
319 if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
320 match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
321 match.setField(MatchType.NW_SRC, InetAddress.getByName(source.getIp()));
322 match.setField(MatchType.NW_DST, InetAddress.getByName(dest.getIp()));
323 match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(dest.getProtocol()));
324 match.setField(MatchType.TP_SRC, source.getPort());
325 match.setField(MatchType.TP_DST, dest.getPort());
327 actions.add(new SetNwDst(InetAddress.getByName(destMachineIp)));
328 actions.add(new SetDlDst(destMachineMac));
331 if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
332 match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
333 match.setField(MatchType.NW_SRC, InetAddress.getByName(destMachineIp));
334 match.setField(MatchType.NW_DST, InetAddress.getByName(source.getIp()));
335 match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(source.getProtocol()));
336 match.setField(MatchType.TP_SRC, dest.getPort());
337 match.setField(MatchType.TP_DST,source.getPort());
339 actions.add(new SetNwSrc(InetAddress.getByName(dest.getIp())));
340 actions.add(new SetDlSrc(destMachineMac));
343 actions.add(new Output(outport));
345 // Make sure the priority for IP switch entries is
346 // set to a level just above default drop entries
348 Flow flow = new Flow(match, actions);
349 flow.setIdleTimeout((short) 5);
350 flow.setHardTimeout((short) 0);
351 flow.setPriority(LB_IPSWITCH_PRIORITY);
353 String policyName = source.getIp()+":"+source.getProtocol()+":"+source.getPort();
354 String flowName =null;
356 if(flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW){
357 flowName = "["+policyName+":"+source.getIp() + ":"+dest.getIp()+"]";
360 if(flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW){
362 flowName = "["+policyName+":"+dest.getIp() + ":"+source.getIp()+"]";
365 FlowEntry fEntry = new FlowEntry(policyName, flowName, flow, sourceSwitch);
367 lbsLogger.info("Install flow entry {} on node {}",fEntry.toString(),sourceSwitch.toString());
369 if(!this.ruleManager.checkFlowEntryConflict(fEntry)){
370 if(this.ruleManager.installFlowEntry(fEntry).isSuccess()){
373 lbsLogger.error("Error in installing flow entry to node : {}",sourceSwitch);
376 lbsLogger.error("Conflicting flow entry exists : {}",fEntry.toString());
382 * Function called by the dependency manager when all the required
383 * dependencies are satisfied
386 void init(Component c) {
387 Dictionary<?, ?> props = c.getServiceProperties();
389 this.containerName = (String) props.get("containerName");
391 lbsLogger.info("Running container name:" + this.containerName);
394 // In the Global instance case the containerName is empty
395 this.containerName = "";
397 lbsLogger.info(configManager.toString());
401 * Function called by the dependency manager when at least one
402 * dependency become unsatisfied or when the component is shutting
403 * down because for example bundle is being stopped.
410 * Function called by dependency manager after "init ()" is called
411 * and after the services provided by the class are registered in
412 * the service registry
419 * Function called by the dependency manager before the services
420 * exported by the component are unregistered, this will be
421 * followed by a "destroy ()" calls
428 * All the methods below are just proxy methods to direct the REST API requests to configuration
429 * manager. We need this redirection as currently, opendaylight supports only one
430 * implementation of the service.
433 public Set<VIP> getAllVIPs() {
434 return configManager.getAllVIPs();
438 public boolean vipExists(String name, String ip, String protocol,
439 short protocolPort, String poolName) {
440 return configManager.vipExists(name, ip, protocol, protocolPort, poolName);
444 public boolean vipExists(VIP vip) {
445 return configManager.vipExists(vip);
449 public VIP createVIP(String name, String ip, String protocol,
450 short protocolPort, String poolName) {
451 return configManager.createVIP(name, ip, protocol, protocolPort, poolName);
455 public VIP updateVIP(String name, String poolName) {
456 return configManager.updateVIP(name, poolName);
460 public VIP deleteVIP(String name) {
461 return configManager.deleteVIP(name);
465 public boolean memberExists(String name, String memberIP, String poolName) {
466 return configManager.memberExists(name, memberIP, poolName);
470 public Set<PoolMember> getAllPoolMembers(String poolName) {
472 return configManager.getAllPoolMembers(poolName);
476 public PoolMember addPoolMember(String name,
479 return configManager.addPoolMember(name, memberIP, poolName);
483 public PoolMember removePoolMember(String name, String poolName) {
485 return configManager.removePoolMember(name, poolName);
489 public Set<Pool> getAllPools() {
491 return configManager.getAllPools();
495 public Pool getPool(String poolName) {
496 return configManager.getPool(poolName);
500 public boolean poolExists(String name, String lbMethod) {
501 return configManager.poolExists(name, lbMethod);
505 public Pool createPool(String name, String lbMethod) {
506 return configManager.createPool(name, lbMethod);
510 public Pool deletePool(String poolName) {
511 return configManager.deletePool(poolName);
515 public boolean vipExists(String name) {
516 return configManager.vipExists(name);
520 public boolean memberExists(String name, String poolName) {
521 return configManager.memberExists(name, poolName);
525 public boolean poolExists(String name) {
526 return configManager.poolExists(name);
530 public String getVIPAttachedPool(String name) {
531 return configManager.getVIPAttachedPool(name);