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.HostIdFactory;
21 import org.opendaylight.controller.hosttracker.IHostId;
22 import org.opendaylight.controller.hosttracker.IfIptoHost;
23 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
24 import org.opendaylight.controller.sal.action.Action;
25 import org.opendaylight.controller.sal.action.Output;
26 import org.opendaylight.controller.sal.action.SetDlDst;
27 import org.opendaylight.controller.sal.action.SetDlSrc;
28 import org.opendaylight.controller.sal.action.SetNwDst;
29 import org.opendaylight.controller.sal.action.SetNwSrc;
30 import org.opendaylight.controller.sal.core.Node;
31 import org.opendaylight.controller.sal.core.NodeConnector;
32 import org.opendaylight.controller.sal.core.Path;
33 import org.opendaylight.controller.sal.flowprogrammer.Flow;
34 import org.opendaylight.controller.sal.match.Match;
35 import org.opendaylight.controller.sal.match.MatchType;
36 import org.opendaylight.controller.sal.packet.Ethernet;
37 import org.opendaylight.controller.sal.packet.IDataPacketService;
38 import org.opendaylight.controller.sal.packet.IListenDataPacket;
39 import org.opendaylight.controller.sal.packet.IPv4;
40 import org.opendaylight.controller.sal.packet.Packet;
41 import org.opendaylight.controller.sal.packet.PacketResult;
42 import org.opendaylight.controller.sal.packet.RawPacket;
43 import org.opendaylight.controller.sal.routing.IRouting;
44 import org.opendaylight.controller.sal.utils.EtherTypes;
45 import org.opendaylight.controller.sal.utils.GlobalConstants;
46 import org.opendaylight.controller.sal.utils.IPProtocols;
47 import org.opendaylight.controller.samples.loadbalancer.ConfigManager;
48 import org.opendaylight.controller.samples.loadbalancer.IConfigManager;
49 import org.opendaylight.controller.samples.loadbalancer.LBConst;
50 import org.opendaylight.controller.samples.loadbalancer.LBUtil;
51 import org.opendaylight.controller.samples.loadbalancer.entities.Client;
52 import org.opendaylight.controller.samples.loadbalancer.entities.Pool;
53 import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember;
54 import org.opendaylight.controller.samples.loadbalancer.entities.VIP;
55 import org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy;
56 import org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * This class is the main class that represents the load balancer service. This
62 * is a sample load balancer application that balances traffic to backend
63 * servers based on the source address and source port on each incoming packet.
64 * The service reactively installs OpenFlow rules to direct all packets with a
65 * specific source address and source port to one of the appropriate backend
66 * servers. The servers may be chosen using a round robin policy or a random
67 * policy. This service can be configured via a REST APIs which are similar to
68 * the OpenStack Quantum LBaaS (Load-balancer-as-a-Service) v1.0 API proposal
69 * (http://wiki.openstack.org/Quantum/LBaaS)
71 * To use this service, a virtual IP (or VIP) should be exposed to the clients
72 * of this service and used as the destination address. A VIP is a entity that
73 * comprises of a virtual IP, port and protocol (TCP or UDP). Assumptions: 1.
74 * One or more VIPs may be mapped to the same server pool. All VIPs that share
75 * the same pool must also share the same load balancing policy (random or round
78 * 2. Only one server pool can be be assigned to a VIP.
80 * 3. All flow rules are installed with an idle timeout of 5 seconds.
82 * 4. Packets to a VIP must leave the OpenFlow cluster from the same switch from
83 * where it entered it.
85 * 5. When you delete a VIP or a server pool or a server from a pool, the
86 * service does not delete the flow rules it has already installed. The flow
87 * rules should automatically time out after the idle timeout of 5 seconds.
90 public class LoadBalancerService implements IListenDataPacket, IConfigManager {
95 private static Logger lbsLogger = LoggerFactory.getLogger(LoadBalancerService.class);
98 * Single instance of the configuration manager. Application passes this
99 * reference to all the new policies implemented for load balancing.
101 private static ConfigManager configManager = new ConfigManager();
104 * Round robing policy instance. Need to implement factory patterns to get
107 private static RoundRobinLBPolicy rrLBMethod = new RoundRobinLBPolicy(configManager);
110 * Random policy instance.
112 private static RandomLBPolicy ranLBMethod = new RandomLBPolicy(configManager);
115 * Reference to the data packet service
117 private IDataPacketService dataPacketService = null;
120 * Reference to the host tracker service
122 private IfIptoHost hostTracker;
125 * Reference to the forwarding manager
127 private IForwardingRulesManager ruleManager;
130 * Reference to the routing service
132 private IRouting routing;
135 * Load balancer application installs all flows with priority 2.
137 private static short LB_IPSWITCH_PRIORITY = 2;
140 * Name of the container where this application will register.
142 private String containerName = null;
145 * Set/unset methods for the service instance that load balancer service
148 public String getContainerName() {
149 if (containerName == null)
150 return GlobalConstants.DEFAULT.toString();
151 return containerName;
154 void setDataPacketService(IDataPacketService s) {
155 this.dataPacketService = s;
158 void unsetDataPacketService(IDataPacketService s) {
159 if (this.dataPacketService == s) {
160 this.dataPacketService = null;
164 public void setRouting(IRouting routing) {
165 this.routing = routing;
168 public void unsetRouting(IRouting routing) {
169 if (this.routing == routing) {
174 public void setHostTracker(IfIptoHost hostTracker) {
175 lbsLogger.debug("Setting HostTracker");
176 this.hostTracker = hostTracker;
179 public void unsetHostTracker(IfIptoHost hostTracker) {
180 if (this.hostTracker == hostTracker) {
181 this.hostTracker = null;
185 public void setForwardingRulesManager(IForwardingRulesManager forwardingRulesManager) {
186 lbsLogger.debug("Setting ForwardingRulesManager");
187 this.ruleManager = forwardingRulesManager;
190 public void unsetForwardingRulesManager(IForwardingRulesManager forwardingRulesManager) {
191 if (this.ruleManager == forwardingRulesManager) {
192 this.ruleManager = null;
197 * This method receives first packet of flows for which there is no matching
198 * flow rule installed on the switch. IP addresses used for VIPs are not
199 * supposed to be used by any real/virtual host in the network. Hence, any
200 * forwarding/routing service will not install any flows rules matching
201 * these VIPs. This ensures that all the flows destined for VIPs will not
202 * find a match in the switch and will be forwarded to the load balancing
203 * service. Service will decide where to route this traffic based on the
204 * load balancing policy of the VIP's attached pool and will install
205 * appropriate flow rules in a reactive manner.
208 public PacketResult receiveDataPacket(RawPacket inPkt) {
211 return PacketResult.IGNORED;
214 Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
216 if (formattedPak instanceof Ethernet) {
217 byte[] vipMacAddr = ((Ethernet) formattedPak).getDestinationMACAddress();
218 Object ipPkt = formattedPak.getPayload();
220 if (ipPkt instanceof IPv4) {
222 lbsLogger.debug("Packet recieved from switch : {}", inPkt.getIncomingNodeConnector().getNode()
224 IPv4 ipv4Pkt = (IPv4) ipPkt;
225 if (IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.TCP.toString())
226 || IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.UDP.toString())) {
228 lbsLogger.debug("Packet protocol : {}", IPProtocols.getProtocolName(ipv4Pkt.getProtocol()));
229 Client client = new LBUtil().getClientFromPacket(ipv4Pkt);
230 VIP vip = new LBUtil().getVIPFromPacket(ipv4Pkt);
232 if (configManager.vipExists(vip)) {
233 VIP vipWithPoolName = configManager.getVIPWithPoolName(vip);
234 String poolMemberIp = null;
235 if (vipWithPoolName.getPoolName() == null) {
236 lbsLogger.error("No pool attached. Please attach pool with the VIP -- {}", vip);
237 return PacketResult.IGNORED;
239 if (configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod()
240 .equalsIgnoreCase(LBConst.ROUND_ROBIN_LB_METHOD)) {
242 poolMemberIp = rrLBMethod.getPoolMemberForClient(client, vipWithPoolName);
245 if (configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod()
246 .equalsIgnoreCase(LBConst.RANDOM_LB_METHOD)) {
247 poolMemberIp = ranLBMethod.getPoolMemberForClient(client, vipWithPoolName);
252 Node clientNode = inPkt.getIncomingNodeConnector().getNode();
253 // HostTracker hosts db key scheme implementation
254 IHostId id = HostIdFactory.create(InetAddress.getByName(poolMemberIp), null);
255 HostNodeConnector hnConnector = this.hostTracker.hostFind(id);
257 Node destNode = hnConnector.getnodeconnectorNode();
259 lbsLogger.debug("Client is connected to switch : {}", clientNode.toString());
261 .debug("Destination pool machine is connected to switch : {}", destNode.toString());
263 // Get path between both the nodes
264 NodeConnector forwardPort = null;
266 if (clientNode.getNodeIDString().equals(destNode.getNodeIDString())) {
268 forwardPort = hnConnector.getnodeConnector();
271 .info("Both source (client) and destination pool machine is connected to same switch nodes. Respective ports are - {},{}",
272 forwardPort, inPkt.getIncomingNodeConnector());
276 Path route = this.routing.getRoute(clientNode, destNode);
278 lbsLogger.info("Path between source (client) and destination switch nodes : {}",
281 forwardPort = route.getEdges().get(0).getTailNodeConnector();
285 if (installLoadBalancerFlow(client, vip, clientNode, poolMemberIp,
286 hnConnector.getDataLayerAddressBytes(), forwardPort,
287 LBConst.FORWARD_DIRECTION_LB_FLOW)) {
288 lbsLogger.info("Traffic from client : {} will be routed " + "to pool machine : {}",
289 client, poolMemberIp);
291 lbsLogger.error("Not able to route traffic from client : {}", client);
294 if (installLoadBalancerFlow(client, vip, clientNode, poolMemberIp, vipMacAddr,
295 inPkt.getIncomingNodeConnector(), LBConst.REVERSE_DIRECTION_LB_FLOW)) {
296 lbsLogger.info("Flow rule installed to change the source ip/mac from "
297 + "pool machine ip {} to VIP {} for traffic coming pool machine", poolMemberIp,
300 lbsLogger.error("Not able to route traffic from client : {}", client);
302 } catch (UnknownHostException e) {
303 lbsLogger.error("Pool member not found in the network : {}", e.getMessage());
304 lbsLogger.error("", e);
310 return PacketResult.IGNORED;
314 * This method installs the flow rule for routing the traffic between two
317 * @param source Traffic is sent by this source
319 * @param dest Traffic is destined to this destination (VIP)
321 * @param sourceSwitch Switch from where controller received the packet
323 * @param destMachineIp IP address of the pool member where traffic needs to
326 * @param destMachineMac MAC address of the pool member where traffic needs
329 * @param outport Use this port to send out traffic
331 * @param flowDirection FORWARD_DIRECTION_LB_FLOW or
332 * REVERSE_DIRECTION_LB_FLOW
334 * @return true If flow installation was successful false else
336 * @throws UnknownHostException
338 private boolean installLoadBalancerFlow(Client source, VIP dest, Node sourceSwitch, String destMachineIp,
339 byte[] destMachineMac, NodeConnector outport, int flowDirection) throws UnknownHostException {
341 Match match = new Match();
342 List<Action> actions = new ArrayList<Action>();
344 if (flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW) {
345 match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
346 match.setField(MatchType.NW_SRC, InetAddress.getByName(source.getIp()));
347 match.setField(MatchType.NW_DST, InetAddress.getByName(dest.getIp()));
348 match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(dest.getProtocol()));
349 match.setField(MatchType.TP_SRC, source.getPort());
350 match.setField(MatchType.TP_DST, dest.getPort());
352 actions.add(new SetNwDst(InetAddress.getByName(destMachineIp)));
353 actions.add(new SetDlDst(destMachineMac));
356 if (flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW) {
357 match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue());
358 match.setField(MatchType.NW_SRC, InetAddress.getByName(destMachineIp));
359 match.setField(MatchType.NW_DST, InetAddress.getByName(source.getIp()));
360 match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(source.getProtocol()));
361 match.setField(MatchType.TP_SRC, dest.getPort());
362 match.setField(MatchType.TP_DST, source.getPort());
364 actions.add(new SetNwSrc(InetAddress.getByName(dest.getIp())));
365 actions.add(new SetDlSrc(destMachineMac));
368 actions.add(new Output(outport));
370 // Make sure the priority for IP switch entries is
371 // set to a level just above default drop entries
373 Flow flow = new Flow(match, actions);
374 flow.setIdleTimeout((short) 5);
375 flow.setHardTimeout((short) 0);
376 flow.setPriority(LB_IPSWITCH_PRIORITY);
378 String policyName = source.getIp() + ":" + source.getProtocol() + ":" + source.getPort();
379 String flowName = null;
381 if (flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW) {
382 flowName = "[" + policyName + ":" + source.getIp() + ":" + dest.getIp() + "]";
385 if (flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW) {
387 flowName = "[" + policyName + ":" + dest.getIp() + ":" + source.getIp() + "]";
390 FlowEntry fEntry = new FlowEntry(policyName, flowName, flow, sourceSwitch);
392 lbsLogger.info("Install flow entry {} on node {}", fEntry.toString(), sourceSwitch.toString());
394 if (!this.ruleManager.checkFlowEntryConflict(fEntry)) {
395 if (this.ruleManager.installFlowEntry(fEntry).isSuccess()) {
398 lbsLogger.error("Error in installing flow entry to node : {}", sourceSwitch);
401 lbsLogger.error("Conflicting flow entry exists : {}", fEntry.toString());
407 * Function called by the dependency manager when all the required
408 * dependencies are satisfied
411 void init(Component c) {
412 Dictionary<?, ?> props = c.getServiceProperties();
414 this.containerName = (String) props.get("containerName");
416 lbsLogger.info("Running container name:" + this.containerName);
419 // In the Global instance case the containerName is empty
420 this.containerName = "";
422 lbsLogger.info(configManager.toString());
427 * Function called by the dependency manager when at least one dependency
428 * become unsatisfied or when the component is shutting down because for
429 * example bundle is being stopped.
436 * Function called by dependency manager after "init ()" is called and after
437 * the services provided by the class are registered in the service registry
444 * Function called by the dependency manager before the services exported by
445 * the component are unregistered, this will be followed by a "destroy ()"
453 * All the methods below are just proxy methods to direct the REST API
454 * requests to configuration manager. We need this redirection as currently,
455 * opendaylight supports only one implementation of the service.
458 public Set<VIP> getAllVIPs() {
459 return configManager.getAllVIPs();
463 public boolean vipExists(String name, String ip, String protocol, short protocolPort, String poolName) {
464 return configManager.vipExists(name, ip, protocol, protocolPort, poolName);
468 public boolean vipExists(VIP vip) {
469 return configManager.vipExists(vip);
473 public VIP createVIP(String name, String ip, String protocol, short protocolPort, String poolName) {
474 return configManager.createVIP(name, ip, protocol, protocolPort, poolName);
478 public VIP updateVIP(String name, String poolName) {
479 return configManager.updateVIP(name, poolName);
483 public VIP deleteVIP(String name) {
484 return configManager.deleteVIP(name);
488 public boolean memberExists(String name, String memberIP, String poolName) {
489 return configManager.memberExists(name, memberIP, poolName);
493 public Set<PoolMember> getAllPoolMembers(String poolName) {
495 return configManager.getAllPoolMembers(poolName);
499 public PoolMember addPoolMember(String name, String memberIP, String poolName) {
500 return configManager.addPoolMember(name, memberIP, poolName);
504 public PoolMember removePoolMember(String name, String poolName) {
506 return configManager.removePoolMember(name, poolName);
510 public Set<Pool> getAllPools() {
512 return configManager.getAllPools();
516 public Pool getPool(String poolName) {
517 return configManager.getPool(poolName);
521 public boolean poolExists(String name, String lbMethod) {
522 return configManager.poolExists(name, lbMethod);
526 public Pool createPool(String name, String lbMethod) {
527 return configManager.createPool(name, lbMethod);
531 public Pool deletePool(String poolName) {
532 return configManager.deletePool(poolName);
536 public boolean vipExists(String name) {
537 return configManager.vipExists(name);
541 public boolean memberExists(String name, String poolName) {
542 return configManager.memberExists(name, poolName);
546 public boolean poolExists(String name) {
547 return configManager.poolExists(name);
551 public String getVIPAttachedPool(String name) {
552 return configManager.getVIPAttachedPool(name);