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