80a6ed69cc67db72cc8df6ba30b3036af490b2ec
[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 =
122                 new ArrayList<InstanceIdentifier<BridgeOtherConfigs>>();
123
124         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
125
126         if (oldBridge != null && oldBridge.getOtherConfigColumn() != null) {
127             for (Entry<String, String> otherConfig:
128                 oldBridge.getOtherConfigColumn().getData().entrySet()) {
129                 if (bridge.getOtherConfigColumn() == null
130                         || !bridge.getOtherConfigColumn().getData().containsKey(otherConfig.getKey())) {
131                     InstanceIdentifier<BridgeOtherConfigs> iid = bridgeIid
132                             .augmentation(OvsdbBridgeAugmentation.class)
133                             .child(BridgeOtherConfigs.class,
134                                     new BridgeOtherConfigsKey(otherConfig.getKey()));
135                     result.add(iid);
136                 }
137             }
138         }
139         return result;
140     }
141
142     private List<InstanceIdentifier<BridgeExternalIds>> externalIdsToRemove(
143             InstanceIdentifier<Node> bridgeIid, Bridge bridge) {
144         Preconditions.checkNotNull(bridgeIid);
145         Preconditions.checkNotNull(bridge);
146         List<InstanceIdentifier<BridgeExternalIds>> result =
147                 new ArrayList<InstanceIdentifier<BridgeExternalIds>>();
148
149         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
150
151         if (oldBridge != null && oldBridge.getExternalIdsColumn() != null) {
152             for (Entry<String, String> externalId:
153                 oldBridge.getExternalIdsColumn().getData().entrySet()) {
154                 if (bridge.getExternalIdsColumn() == null
155                         || !bridge.getExternalIdsColumn().getData().containsKey(externalId.getKey())) {
156                     InstanceIdentifier<BridgeExternalIds> iid = bridgeIid
157                             .augmentation(OvsdbBridgeAugmentation.class)
158                             .child(BridgeExternalIds.class,
159                                     new BridgeExternalIdsKey(externalId.getKey()));
160                     result.add(iid);
161                 }
162             }
163         }
164         return result;
165     }
166
167     private List<InstanceIdentifier<ProtocolEntry>> protocolEntriesToRemove(
168             InstanceIdentifier<Node> bridgeIid, Bridge bridge) {
169         Preconditions.checkNotNull(bridgeIid);
170         Preconditions.checkNotNull(bridge);
171         List<InstanceIdentifier<ProtocolEntry>> result =
172                 new ArrayList<InstanceIdentifier<ProtocolEntry>>();
173         Bridge oldBridge = oldBridgeRows.get(bridge.getUuid());
174
175         try {
176             if (oldBridge != null && oldBridge.getProtocolsColumn() != null) {
177                 for (String protocol : oldBridge.getProtocolsColumn().getData()) {
178                     if (bridge.getProtocolsColumn() == null || !bridge.getProtocolsColumn().getData()
179                                 .contains(protocol)) {
180                         Class<? extends OvsdbBridgeProtocolBase> proto = SouthboundConstants.OVSDB_PROTOCOL_MAP
181                                 .inverse().get(protocol);
182                         InstanceIdentifier<ProtocolEntry> iid = bridgeIid
183                                 .augmentation(OvsdbBridgeAugmentation.class)
184                                 .child(ProtocolEntry.class,
185                                         new ProtocolEntryKey(proto));
186                         result.add(iid);
187                     }
188                 }
189             }
190         } catch (SchemaVersionMismatchException e) {
191             LOG.warn("protocol not supported by this version of ovsdb", e);
192         }
193         return result;
194     }
195
196     private Node buildConnectionNode(
197             Bridge bridge) {
198         //Update node with managed node reference
199         NodeBuilder connectionNode = new NodeBuilder();
200         connectionNode.setNodeId(getOvsdbConnectionInstance().getNodeId());
201
202         OvsdbNodeAugmentationBuilder ovsdbConnectionAugmentationBuilder = new OvsdbNodeAugmentationBuilder();
203         List<ManagedNodeEntry> managedBridges = new ArrayList<ManagedNodeEntry>();
204         InstanceIdentifier<Node> bridgeIid = SouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
205                 bridge);
206         ManagedNodeEntry managedBridge = new ManagedNodeEntryBuilder().setBridgeRef(
207                 new OvsdbBridgeRef(bridgeIid)).build();
208         managedBridges.add(managedBridge);
209         ovsdbConnectionAugmentationBuilder.setManagedNodeEntry(managedBridges);
210
211         connectionNode.addAugmentation(OvsdbNodeAugmentation.class, ovsdbConnectionAugmentationBuilder.build());
212
213         LOG.debug("Update node with bridge node ref {}",
214                 ovsdbConnectionAugmentationBuilder.getManagedNodeEntry().iterator().next());
215         return connectionNode.build();
216     }
217
218     private Node buildBridgeNode(Bridge bridge) {
219         NodeBuilder bridgeNodeBuilder = new NodeBuilder();
220         NodeId bridgeNodeId = getNodeId(bridge);
221         bridgeNodeBuilder.setNodeId(bridgeNodeId);
222         OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder = new OvsdbBridgeAugmentationBuilder();
223         ovsdbBridgeAugmentationBuilder.setBridgeName(new OvsdbBridgeName(bridge.getName()));
224         ovsdbBridgeAugmentationBuilder.setBridgeUuid(new Uuid(bridge.getUuid().toString()));
225         setDataPath(ovsdbBridgeAugmentationBuilder, bridge);
226         setDataPathType(ovsdbBridgeAugmentationBuilder, bridge);
227         setProtocol(ovsdbBridgeAugmentationBuilder, bridge);
228         setExternalIds(ovsdbBridgeAugmentationBuilder, bridge);
229         setOtherConfig(ovsdbBridgeAugmentationBuilder, bridge);
230         setFailMode(ovsdbBridgeAugmentationBuilder, bridge);
231         setOpenFlowNodeRef(ovsdbBridgeAugmentationBuilder, bridge);
232         setManagedBy(ovsdbBridgeAugmentationBuilder);
233         bridgeNodeBuilder.addAugmentation(OvsdbBridgeAugmentation.class, ovsdbBridgeAugmentationBuilder.build());
234
235         LOG.debug("Built with the intent to store bridge data {}",
236                 ovsdbBridgeAugmentationBuilder.build());
237         return bridgeNodeBuilder.build();
238     }
239
240     private void setManagedBy(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder) {
241         InstanceIdentifier<Node> connectionNodePath = getOvsdbConnectionInstance().getInstanceIdentifier();
242         ovsdbBridgeAugmentationBuilder.setManagedBy(new OvsdbNodeRef(connectionNodePath));
243     }
244
245     private void setDataPathType(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
246             Bridge bridge) {
247         ovsdbBridgeAugmentationBuilder.setDatapathType(
248                 SouthboundMapper.createDatapathType(bridge.getDatapathTypeColumn().getData()));
249     }
250
251     private void setFailMode(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
252             Bridge bridge) {
253         if (bridge.getFailModeColumn() != null
254                 && bridge.getFailModeColumn().getData() != null
255                 && !bridge.getFailModeColumn().getData().isEmpty()) {
256             String[] failmodeArray = new String[bridge.getFailModeColumn().getData().size()];
257             bridge.getFailModeColumn().getData().toArray(failmodeArray);
258             ovsdbBridgeAugmentationBuilder.setFailMode(
259                     SouthboundConstants.OVSDB_FAIL_MODE_MAP.inverse().get(failmodeArray[0]));
260         }
261     }
262
263     private void setOtherConfig(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
264             Bridge bridge) {
265         Map<String, String> otherConfigs = bridge
266                 .getOtherConfigColumn().getData();
267         if (otherConfigs != null && !otherConfigs.isEmpty()) {
268             Set<String> otherConfigKeys = otherConfigs.keySet();
269             List<BridgeOtherConfigs> otherConfigList = new ArrayList<BridgeOtherConfigs>();
270             String otherConfigValue;
271             for (String otherConfigKey : otherConfigKeys) {
272                 otherConfigValue = otherConfigs.get(otherConfigKey);
273                 if (otherConfigKey != null && otherConfigValue != null) {
274                     otherConfigList.add(new BridgeOtherConfigsBuilder()
275                             .setBridgeOtherConfigKey(otherConfigKey)
276                             .setBridgeOtherConfigValue(otherConfigValue)
277                             .build());
278                 }
279             }
280             ovsdbBridgeAugmentationBuilder.setBridgeOtherConfigs(otherConfigList);
281         }
282     }
283
284     private void setExternalIds(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
285             Bridge bridge) {
286         Map<String, String> externalIds = bridge.getExternalIdsColumn()
287                 .getData();
288         if (externalIds != null && !externalIds.isEmpty()) {
289             Set<String> externalIdKeys = externalIds.keySet();
290             List<BridgeExternalIds> externalIdsList = new ArrayList<BridgeExternalIds>();
291             String externalIdValue;
292             for (String externalIdKey : externalIdKeys) {
293                 externalIdValue = externalIds.get(externalIdKey);
294                 if (externalIdKey != null && externalIdValue != null) {
295                     externalIdsList.add(new BridgeExternalIdsBuilder()
296                             .setBridgeExternalIdKey(externalIdKey)
297                             .setBridgeExternalIdValue(externalIdValue)
298                             .build());
299                 }
300             }
301             ovsdbBridgeAugmentationBuilder.setBridgeExternalIds(externalIdsList);
302         }
303     }
304
305     private void setProtocol(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
306             Bridge bridge) {
307         if (SouthboundMapper.createMdsalProtocols(bridge) != null
308                 && SouthboundMapper.createMdsalProtocols(bridge).size() > 0) {
309             ovsdbBridgeAugmentationBuilder.setProtocolEntry(SouthboundMapper.createMdsalProtocols(bridge));
310         }
311     }
312
313     private void setDataPath(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
314             Bridge bridge) {
315         DatapathId dpid = SouthboundMapper.createDatapathId(bridge);
316         if (dpid != null) {
317             ovsdbBridgeAugmentationBuilder.setDatapathId(dpid);
318         }
319     }
320
321     private void setOpenFlowNodeRef(OvsdbBridgeAugmentationBuilder ovsdbBridgeAugmentationBuilder,
322             Bridge bridge) {
323         Map<UUID, Controller> updatedControllerRows =
324                 TyperUtils.extractRowsUpdated(Controller.class, getUpdates(), getDbSchema());
325         LOG.debug("setOpenFlowNodeRef: updatedControllerRows: {}", updatedControllerRows);
326         for (ControllerEntry controllerEntry: SouthboundMapper.createControllerEntries(bridge, updatedControllerRows)) {
327             if (controllerEntry != null
328                 && controllerEntry.isIsConnected() != null && controllerEntry.isIsConnected()) {
329                 String [] controllerTarget = controllerEntry.getTarget().getValue().split(":");
330                 IpAddress bridgeControllerIpAddress = null;
331                 PortNumber bridgeControllerPortNumber = null;
332                 for (String targetElement : controllerTarget) {
333                     if (InetAddresses.isInetAddress(targetElement)) {
334                         bridgeControllerIpAddress = new IpAddress(targetElement.toCharArray());
335                         continue;
336                     }
337                     if (NumberUtils.isNumber(targetElement)) {
338                         bridgeControllerPortNumber = new PortNumber(
339                                 Integer.valueOf(String.valueOf(targetElement)));
340                         continue;
341                     }
342                 }
343                 try {
344                     Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
345                 networkInterfacesLoop:
346                     while (networkInterfaces.hasMoreElements()) {
347                         NetworkInterface networkInterface = networkInterfaces.nextElement();
348                         Enumeration<InetAddress> networkInterfaceAddresses = networkInterface.getInetAddresses();
349                         while (networkInterfaceAddresses.hasMoreElements()) {
350                             InetAddress networkInterfaceAddress = networkInterfaceAddresses.nextElement();
351                             if (bridgeControllerIpAddress.getIpv4Address().getValue()
352                                     .equals(networkInterfaceAddress.getHostAddress())) {
353                                 ovsdbBridgeAugmentationBuilder.setBridgeOpenflowNodeRef(
354                                         getOvsdbConnectionInstance().getInstanceIdentifier());
355                                 break networkInterfacesLoop;
356                             }
357                         }
358                     }
359                 } catch (Exception e) {
360                     LOG.warn("Error getting local ip address {}", e);
361                 }
362             }
363         }
364     }
365     private InstanceIdentifier<Node> getInstanceIdentifier(Bridge bridge) {
366         return SouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
367                 bridge);
368     }
369
370     private NodeId getNodeId(Bridge bridge) {
371         NodeKey nodeKey = getInstanceIdentifier(bridge).firstKeyOf(Node.class, NodeKey.class);
372         return nodeKey.getNodeId();
373     }
374 }