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