Skeleton implementation of L3 using PipelineOrchestration
[ovsdb.git] / openstack / net-virt / src / main / java / org / opendaylight / ovsdb / openstack / netvirt / SouthboundHandler.java
1 /*
2  * Copyright (C) 2013 Red Hat, Inc.
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  * Authors : Madhu Venugopal, Brent Salisbury, Sam Hague, Dave Tucker
9  */
10 package org.opendaylight.ovsdb.openstack.netvirt;
11
12 import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
13 import org.opendaylight.controller.sal.core.Node;
14 import org.opendaylight.controller.sal.core.NodeConnector;
15 import org.opendaylight.controller.sal.core.Property;
16 import org.opendaylight.controller.sal.core.UpdateType;
17 import org.opendaylight.controller.switchmanager.IInventoryListener;
18 import org.opendaylight.ovsdb.lib.notation.Row;
19 import org.opendaylight.ovsdb.lib.notation.UUID;
20 import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
21 import org.opendaylight.ovsdb.openstack.netvirt.api.BridgeConfigurationManager;
22 import org.opendaylight.ovsdb.openstack.netvirt.api.NetworkingProviderManager;
23 import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager;
24 import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;
25 import org.opendaylight.ovsdb.plugin.api.OvsdbConfigurationService;
26 import org.opendaylight.ovsdb.plugin.api.OvsdbConnectionService;
27 import org.opendaylight.ovsdb.plugin.api.OvsdbInventoryListener;
28 import org.opendaylight.ovsdb.schema.openvswitch.Interface;
29 import org.opendaylight.ovsdb.schema.openvswitch.OpenVSwitch;
30 import org.opendaylight.ovsdb.schema.openvswitch.Port;
31
32 import com.google.common.collect.Lists;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import java.net.InetAddress;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40 import java.util.concurrent.ConcurrentMap;
41
42 public class SouthboundHandler extends AbstractHandler implements OvsdbInventoryListener,
43                                                                   IInventoryListener {
44     static final Logger logger = LoggerFactory.getLogger(SouthboundHandler.class);
45     //private Thread eventThread;
46     List<Node> nodeCache;
47
48     // The implementation for each of these services is resolved by the OSGi Service Manager
49     private volatile org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService configurationService;
50     private volatile BridgeConfigurationManager bridgeConfigurationManager;
51     private volatile TenantNetworkManager tenantNetworkManager;
52     private volatile NetworkingProviderManager networkingProviderManager;
53     private volatile OvsdbConfigurationService ovsdbConfigurationService;
54     private volatile OvsdbConnectionService connectionService;
55     private volatile NeutronL3Adapter neutronL3Adapter;
56
57     void init() {
58         nodeCache = Lists.newArrayList();
59     }
60
61     void start() {
62         this.triggerUpdates();
63     }
64
65     @Override
66     public void nodeAdded(Node node, InetAddress address, int port) {
67         this.enqueueEvent(new SouthboundEvent(node, Action.ADD));
68     }
69
70     @Override
71     public void nodeRemoved(Node node) {
72         this.enqueueEvent(new SouthboundEvent(node, Action.DELETE));
73     }
74
75     @Override
76     public void rowAdded(Node node, String tableName, String uuid, Row row) {
77         this.enqueueEvent(new SouthboundEvent(node, tableName, uuid, row, Action.ADD));
78     }
79
80     @Override
81     public void rowUpdated(Node node, String tableName, String uuid, Row oldRow, Row newRow) {
82         if (this.isUpdateOfInterest(node, oldRow, newRow)) {
83             this.enqueueEvent(new SouthboundEvent(node, tableName, uuid, newRow, Action.UPDATE));
84         }
85     }
86
87     /*
88      * Ignore unnecessary updates to be even considered for processing.
89      * (Especially stats update are fast and furious).
90      */
91
92     private boolean isUpdateOfInterest(Node node, Row oldRow, Row newRow) {
93         if (oldRow == null) return true;
94         if (newRow.getTableSchema().getName().equals(ovsdbConfigurationService.getTableName(node, Interface.class))) {
95             // We are NOT interested in Stats only updates
96             Interface oldIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, oldRow);
97             if (oldIntf.getName() == null && oldIntf.getExternalIdsColumn() == null && oldIntf.getMacColumn() == null &&
98                 oldIntf.getOpenFlowPortColumn() == null && oldIntf.getOptionsColumn() == null && oldIntf.getOtherConfigColumn() == null &&
99                 oldIntf.getTypeColumn() == null) {
100                 logger.trace("IGNORING Interface Update: node {}, row: {}", node, newRow);
101                 return false;
102             }
103         } else if (newRow.getTableSchema().getName().equals(ovsdbConfigurationService.getTableName(node, Port.class))) {
104             // We are NOT interested in Stats only updates
105             Port oldPort = ovsdbConfigurationService.getTypedRow(node, Port.class, oldRow);
106             if (oldPort.getName() == null && oldPort.getExternalIdsColumn() == null && oldPort.getMacColumn() == null &&
107                 oldPort.getInterfacesColumn() == null && oldPort.getTagColumn() == null && oldPort.getTrunksColumn() == null) {
108                 logger.trace("IGNORING Port Update: node {}, row: {}", node, newRow);
109                 return false;
110             }
111         } else if (newRow.getTableSchema().getName().equals(ovsdbConfigurationService.getTableName(node, OpenVSwitch.class))) {
112             OpenVSwitch oldOpenvSwitch = ovsdbConfigurationService.getTypedRow(node, OpenVSwitch.class, oldRow);
113             if (oldOpenvSwitch.getOtherConfigColumn()== null) {
114                 /* we are only interested in other_config field change */
115                 return false;
116             }
117         }
118         return true;
119     }
120
121     @Override
122     public void rowRemoved(Node node, String tableName, String uuid, Row row, Object context) {
123         this.enqueueEvent(new SouthboundEvent(node, tableName, uuid, row, context, Action.DELETE));
124     }
125
126     public void processNodeUpdate(Node node, Action action) {
127         if (action == Action.DELETE) return;
128         logger.trace("Process Node added {}", node);
129         bridgeConfigurationManager.prepareNode(node);
130     }
131
132     private void processRowUpdate(Node node, String tableName, String uuid, Row row,
133                                   Object context, Action action) {
134         if (action == Action.DELETE) {
135             if (tableName.equalsIgnoreCase(ovsdbConfigurationService.getTableName(node, Interface.class))) {
136                 logger.debug("Processing update of {}. Deleted node: {}, uuid: {}, row: {}", tableName, node, uuid, row);
137                 Interface deletedIntf = ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
138                 NeutronNetwork network = null;
139                 if (context == null) {
140                     network = tenantNetworkManager.getTenantNetwork(deletedIntf);
141                 } else {
142                     network = (NeutronNetwork)context;
143                 }
144                 List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(node);
145                 logger.info("Delete interface " + deletedIntf.getName());
146
147                 if (deletedIntf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
148                     deletedIntf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
149                     phyIfName.contains(deletedIntf.getName())) {
150                     /* delete tunnel interfaces or physical interfaces */
151                     this.handleInterfaceDelete(node, uuid, deletedIntf, false, null);
152                 } else if (network != null && !network.getRouterExternal()) {
153                     logger.debug("Processing update of {}:{} node {} intf {} network {}",
154                             tableName, action, node, uuid, network.getNetworkUUID());
155                     try {
156                         ConcurrentMap<String, Row> interfaces = this.ovsdbConfigurationService
157                                 .getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
158                         if (interfaces != null) {
159                             boolean isLastInstanceOnNode = true;
160                             for (String intfUUID : interfaces.keySet()) {
161                                 if (intfUUID.equals(uuid)) continue;
162                                 Interface intf = this.ovsdbConfigurationService.getTypedRow(node, Interface.class, interfaces.get(intfUUID));
163                                 NeutronNetwork neutronNetwork = tenantNetworkManager.getTenantNetwork(intf);
164                                 if (neutronNetwork != null && neutronNetwork.equals(network)) isLastInstanceOnNode = false;
165                             }
166                             this.handleInterfaceDelete(node, uuid, deletedIntf, isLastInstanceOnNode, network);
167                         }
168                     } catch (Exception e) {
169                         logger.error("Error fetching Interface Rows for node " + node, e);
170                     }
171                 }
172             }
173         }
174         else if (tableName.equalsIgnoreCase(ovsdbConfigurationService.getTableName(node, Interface.class))) {
175             logger.debug("Processing update of {}:{} node: {}, interface uuid: {}, row: {}",
176                     tableName, action, node, uuid, row);
177             Interface intf = this.ovsdbConfigurationService.getTypedRow(node, Interface.class, row);
178             NeutronNetwork network = tenantNetworkManager.getTenantNetwork(intf);
179             if (network != null && !network.getRouterExternal()) {
180                 if (networkingProviderManager.getProvider(node).hasPerTenantTunneling()) {
181                     int vlan = tenantNetworkManager.networkCreated(node, network.getID());
182                     String portUUID = this.getPortIdForInterface(node, uuid, intf);
183                     if (portUUID != null) {
184                         logger.debug("Neutron Network {}:{} Created with Internal vlan {} port {}",
185                                  network.getNetworkUUID(), network.getNetworkName(), vlan, portUUID);
186                         tenantNetworkManager.programInternalVlan(node, portUUID, network);
187                     } else {
188                         logger.trace("Neutron Network {}:{} Created with Internal vlan {} but have no portUUID",
189                                  network.getNetworkUUID(), network.getNetworkName(), vlan);
190                     }
191                 }
192                 this.handleInterfaceUpdate(node, uuid, intf);
193             }
194
195         } else if (tableName.equalsIgnoreCase(ovsdbConfigurationService.getTableName(node, Port.class))) {
196             logger.debug("Processing update of {}:{} node: {}, port uuid: {}, row: {}", tableName, action, node, uuid, row);
197             Port port = this.ovsdbConfigurationService.getTypedRow(node, Port.class, row);
198             Set<UUID> interfaceUUIDs = port.getInterfacesColumn().getData();
199             for (UUID intfUUID : interfaceUUIDs) {
200                 logger.trace("Scanning interface "+intfUUID);
201                 try {
202                     Row intfRow = this.ovsdbConfigurationService
203                             .getRow(node, ovsdbConfigurationService.getTableName(node, Interface.class),
204                                     intfUUID.toString());
205                     Interface intf = this.ovsdbConfigurationService.getTypedRow(node, Interface.class, intfRow);
206                     NeutronNetwork network = tenantNetworkManager.getTenantNetwork(intf);
207                     if (network != null && !network.getRouterExternal()) {
208                          logger.debug("Processing update of {}:{} node {} intf {} network {}",
209                                  tableName, action, node, intfUUID, network.getNetworkUUID());
210                         tenantNetworkManager.programInternalVlan(node, uuid, network);
211                         this.handleInterfaceUpdate(node, intfUUID.toString(), intf);
212                     } else {
213                         logger.trace("Ignoring update because there is not a neutron network {} for port {}, interface {}",
214                                 network, uuid, intfUUID);
215                     }
216                 } catch (Exception e) {
217                     logger.error("Failed to process row update", e);
218                 }
219             }
220         } else if (tableName.equalsIgnoreCase(ovsdbConfigurationService.getTableName(node, OpenVSwitch.class))) {
221             logger.debug("Processing update of {}:{} node: {}, ovs uuid: {}, row: {}", tableName, action, node, uuid, row);
222             try {
223                 ConcurrentMap<String, Row> interfaces = this.ovsdbConfigurationService
224                         .getRows(node, ovsdbConfigurationService.getTableName(node, Interface.class));
225                 if (interfaces != null) {
226                     for (String intfUUID : interfaces.keySet()) {
227                         Interface intf = ovsdbConfigurationService.getTypedRow(node, Interface.class, interfaces.get(intfUUID));
228                         this.handleInterfaceUpdate(node, intfUUID, intf);
229                     }
230                 }
231             } catch (Exception e) {
232                 logger.error("Error fetching Interface Rows for node " + node, e);
233             }
234         }
235     }
236
237     private void handleInterfaceUpdate (Node node, String uuid, Interface intf) {
238         logger.trace("Interface update of node: {}, uuid: {}", node, uuid);
239         NeutronNetwork network = tenantNetworkManager.getTenantNetwork(intf);
240         if (network != null) {
241             neutronL3Adapter.handleInterfaceEvent(node, intf, network, Action.UPDATE);
242             if (bridgeConfigurationManager.createLocalNetwork(node, network))
243                 networkingProviderManager.getProvider(node).handleInterfaceUpdate(network, node, intf);
244         } else {
245             logger.debug("No tenant network found on node: {}, uuid: {} for interface: {}", node, uuid, intf);
246         }
247     }
248
249     private void handleInterfaceDelete (Node node, String uuid, Interface intf, boolean isLastInstanceOnNode,
250                                         NeutronNetwork network) {
251         logger.debug("handleInterfaceDelete: node: {}, uuid: {}, isLastInstanceOnNode: {}, interface: {}",
252                 node, uuid, isLastInstanceOnNode, intf);
253
254         neutronL3Adapter.handleInterfaceEvent(node, intf, network, Action.DELETE);
255         List<String> phyIfName = bridgeConfigurationManager.getAllPhysicalInterfaceNames(node);
256         if (intf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VXLAN) ||
257             intf.getTypeColumn().getData().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_GRE) ||
258             phyIfName.contains(intf.getName())) {
259             /* delete tunnel or physical interfaces */
260             networkingProviderManager.getProvider(node).handleInterfaceDelete(intf.getTypeColumn().getData(), null, node, intf, isLastInstanceOnNode);
261         } else if (network != null) {
262             if (!network.getProviderNetworkType().equalsIgnoreCase(NetworkHandler.NETWORK_TYPE_VLAN)) { /* vlan doesn't need a tunnel endpoint */
263                 if (configurationService.getTunnelEndPoint(node) == null) {
264                     logger.error("Tunnel end-point configuration missing. Please configure it in OpenVSwitch Table");
265                     return;
266                 }
267             }
268             if (isLastInstanceOnNode & networkingProviderManager.getProvider(node).hasPerTenantTunneling()) {
269                 tenantNetworkManager.reclaimInternalVlan(node, uuid, network);
270             }
271             networkingProviderManager.getProvider(node).handleInterfaceDelete(network.getProviderNetworkType(), network, node, intf, isLastInstanceOnNode);
272         }
273     }
274
275     private String getPortIdForInterface (Node node, String uuid, Interface intf) {
276         try {
277             Map<String, Row> ports = this.ovsdbConfigurationService.getRows(node, ovsdbConfigurationService.getTableName(node, Port.class));
278             if (ports == null) return null;
279             for (String portUUID : ports.keySet()) {
280                 Port port = ovsdbConfigurationService.getTypedRow(node, Port.class, ports.get(portUUID));
281                 Set<UUID> interfaceUUIDs = port.getInterfacesColumn().getData();
282                 logger.trace("Scanning Port {} to identify interface : {} ",port, uuid);
283                 for (UUID intfUUID : interfaceUUIDs) {
284                     if (intfUUID.toString().equalsIgnoreCase(uuid)) {
285                         logger.trace("Found Interface {} -> {}", uuid, portUUID);
286                         return portUUID;
287                     }
288                 }
289             }
290         } catch (Exception e) {
291             logger.debug("Failed to get Port tag for for Intf {}:{}", intf, e);
292         }
293         return null;
294     }
295
296     @Override
297     public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
298         logger.debug("notifyNode: Node {} update {} from Controller's inventory Service", node, type);
299
300         // Add the Node Type check back once the Consistency issue is resolved between MD-SAL and AD-SAL
301         if (!type.equals(UpdateType.REMOVED) && !nodeCache.contains(node)) {
302             nodeCache.add(node);
303             networkingProviderManager.getProvider(node).initializeOFFlowRules(node);
304         } else if (type.equals(UpdateType.REMOVED)){
305             nodeCache.remove(node);
306         }
307     }
308
309     @Override
310     public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
311         //We are not interested in the nodeConnectors at this moment
312     }
313
314     private void triggerUpdates() {
315         List<Node> nodes = connectionService.getNodes();
316         if (nodes == null) return;
317         for (Node node : nodes) {
318             try {
319                 List<String> tableNames = ovsdbConfigurationService.getTables(node);
320                 if (tableNames == null) continue;
321                 for (String tableName : tableNames) {
322                     Map<String, Row> rows = ovsdbConfigurationService.getRows(node, tableName);
323                     if (rows == null) continue;
324                     for (String uuid : rows.keySet()) {
325                         Row row = rows.get(uuid);
326                         this.rowAdded(node, tableName, uuid, row);
327                     }
328                 }
329             } catch (Exception e) {
330                 logger.error("Exception during OVSDB Southbound update trigger", e);
331             }
332         }
333     }
334
335     /**
336      * Process the event.
337      *
338      * @param abstractEvent the {@link org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent} event to be handled.
339      * @see EventDispatcher
340      */
341     @Override
342     public void processEvent(AbstractEvent abstractEvent) {
343         if (!(abstractEvent instanceof SouthboundEvent)) {
344             logger.error("Unable to process abstract event " + abstractEvent);
345             return;
346         }
347         SouthboundEvent ev = (SouthboundEvent) abstractEvent;
348         switch (ev.getType()) {
349             case NODE:
350                 try {
351                     processNodeUpdate(ev.getNode(), ev.getAction());
352                 } catch (Exception e) {
353                     logger.error("Exception caught in ProcessNodeUpdate for node " + ev.getNode(), e);
354                 }
355                 break;
356             case ROW:
357                 try {
358                     processRowUpdate(ev.getNode(), ev.getTableName(), ev.getUuid(), ev.getRow(),
359                                      ev.getContext(),ev.getAction());
360                 } catch (Exception e) {
361                     logger.error("Exception caught in ProcessRowUpdate for node " + ev.getNode(), e);
362                 }
363                 break;
364             default:
365                 logger.warn("Unable to process type " + ev.getType() +
366                             " action " + ev.getAction() + " for node " + ev.getNode());
367                 break;
368         }
369     }
370 }