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