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