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