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