Merge "Bug 5174: Added AutoAttach attributes"
[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         bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
232
233         LOG.debug("Built with the intent to store bridge data {}",
234                 ovsdbBridgeAugmentationBuilder.build());
235         return bridgeNodeBuilder.build();
236     }
237
238     private void setManagedBy(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder) {
239         InstanceIdentifier<Node> connectionNodePath = getOvsdbConnectionInstance().getInstanceIdentifier();
240         ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
241     }
242
243     private void setDataPathType(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
244             Bridge bridge) {
245         ovsdbBridgeAugmentationBuilder.setDatapathType(
246                 SouthboundMapper.createDatapathType(bridge.getDatapathTypeColumn().getData()));
247     }
248
249     private void setFailMode(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
250             Bridge bridge) {
251         if (bridge.getFailModeColumn() != null
252                 && bridge.getFailModeColumn().getData() != null
253                 && !bridge.getFailModeColumn().getData().isEmpty()) {
254             String[] failmodeArray = new String[bridge.getFailModeColumn().getData().size()];
255             bridge.getFailModeColumn().getData().toArray(failmodeArray);
256             ovsdbBridgeAugmentationBuilder.setFailMode(
257                     SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get(failmodeArray[0]));
258         }
259     }
260
261     private void setOtherConfig(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
262             Bridge bridge) {
263         Map<String, String> otherConfigs = bridge
264                 .getOtherConfigColumn().getData();
265         if (otherConfigs != null && !otherConfigs.isEmpty()) {
266             Set<String> otherConfigKeys = otherConfigs.keySet();
267             List<BridgeOtherConfigs> otherConfigList = new ArrayList<>();
268             String otherConfigValue;
269             for (String otherConfigKey : otherConfigKeys) {
270                 otherConfigValue = otherConfigs.get(otherConfigKey);
271                 if (otherConfigKey != null && otherConfigValue != null) {
272                     otherConfigList.add(new BridgeOtherConfigsBuilder()
273                             .setBridgeOtherConfigKey(otherConfigKey)
274                             .setBridgeOtherConfigValue(otherConfigValue)
275                             .build());
276                 }
277             }
278             ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigList);
279         }
280     }
281
282     private void setExternalIds(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
283             Bridge bridge) {
284         Map<String, String> externalIds = bridge.getExternalIdsColumn()
285                 .getData();
286         if (externalIds != null && !externalIds.isEmpty()) {
287             Set<String> externalIdKeys = externalIds.keySet();
288             List<BridgeExternalIds> externalIdsList = new ArrayList<>();
289             String externalIdValue;
290             for (String externalIdKey : externalIdKeys) {
291                 externalIdValue = externalIds.get(externalIdKey);
292                 if (externalIdKey != null && externalIdValue != null) {
293                     externalIdsList.add(new BridgeExternalIdsBuilder()
294                             .setBridgeExternalIdKey(externalIdKey)
295                             .setBridgeExternalIdValue(externalIdValue)
296                             .build());
297                 }
298             }
299             ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIdsList);
300         }
301     }
302
303     private void setProtocol(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
304             Bridge bridge) {
305         if (SouthboundMapper.createMdsalProtocols(bridge) != null
306                 && SouthboundMapper.createMdsalProtocols(bridge).size() > 0) {
307             ovsdbBridgeAugmentationBuilder.setProtocolEntry(SouthboundMapper.createMdsalProtocols(bridge));
308         }
309     }
310
311     private void setDataPath(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
312             Bridge bridge) {
313         DatapathId dpid = SouthboundMapper.createDatapathId(bridge);
314         if (dpid != null) {
315             ovsdbBridgeAugmentationBuilder.setDatapathId(dpid);
316         }
317     }
318
319     private void setOpenFlowNodeRef(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
320             Bridge bridge) {
321         Map<UUID, Controller> updatedControllerRows =
322                 TyperUtils.extractRowsUpdated(Controller.class, getUpdates(), getDbSchema());
323         LOG.debug("setOpenFlowNodeRef: updatedControllerRows: {}", updatedControllerRows);
324         for (ControllerEntry controllerEntry: SouthboundMapper.createControllerEntries(bridge, updatedControllerRows)) {
325             if (controllerEntry != null
326                 && controllerEntry.isIsConnected() != null && controllerEntry.isIsConnected()) {
327                 String [] controllerTarget = controllerEntry.getTarget().getValue().split(":");
328                 IpAddress bridgeControllerIpAddress = null;
329                 PortNumber bridgeControllerPortNumber = null;
330                 for (String targetElement : controllerTarget) {
331                     if (InetAddresses.isInetAddress(targetElement)) {
332                         bridgeControllerIpAddress = new IpAddress(targetElement.toCharArray());
333                         continue;
334                     }
335                     if (NumberUtils.isNumber(targetElement)) {
336                         bridgeControllerPortNumber = new PortNumber(
337                                 Integer.valueOf(String.valueOf(targetElement)));
338                         continue;
339                     }
340                 }
341                 try {
342                     Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
343                 networkInterfacesLoop:
344                     while (networkInterfaces.hasMoreElements()) {
345                         NetworkInterface networkInterface = networkInterfaces.nextElement();
346                         Enumeration<InetAddress> networkInterfaceAddresses = networkInterface.getInetAddresses();
347                         while (networkInterfaceAddresses.hasMoreElements()) {
348                             InetAddress networkInterfaceAddress = networkInterfaceAddresses.nextElement();
349                             if (bridgeControllerIpAddress.getIpv4Address().getValue()
350                                     .equals(networkInterfaceAddress.getHostAddress())) {
351                                 ovsdbBridgeAugmentationBuilder.setBridgeOpenflowNodeRef(
352                                         getOvsdbConnectionInstance().getInstanceIdentifier());
353                                 break networkInterfacesLoop;
354                             }
355                         }
356                     }
357                 } catch (Exception e) {
358                     LOG.warn("Error getting local ip address", e);
359                 }
360             }
361         }
362     }
363     private InstanceIdentifier<Node> getInstanceIdentifier(Bridge bridge) {
364         return SouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
365                 bridge);
366     }
367
368     private NodeId getNodeId(Bridge bridge) {
369         NodeKey nodeKey = getInstanceIdentifier(bridge).firstKeyOf(Node.class, NodeKey.class);
370         return nodeKey.getNodeId();
371     }
372 }