Merge "Add UT for SouthboundMapper and SouthboundProvider"
[netvirt.git] / openstack / net-virt / src / main / java / org / opendaylight / ovsdb / openstack / netvirt / LBaaSHandler.java
1 /*
2  * Copyright (c) 2014, 2015 SDN Hub, LLC. and others. All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.ovsdb.openstack.netvirt;
10
11 import java.net.HttpURLConnection;
12 import java.util.List;
13 import java.util.Map;
14
15 import org.opendaylight.neutron.spi.INeutronLoadBalancerAware;
16 import org.opendaylight.neutron.spi.INeutronLoadBalancerCRUD;
17 import org.opendaylight.neutron.spi.INeutronLoadBalancerPoolCRUD;
18 import org.opendaylight.neutron.spi.INeutronNetworkCRUD;
19 import org.opendaylight.neutron.spi.INeutronPortCRUD;
20 import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
21 import org.opendaylight.neutron.spi.NeutronLoadBalancer;
22 import org.opendaylight.neutron.spi.NeutronLoadBalancerPool;
23 import org.opendaylight.neutron.spi.NeutronLoadBalancerPoolMember;
24 import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
25 import org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher;
26 import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerConfiguration;
27 import org.opendaylight.ovsdb.openstack.netvirt.api.LoadBalancerProvider;
28 import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheListener;
29 import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheManager;
30 import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
31 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
32
33 import org.osgi.framework.ServiceReference;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.common.base.Preconditions;
38
39 /**
40  * Handle requests for OpenStack Neutron v2.0 LBaaS API calls for /v2.0/loadbalancers.
41  */
42
43 //TODO: Implement INeutronLoadBalancerHealthMonitorAware, INeutronLoadBalancerListenerAware, INeutronLoadBalancerPoolMemberAware,
44
45 public class LBaaSHandler extends AbstractHandler
46         implements INeutronLoadBalancerAware, ConfigInterface, NodeCacheListener {
47     private static final Logger LOG = LoggerFactory.getLogger(LBaaSHandler.class);
48
49     // The implementation for each of these services is resolved by the OSGi Service Manager
50     private volatile INeutronLoadBalancerCRUD neutronLBCache;
51     private volatile INeutronLoadBalancerPoolCRUD neutronLBPoolCache;
52     private volatile INeutronPortCRUD neutronPortCache;
53     private volatile INeutronNetworkCRUD neutronNetworkCache;
54     private volatile INeutronSubnetCRUD neutronSubnetCache;
55     private volatile LoadBalancerProvider loadBalancerProvider;
56     private volatile NodeCacheManager nodeCacheManager;
57
58     @Override
59     public int canCreateNeutronLoadBalancer(NeutronLoadBalancer neutronLB) {
60         //Always allowed and not wait for pool and members to be created
61         return HttpURLConnection.HTTP_OK;
62     }
63
64     @Override
65     public void neutronLoadBalancerCreated(NeutronLoadBalancer neutronLB) {
66         LOG.debug("Neutron LB Creation : {}", neutronLB.toString());
67         enqueueEvent(new NorthboundEvent(neutronLB, Action.ADD));
68     }
69
70     /**
71      * Assuming that the pool information is fully populated before this call is made,
72      * we go with creating the LoadBalancerConfiguration object for this call with
73      * all information that is necessary to insert flow_mods
74      */
75     private void doNeutronLoadBalancerCreate(NeutronLoadBalancer neutronLB) {
76         Preconditions.checkNotNull(loadBalancerProvider);
77         LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
78         final List<Node> nodes = nodeCacheManager.getBridgeNodes();
79
80         if (!lbConfig.isValid()) {
81             LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
82         } else if (nodes.isEmpty()) {
83             LOG.debug("Noop with LB {} creation because no nodes available.", lbConfig.getName());
84         } else {
85             for (Node node : nodes) {
86                 loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
87             }
88         }
89     }
90
91     @Override
92     public int canUpdateNeutronLoadBalancer(NeutronLoadBalancer delta, NeutronLoadBalancer original) {
93         //Update allowed anytime, even when the LB has no active pool yet
94         return HttpURLConnection.HTTP_OK;
95     }
96
97     @Override
98     public void neutronLoadBalancerUpdated(NeutronLoadBalancer neutronLB) {
99         LOG.debug("Neutron LB Update : {}", neutronLB.toString());
100         enqueueEvent(new NorthboundEvent(neutronLB, Action.UPDATE));
101     }
102
103     @Override
104     public int canDeleteNeutronLoadBalancer(NeutronLoadBalancer neutronLB) {
105         //Always allowed and not wait for pool to stop using it
106         return HttpURLConnection.HTTP_OK;
107     }
108
109     @Override
110     public void neutronLoadBalancerDeleted(NeutronLoadBalancer neutronLB) {
111         LOG.debug("Neutron LB Deletion : {}", neutronLB.toString());
112         enqueueEvent(new NorthboundEvent(neutronLB, Action.DELETE));
113     }
114
115     private void doNeutronLoadBalancerDelete(NeutronLoadBalancer neutronLB) {
116         Preconditions.checkNotNull(loadBalancerProvider);
117         LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
118         final List<Node> nodes = nodeCacheManager.getBridgeNodes();
119
120         if (!lbConfig.isValid()) {
121             LOG.debug("Neutron LB pool configuration invalid for {} ", lbConfig.getName());
122         } else if (nodes.isEmpty()) {
123             LOG.debug("Noop with LB {} deletion because no nodes available.", lbConfig.getName());
124         } else {
125             for (Node node : nodes) {
126                 loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE);
127             }
128         }
129     }
130
131     /**
132      * Process the event.
133      *
134      * @param abstractEvent the {@link org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent} event to be handled.
135      * @see org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher
136      */
137     @Override
138     public void processEvent(AbstractEvent abstractEvent) {
139         LOG.debug("Processing Loadbalancer event {}", abstractEvent);
140         if (!(abstractEvent instanceof NorthboundEvent)) {
141             LOG.error("Unable to process abstract event {}", abstractEvent);
142             return;
143         }
144         NorthboundEvent ev = (NorthboundEvent) abstractEvent;
145         switch (ev.getAction()) {
146             case ADD:
147                 doNeutronLoadBalancerCreate(ev.getLoadBalancer());
148                 break;
149             case DELETE:
150                 doNeutronLoadBalancerDelete(ev.getLoadBalancer());
151                 break;
152             case UPDATE:
153                 /**
154                  * Currently member update requires delete and re-adding
155                  * Also, weights and weight updates are not supported
156                  */
157                 doNeutronLoadBalancerDelete(ev.getLoadBalancer());
158                 doNeutronLoadBalancerCreate(ev.getLoadBalancer());
159                 break;
160             default:
161                 LOG.warn("Unable to process event action {}", ev.getAction());
162                 break;
163         }
164     }
165
166     /**
167      * Useful utility for extracting the loadbalancer instance
168      * configuration from the neutron LB cache
169      */
170     public LoadBalancerConfiguration extractLBConfiguration(NeutronLoadBalancer neutronLB) {
171         String loadBalancerName = neutronLB.getLoadBalancerName();
172         String loadBalancerVip = neutronLB.getLoadBalancerVipAddress();
173         String loadBalancerSubnetID = neutronLB.getLoadBalancerVipSubnetID();
174
175         LoadBalancerConfiguration lbConfig = new LoadBalancerConfiguration(loadBalancerName, loadBalancerVip);
176         Map.Entry<String,String> providerInfo =
177                 NeutronCacheUtils.getProviderInformation(neutronNetworkCache, neutronSubnetCache, loadBalancerSubnetID);
178         if (providerInfo != null) {
179             lbConfig.setProviderNetworkType(providerInfo.getKey());
180             lbConfig.setProviderSegmentationId(providerInfo.getValue());
181         }
182         lbConfig.setVmac(NeutronCacheUtils.getMacAddress(neutronPortCache, loadBalancerSubnetID, loadBalancerVip));
183
184         for (NeutronLoadBalancerPool neutronLBPool: neutronLBPoolCache.getAllNeutronLoadBalancerPools()) {
185             List<NeutronLoadBalancerPoolMember> members = neutronLBPool.getLoadBalancerPoolMembers();
186             String memberProtocol = neutronLBPool.getLoadBalancerPoolProtocol();
187             if (memberProtocol == null) {
188                 continue;
189             }
190
191             if (!(memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_TCP) ||
192                   memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTP) ||
193                   memberProtocol.equalsIgnoreCase(LoadBalancerConfiguration.PROTOCOL_HTTPS))) {
194                 continue;
195             }
196             for (NeutronLoadBalancerPoolMember neutronLBPoolMember: members) {
197                 Boolean memberAdminStateIsUp = neutronLBPoolMember.getPoolMemberAdminStateIsUp();
198                 String memberSubnetID = neutronLBPoolMember.getPoolMemberSubnetID();
199                 if (memberSubnetID != null && memberAdminStateIsUp != null &&
200                         memberSubnetID.equals(loadBalancerSubnetID) && memberAdminStateIsUp) {
201                     String memberID = neutronLBPoolMember.getID();
202                     String memberIP = neutronLBPoolMember.getPoolMemberAddress();
203                     Integer memberPort = neutronLBPoolMember.getPoolMemberProtoPort();
204                     if (memberID == null || memberIP == null || memberPort == null) {
205                         LOG.debug("Neutron LB pool member details incomplete: {}", neutronLBPoolMember);
206                         continue;
207                     }
208                     String memberMAC = NeutronCacheUtils.getMacAddress(neutronPortCache, memberSubnetID, memberIP);
209                     if (memberMAC == null) {
210                         continue;
211                     }
212                     lbConfig.addMember(memberID, memberIP, memberMAC, memberProtocol, memberPort);
213                 }
214             }
215         }
216         return lbConfig;
217     }
218
219     /**
220      * On the addition of a new node, we iterate through all existing loadbalancer
221      * instances and program the node for all of them. It is sufficient to do that only
222      * when a node is added, and only for the LB instances (and not individual members).
223      */
224     @Override
225     public void notifyNode(Node node, Action type) {
226         LOG.debug("notifyNode: Node {} update {} from Controller's inventory Service", node, type);
227         Preconditions.checkNotNull(loadBalancerProvider);
228
229         for (NeutronLoadBalancer neutronLB: neutronLBCache.getAllNeutronLoadBalancers()) {
230             LoadBalancerConfiguration lbConfig = extractLBConfiguration(neutronLB);
231             if (!lbConfig.isValid()) {
232                 LOG.debug("Neutron LB configuration invalid for {} ", lbConfig.getName());
233             } else {
234                if (type.equals(Action.ADD)) {
235                    loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.ADD);
236
237                /* When node disappears, we do nothing for now. Making a call to
238                 * loadBalancerProvider.programLoadBalancerRules(node, lbConfig, Action.DELETE)
239                 * can lead to TransactionCommitFailedException. Similarly when node is changed,
240                 * because of remove followed by add, we do nothing.
241                 */
242
243                  //(type.equals(UpdateType.REMOVED) || type.equals(UpdateType.CHANGED))
244                }
245             }
246         }
247     }
248
249     @Override
250     public void setDependencies(ServiceReference serviceReference) {
251         loadBalancerProvider =
252                 (LoadBalancerProvider) ServiceHelper.getGlobalInstance(LoadBalancerProvider.class, this);
253         nodeCacheManager =
254                 (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this);
255         nodeCacheManager.cacheListenerAdded(serviceReference, this);
256         eventDispatcher =
257                 (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this);
258         eventDispatcher.eventHandlerAdded(serviceReference, this);
259     }
260
261     @Override
262     public void setDependencies(Object impl) {
263         if (impl instanceof INeutronNetworkCRUD) {
264             neutronNetworkCache = (INeutronNetworkCRUD)impl;
265         } else if (impl instanceof INeutronPortCRUD) {
266             neutronPortCache = (INeutronPortCRUD)impl;
267         } else if (impl instanceof INeutronSubnetCRUD) {
268             neutronSubnetCache = (INeutronSubnetCRUD)impl;
269         } else if (impl instanceof INeutronLoadBalancerCRUD) {
270             neutronLBCache = (INeutronLoadBalancerCRUD)impl;
271         } else if (impl instanceof INeutronLoadBalancerPoolCRUD) {
272             neutronLBPoolCache = (INeutronLoadBalancerPoolCRUD)impl;
273         } else if (impl instanceof LoadBalancerProvider) {
274             loadBalancerProvider = (LoadBalancerProvider)impl;
275         }
276     }
277 }