Merge "BUG-4417 Program tunnel flows on new Neutron nodes"
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / transactions / md / OvsdbBridgeUpdateCommand.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
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
9 package org.opendaylight.ovsdb.southbound.transactions.md;
10
11 import java.net.InetAddress;
12 import java.net.NetworkInterface;
13 import java.util.ArrayList;
14 import java.util.Enumeration;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Set;
19
20 import org.apache.commons.lang3.math.NumberUtils;
21 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
24 import org.opendaylight.ovsdb.lib.message.TableUpdates;
25 import org.opendaylight.ovsdb.lib.notation.UUID;
26 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
27 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
28 import org.opendaylight.ovsdb.schema.openvswitch.Bridge;
29 import org.opendaylight.ovsdb.schema.openvswitch.Controller;
30 import org.opendaylight.ovsdb.southbound.OvsdbConnectionInstance;
31 import org.opendaylight.ovsdb.southbound.SouthboundConstants;
32 import org.opendaylight.ovsdb.southbound.SouthboundMapper;
33 import org.opendaylight.ovsdb.southbound.SouthboundUtil;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.DatapathId;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentationBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeName;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeProtocolBase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeRef;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentationBuilder;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeRef;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIds;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIdsBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeExternalIdsKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigs;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.BridgeOtherConfigsKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ControllerEntry;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntry;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.bridge.attributes.ProtocolEntryKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntry;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.ManagedNodeEntryBuilder;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
60 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
61 import org.opendaylight.yangtools.yang.binding.DataObject;
62 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import com.google.common.base.Optional;
67 import com.google.common.base.Preconditions;
68 import com.google.common.net.InetAddresses;
69
70 public class OvsdbBridgeUpdateCommand extends AbstractTransactionCommand {
71     private static final Logger LOG = LoggerFactory.getLogger(OvsdbBridgeUpdateCommand.class);
72     private Map<UUID,Bridge> updatedBridgeRows;
73     private Map<UUID, Bridge> oldBridgeRows;
74
75     public OvsdbBridgeUpdateCommand(OvsdbConnectionInstance key, TableUpdates updates,
76             DatabaseSchema dbSchema) {
77         super(key,updates,dbSchema);
78         updatedBridgeRows = TyperUtils.extractRowsUpdated(Bridge.class, getUpdates(), getDbSchema());
79         oldBridgeRows = TyperUtils.extractRowsOld(Bridge.class, getUpdates(), getDbSchema());
80     }
81
82     @Override
83     public void execute(ReadWriteTransaction transaction) {
84         for (Entry<UUID, Bridge> entry : updatedBridgeRows.entrySet()) {
85             updateBridge(transaction, entry.getValue());
86         }
87     }
88
89     private void updateBridge(ReadWriteTransaction transaction,
90             Bridge bridge) {
91         final InstanceIdentifier<Node> connectionIId = getOvsdbConnectionInstance().getInstanceIdentifier();
92         Optional<Node> connection = SouthboundUtil.readNode(transaction, connectionIId);
93         if (connection.isPresent()) {
94             LOG.debug("Connection {} is present",connection);
95
96             // Update the connection node to let it know it manages this bridge
97             Node connectionNode = buildConnectionNode(bridge);
98             transaction.merge(LogicalDatastoreType.OPERATIONAL, connectionIId, connectionNode);
99
100             // Update the bridge node with whatever data we are getting
101             InstanceIdentifier<Node> bridgeIid = getInstanceIdentifier(bridge);
102             Node bridgeNode = buildBridgeNode(bridge);
103             transaction.merge(LogicalDatastoreType.OPERATIONAL, bridgeIid, bridgeNode);
104             deleteEntries(transaction, protocolEntriesToRemove(bridgeIid,bridge));
105             deleteEntries(transaction, externalIdsToRemove(bridgeIid,bridge));
106             deleteEntries(transaction, bridgeOtherConfigsToRemove(bridgeIid,bridge));
107         }
108     }
109
110     private <T extends DataObject> void deleteEntries(ReadWriteTransaction transaction,
111             List<InstanceIdentifier<T>> entryIids) {
112         for (InstanceIdentifier<T> entryIid: entryIids) {
113             transaction.delete(LogicalDatastoreType.OPERATIONAL, entryIid);
114         }
115     }
116
117     private List<InstanceIdentifier<BridgeOtherConfigs>> bridgeOtherConfigsToRemove(
118             InstanceIdentifier<Node> bridgeIid, Bridge bridge) {
119         Preconditions.checkNotNull(bridgeIid);
120         Preconditions.checkNotNull(bridge);
121         List<InstanceIdentifier<BridgeOtherConfigs>> result = new ArrayList<>();
122
123         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
124
125         if (oldBridge != null && oldBridge.getOtherConfigColumn() != null) {
126             for (Entry<String, String> otherConfig:
127                 oldBridge.getOtherConfigColumn().getData().entrySet()) {
128                 if (bridge.getOtherConfigColumn() == null
129                         || !bridge.getOtherConfigColumn().getData().containsKey(otherConfig.getKey())) {
130                     InstanceIdentifier<BridgeOtherConfigs> iid = bridgeIid
131                             .augmentation(OvsdbBridgeAugmentation.class)
132                             .child(BridgeOtherConfigs.class,
133                                     new BridgeOtherConfigsKey(otherConfig.getKey()));
134                     result.add(iid);
135                 }
136             }
137         }
138         return result;
139     }
140
141     private List<InstanceIdentifier<BridgeExternalIds>> externalIdsToRemove(
142             InstanceIdentifier<Node> bridgeIid, Bridge bridge) {
143         Preconditions.checkNotNull(bridgeIid);
144         Preconditions.checkNotNull(bridge);
145         List<InstanceIdentifier<BridgeExternalIds>> result = new ArrayList<>();
146
147         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
148
149         if (oldBridge != null && oldBridge.getExternalIdsColumn() != null) {
150             for (Entry<String, String> externalId:
151                 oldBridge.getExternalIdsColumn().getData().entrySet()) {
152                 if (bridge.getExternalIdsColumn() == null
153                         || !bridge.getExternalIdsColumn().getData().containsKey(externalId.getKey())) {
154                     InstanceIdentifier<BridgeExternalIds> iid = bridgeIid
155                             .augmentation(OvsdbBridgeAugmentation.class)
156                             .child(BridgeExternalIds.class,
157                                     new BridgeExternalIdsKey(externalId.getKey()));
158                     result.add(iid);
159                 }
160             }
161         }
162         return result;
163     }
164
165     private List<InstanceIdentifier<ProtocolEntry>> protocolEntriesToRemove(
166             InstanceIdentifier<Node> bridgeIid, Bridge bridge) {
167         Preconditions.checkNotNull(bridgeIid);
168         Preconditions.checkNotNull(bridge);
169         List<InstanceIdentifier<ProtocolEntry>> result = new ArrayList<>();
170         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
171
172         try {
173             if (oldBridge != null && oldBridge.getProtocolsColumn() != null) {
174                 for (String protocol : oldBridge.getProtocolsColumn().getData()) {
175                     if (bridge.getProtocolsColumn() == null || !bridge.getProtocolsColumn().getData()
176                                 .contains(protocol)) {
177                         Class<? extends OvsdbBridgeProtocolBase> proto = SouthboundConstants.OVSDB_PROTOCOL_MAP
178                                 .inverse().get(protocol);
179                         InstanceIdentifier<ProtocolEntry> iid = bridgeIid
180                                 .augmentation(OvsdbBridgeAugmentation.class)
181                                 .child(ProtocolEntry.class,
182                                         new ProtocolEntryKey(proto));
183                         result.add(iid);
184                     }
185                 }
186             }
187         } catch (SchemaVersionMismatchException e) {
188             // We don't care about the exception stack trace here
189             LOG.warn("protocol not supported by this version of ovsdb: {}", e.getMessage());
190         }
191         return result;
192     }
193
194     private Node buildConnectionNode(
195             Bridge bridge) {
196         //Update node with managed node reference
197         NodeBuilder connectionNode = new NodeBuilder();
198         connectionNode.setNodeId(getOvsdbConnectionInstance().getNodeId());
199
200         OvsdbNodeAugmentationBuilder ovsdbConnectionAugmentationBuilder = new OvsdbNodeAugmentationBuilder();
201         List<ManagedNodeEntry> managedBridges = new ArrayList<>();
202         InstanceIdentifier<Node> bridgeIid = SouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
203                 bridge);
204         ManagedNodeEntry managedBridge = new ManagedNodeEntryBuilder().setBridgeRef(
205                 new OvsdbBridgeRef(bridgeIid)).build();
206         managedBridges.add(managedBridge);
207         ovsdbConnectionAugmentationBuilder.setManagedNodeEntry(managedBridges);
208
209         connectionNode.addAugmentation(OvsdbNodeAugmentation.class, ovsdbConnectionAugmentationBuilder.build());
210
211         LOG.debug("Update node with bridge node ref {}",
212                 ovsdbConnectionAugmentationBuilder.getManagedNodeEntry().iterator().next());
213         return connectionNode.build();
214     }
215
216     private Node buildBridgeNode(Bridge bridge) {
217         NodeBuilder bridgeNodeBuilder = new NodeBuilder();
218         NodeId bridgeNodeId = getNodeId(bridge);
219         bridgeNodeBuilder.setNodeId(bridgeNodeId);
220         OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
221         ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridge.getName()));
222         ovsdbBridgeAugmentationBuilder.setBridgeUuid(new Uuid(bridge.getUuid().toString()));
223         setDataPath(ovsdbBridgeAugmentationBuilder, bridge);
224         setDataPathType(ovsdbBridgeAugmentationBuilder, bridge);
225         setProtocol(ovsdbBridgeAugmentationBuilder, bridge);
226         setExternalIds(ovsdbBridgeAugmentationBuilder, bridge);
227         setOtherConfig(ovsdbBridgeAugmentationBuilder, bridge);
228         setFailMode(ovsdbBridgeAugmentationBuilder, bridge);
229         setOpenFlowNodeRef(ovsdbBridgeAugmentationBuilder, bridge);
230         setManagedBy(ovsdbBridgeAugmentationBuilder);
231         setAutoAttach(ovsdbBridgeAugmentationBuilder, bridge);
232         bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
233
234         LOG.debug("Built with the intent to store bridge data {}",
235                 ovsdbBridgeAugmentationBuilder.build());
236         return bridgeNodeBuilder.build();
237     }
238
239     private void setAutoAttach(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
240             Bridge bridge) {
241         try {
242             if (bridge.getAutoAttachColumn() != null
243                     && bridge.getAutoAttachColumn().getData() != null
244                     && !bridge.getAutoAttachColumn().getData().isEmpty()) {
245                 Set<UUID> uuids = bridge.getAutoAttachColumn().getData();
246                 for (UUID uuid : uuids) {
247                     ovsdbBridgeAugmentationBuilder.setAutoAttach(new Uuid(uuid.toString()));
248                 }
249             }
250         } catch (SchemaVersionMismatchException e) {
251             LOG.debug("auto_attach column for Bridge Table unsupported for this version of ovsdb schema. {}", e);
252         }
253     }
254
255     private void setManagedBy(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder) {
256         InstanceIdentifier<Node> connectionNodePath = getOvsdbConnectionInstance().getInstanceIdentifier();
257         ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
258     }
259
260     private void setDataPathType(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
261             Bridge bridge) {
262         ovsdbBridgeAugmentationBuilder.setDatapathType(
263                 SouthboundMapper.createDatapathType(bridge.getDatapathTypeColumn().getData()));
264     }
265
266     private void setFailMode(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
267             Bridge bridge) {
268         if (bridge.getFailModeColumn() != null
269                 && bridge.getFailModeColumn().getData() != null
270                 && !bridge.getFailModeColumn().getData().isEmpty()) {
271             String[] failmodeArray = new String[bridge.getFailModeColumn().getData().size()];
272             bridge.getFailModeColumn().getData().toArray(failmodeArray);
273             ovsdbBridgeAugmentationBuilder.setFailMode(
274                     SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get(failmodeArray[0]));
275         }
276     }
277
278     private void setOtherConfig(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
279             Bridge bridge) {
280         Map<String, String> otherConfigs = bridge
281                 .getOtherConfigColumn().getData();
282         if (otherConfigs != null && !otherConfigs.isEmpty()) {
283             Set<String> otherConfigKeys = otherConfigs.keySet();
284             List<BridgeOtherConfigs> otherConfigList = new ArrayList<>();
285             String otherConfigValue;
286             for (String otherConfigKey : otherConfigKeys) {
287                 otherConfigValue = otherConfigs.get(otherConfigKey);
288                 if (otherConfigKey != null && otherConfigValue != null) {
289                     otherConfigList.add(new BridgeOtherConfigsBuilder()
290                             .setBridgeOtherConfigKey(otherConfigKey)
291                             .setBridgeOtherConfigValue(otherConfigValue)
292                             .build());
293                 }
294             }
295             ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigList);
296         }
297     }
298
299     private void setExternalIds(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
300             Bridge bridge) {
301         Map<String, String> externalIds = bridge.getExternalIdsColumn()
302                 .getData();
303         if (externalIds != null && !externalIds.isEmpty()) {
304             Set<String> externalIdKeys = externalIds.keySet();
305             List<BridgeExternalIds> externalIdsList = new ArrayList<>();
306             String externalIdValue;
307             for (String externalIdKey : externalIdKeys) {
308                 externalIdValue = externalIds.get(externalIdKey);
309                 if (externalIdKey != null && externalIdValue != null) {
310                     externalIdsList.add(new BridgeExternalIdsBuilder()
311                             .setBridgeExternalIdKey(externalIdKey)
312                             .setBridgeExternalIdValue(externalIdValue)
313                             .build());
314                 }
315             }
316             ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIdsList);
317         }
318     }
319
320     private void setProtocol(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
321             Bridge bridge) {
322         if (SouthboundMapper.createMdsalProtocols(bridge) != null
323                 && SouthboundMapper.createMdsalProtocols(bridge).size() > 0) {
324             ovsdbBridgeAugmentationBuilder.setProtocolEntry(SouthboundMapper.createMdsalProtocols(bridge));
325         }
326     }
327
328     private void setDataPath(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
329             Bridge bridge) {
330         DatapathId dpid = SouthboundMapper.createDatapathId(bridge);
331         if (dpid != null) {
332             ovsdbBridgeAugmentationBuilder.setDatapathId(dpid);
333         }
334     }
335
336     private void setOpenFlowNodeRef(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
337             Bridge bridge) {
338         Map<UUID, Controller> updatedControllerRows =
339                 TyperUtils.extractRowsUpdated(Controller.class, getUpdates(), getDbSchema());
340         LOG.debug("setOpenFlowNodeRef: updatedControllerRows: {}", updatedControllerRows);
341         for (ControllerEntry controllerEntry: SouthboundMapper.createControllerEntries(bridge, updatedControllerRows)) {
342             if (controllerEntry != null
343                 && controllerEntry.isIsConnected() != null && controllerEntry.isIsConnected()) {
344                 String [] controllerTarget = controllerEntry.getTarget().getValue().split(":");
345                 IpAddress bridgeControllerIpAddress = null;
346                 PortNumber bridgeControllerPortNumber = null;
347                 for (String targetElement : controllerTarget) {
348                     if (InetAddresses.isInetAddress(targetElement)) {
349                         bridgeControllerIpAddress = new IpAddress(targetElement.toCharArray());
350                         continue;
351                     }
352                     if (NumberUtils.isNumber(targetElement)) {
353                         bridgeControllerPortNumber = new PortNumber(
354                                 Integer.valueOf(String.valueOf(targetElement)));
355                         continue;
356                     }
357                 }
358                 try {
359                     Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
360                 networkInterfacesLoop:
361                     while (networkInterfaces.hasMoreElements()) {
362                         NetworkInterface networkInterface = networkInterfaces.nextElement();
363                         Enumeration<InetAddress> networkInterfaceAddresses = networkInterface.getInetAddresses();
364                         while (networkInterfaceAddresses.hasMoreElements()) {
365                             InetAddress networkInterfaceAddress = networkInterfaceAddresses.nextElement();
366                             if (bridgeControllerIpAddress.getIpv4Address().getValue()
367                                     .equals(networkInterfaceAddress.getHostAddress())) {
368                                 ovsdbBridgeAugmentationBuilder.setBridgeOpenflowNodeRef(
369                                         getOvsdbConnectionInstance().getInstanceIdentifier());
370                                 break networkInterfacesLoop;
371                             }
372                         }
373                     }
374                 } catch (Exception e) {
375                     LOG.warn("Error getting local ip address", e);
376                 }
377             }
378         }
379     }
380     private InstanceIdentifier<Node> getInstanceIdentifier(Bridge bridge) {
381         return SouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
382                 bridge);
383     }
384
385     private NodeId getNodeId(Bridge bridge) {
386         NodeKey nodeKey = getInstanceIdentifier(bridge).firstKeyOf(Node.class, NodeKey.class);
387         return nodeKey.getNodeId();
388     }
389 }