Make TransactionBuilder type-aware
[ovsdb.git] / southbound / southbound-impl / src / main / java / org / opendaylight / ovsdb / southbound / ovsdb / transact / TerminationPointUpdateCommand.java
1 /*
2  * Copyright © 2015, 2017 Brocade Communications 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 package org.opendaylight.ovsdb.southbound.ovsdb.transact;
9
10 import static java.nio.charset.StandardCharsets.UTF_8;
11 import static org.opendaylight.ovsdb.lib.operations.Operations.op;
12 import static org.opendaylight.ovsdb.southbound.SouthboundUtil.schemaMismatchLog;
13
14 import com.google.common.base.Optional;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.Set;
25 import java.util.concurrent.ExecutionException;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
27 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
30 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
31 import org.opendaylight.ovsdb.lib.notation.UUID;
32 import org.opendaylight.ovsdb.lib.operations.TransactionBuilder;
33 import org.opendaylight.ovsdb.schema.openvswitch.Interface;
34 import org.opendaylight.ovsdb.schema.openvswitch.Port;
35 import org.opendaylight.ovsdb.southbound.InstanceIdentifierCodec;
36 import org.opendaylight.ovsdb.southbound.SouthboundConstants;
37 import org.opendaylight.ovsdb.southbound.SouthboundProvider;
38 import org.opendaylight.ovsdb.southbound.SouthboundUtil;
39 import org.opendaylight.ovsdb.utils.yang.YangUtils;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbNodeAugmentation;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbPortInterfaceAttributes.VlanMode;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbQosRef;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.node.attributes.QosEntries;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceBfd;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceExternalIds;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceLldp;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.InterfaceOtherConfigs;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Options;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortExternalIds;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.PortOtherConfigs;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.ovsdb.port._interface.attributes.Trunks;
55 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.opendaylight.yangtools.yang.common.Uint16;
58 import org.opendaylight.yangtools.yang.common.Uint32;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public class TerminationPointUpdateCommand implements TransactCommand {
63
64     private static final Logger LOG = LoggerFactory.getLogger(TerminationPointUpdateCommand.class);
65
66     @Override
67     public void execute(final TransactionBuilder transaction, final BridgeOperationalState state,
68             final DataChangeEvent events, final InstanceIdentifierCodec instanceIdentifierCodec) {
69         execute(transaction, state,
70                 TransactUtils.extractCreatedOrUpdated(events, OvsdbTerminationPointAugmentation.class),
71                 instanceIdentifierCodec);
72     }
73
74     @Override
75     public void execute(final TransactionBuilder transaction, final BridgeOperationalState state,
76             final Collection<DataTreeModification<Node>> modifications,
77             final InstanceIdentifierCodec instanceIdentifierCodec) {
78         execute(transaction, state,
79                 TransactUtils.extractCreatedOrUpdated(modifications, OvsdbTerminationPointAugmentation.class),
80                 instanceIdentifierCodec);
81     }
82
83     private void execute(final TransactionBuilder transaction, final BridgeOperationalState state,
84             final Map<InstanceIdentifier<OvsdbTerminationPointAugmentation>, OvsdbTerminationPointAugmentation>
85                     createdOrUpdated,
86             final InstanceIdentifierCodec instanceIdentifierCodec) {
87         for (Entry<InstanceIdentifier<OvsdbTerminationPointAugmentation>,
88                  OvsdbTerminationPointAugmentation> terminationPointEntry : createdOrUpdated.entrySet()) {
89             updateTerminationPoint(transaction, state, terminationPointEntry.getKey(),
90                     terminationPointEntry.getValue(), instanceIdentifierCodec);
91         }
92     }
93
94     public void updateTerminationPoint(final TransactionBuilder transaction, final BridgeOperationalState state,
95             final InstanceIdentifier<OvsdbTerminationPointAugmentation> iid,
96             final OvsdbTerminationPointAugmentation terminationPoint,
97             final InstanceIdentifierCodec instanceIdentifierCodec) {
98
99         if (terminationPoint != null) {
100             LOG.debug("Received request to update termination point {}",
101                    terminationPoint.getName());
102
103             // Update interface
104             Interface ovsInterface = transaction.getTypedRowWrapper(Interface.class);
105             updateInterface(terminationPoint, ovsInterface);
106             Interface extraInterface = transaction.getTypedRowWrapper(Interface.class);
107             extraInterface.setName("");
108             transaction.add(op.update(ovsInterface)
109                     .where(extraInterface.getNameColumn().getSchema().opEqual(terminationPoint.getName()))
110                     .build());
111
112             TerminationPointCreateCommand.stampInstanceIdentifier(transaction,
113                     iid.firstIdentifierOf(OvsdbTerminationPointAugmentation.class), terminationPoint.getName(),
114                     instanceIdentifierCodec);
115             final String opendaylightIid = instanceIdentifierCodec.serialize(iid);
116             // Update port
117             // Bug#6136
118             Optional<OvsdbBridgeAugmentation> ovsdbBridgeOptional = state.getOvsdbBridgeAugmentation(iid);
119             if (ovsdbBridgeOptional != null && ovsdbBridgeOptional.isPresent()) {
120                 OvsdbBridgeAugmentation operBridge = ovsdbBridgeOptional.get();
121                 if (operBridge != null) {
122                     Port port = transaction.getTypedRowWrapper(Port.class);
123                     updatePort(terminationPoint, port, operBridge, opendaylightIid);
124                     Port extraPort = transaction.getTypedRowWrapper(Port.class);
125                     extraPort.setName("");
126                     transaction.add(op.update(port)
127                         .where(extraPort.getNameColumn().getSchema().opEqual(terminationPoint.getName()))
128                         .build());
129                     LOG.info("Updated Termination Point : {}  with Uuid : {}",
130                         terminationPoint.getName(), terminationPoint.getPortUuid());
131                 }
132             } else {
133                 LOG.warn("OVSDB bridge node was not found: {}", iid);
134             }
135         }
136     }
137
138     private static void updateInterface(final OvsdbTerminationPointAugmentation terminationPoint,
139             final Interface ovsInterface) {
140         updateOfPort(terminationPoint, ovsInterface);
141         updateOfPortRequest(terminationPoint, ovsInterface);
142         updateInterfaceOptions(terminationPoint, ovsInterface);
143         updateInterfaceOtherConfig(terminationPoint, ovsInterface);
144         updateInterfaceExternalIds(terminationPoint, ovsInterface);
145         updateInterfaceLldp(terminationPoint, ovsInterface);
146         updateInterfaceBfd(terminationPoint, ovsInterface);
147         updateInterfacePolicing(terminationPoint, ovsInterface);
148     }
149
150     private static void updatePort(final OvsdbTerminationPointAugmentation terminationPoint,
151             final Port port, final OvsdbBridgeAugmentation operBridge, final String opendaylightIid) {
152         updatePortOtherConfig(terminationPoint, port);
153         updatePortVlanTag(terminationPoint, port);
154         updatePortVlanTrunk(terminationPoint, port);
155         updatePortVlanMode(terminationPoint, port);
156         updatePortExternalIds(terminationPoint, port, opendaylightIid);
157         updatePortQos(terminationPoint, port, operBridge);
158     }
159
160     private static void updatePortQos(final OvsdbTerminationPointAugmentation terminationPoint,
161             final Port port, final OvsdbBridgeAugmentation operBridge) {
162
163         Set<UUID> uuidSet = new HashSet<>();
164
165         // First check if QosEntry is present and use that
166         if (terminationPoint.getQosEntry() != null && !terminationPoint.getQosEntry().isEmpty()) {
167             OvsdbQosRef qosRef = terminationPoint.getQosEntry().iterator().next().getQosRef();
168             Uri qosId = qosRef.getValue().firstKeyOf(QosEntries.class).getQosId();
169             OvsdbNodeAugmentation operNode = getOperNode(operBridge);
170             if (operNode != null && operNode.getQosEntries() != null
171                     && !operNode.getQosEntries().isEmpty()) {
172                 for (QosEntries qosEntry : operNode.getQosEntries()) {
173                     if (qosEntry.getQosId().equals(qosId)) {
174                         uuidSet.add(new UUID(qosEntry.getQosUuid().getValue()));
175                     }
176                 }
177             }
178             if (uuidSet.size() == 0) {
179                 uuidSet.add(new UUID(SouthboundConstants.QOS_NAMED_UUID_PREFIX
180                         + TransactUtils.bytesToHexString(qosId.getValue().getBytes(UTF_8))));
181             }
182         }
183         port.setQos(uuidSet);
184     }
185
186     private static OvsdbNodeAugmentation getOperNode(final OvsdbBridgeAugmentation operBridge) {
187         @SuppressWarnings("unchecked")
188         InstanceIdentifier<Node> iidNode = (InstanceIdentifier<Node>)operBridge.getManagedBy().getValue();
189         OvsdbNodeAugmentation operNode = null;
190         ReadOnlyTransaction transaction = SouthboundProvider.getDb().newReadOnlyTransaction();
191         CheckedFuture<Optional<Node>, ReadFailedException> future =
192                 transaction.read(LogicalDatastoreType.OPERATIONAL, iidNode);
193         try {
194             Optional<Node> nodeOptional = future.get();
195             if (nodeOptional.isPresent()) {
196                 operNode = nodeOptional.get().augmentation(OvsdbNodeAugmentation.class);
197             }
198         } catch (InterruptedException | ExecutionException e) {
199             LOG.warn("Error reading from datastore", e);
200         }
201         return operNode;
202     }
203
204     private static void updateOfPort(final OvsdbTerminationPointAugmentation terminationPoint,
205             final Interface ovsInterface) {
206
207         Uint32 ofPort = terminationPoint.getOfport();
208         if (ofPort != null) {
209             ovsInterface.setOpenFlowPort(Collections.singleton(ofPort.toJava()));
210         }
211     }
212
213     private static void updateOfPortRequest(final OvsdbTerminationPointAugmentation terminationPoint,
214             final Interface ovsInterface) {
215
216         Uint16 ofPortRequest = terminationPoint.getOfportRequest();
217         if (ofPortRequest != null) {
218             ovsInterface.setOpenFlowPortRequest(Collections.singleton(ofPortRequest.longValue()));
219         }
220     }
221
222     private static void updateInterfaceOptions(final OvsdbTerminationPointAugmentation terminationPoint,
223             final Interface ovsInterface) {
224
225         //Configure optional input
226         if (terminationPoint.getOptions() != null) {
227             try {
228                 ovsInterface.setOptions(YangUtils.convertYangKeyValueListToMap(terminationPoint.getOptions(),
229                         Options::getOption, Options::getValue));
230             } catch (NullPointerException e) {
231                 LOG.warn("Incomplete OVSDB interface options", e);
232             }
233         }
234     }
235
236     private static void updateInterfaceExternalIds(final OvsdbTerminationPointAugmentation terminationPoint,
237             final Interface ovsInterface) {
238
239         List<InterfaceExternalIds> interfaceExternalIds =
240                 terminationPoint.getInterfaceExternalIds();
241         if (interfaceExternalIds != null && !interfaceExternalIds.isEmpty()) {
242             interfaceExternalIds.add(SouthboundUtil.createExternalIdsForInterface(
243                 SouthboundConstants.CREATED_BY, SouthboundConstants.ODL));
244         } else {
245             interfaceExternalIds = Arrays.asList(SouthboundUtil.createExternalIdsForInterface(
246                 SouthboundConstants.CREATED_BY, SouthboundConstants.ODL));
247         }
248         try {
249             ovsInterface.setExternalIds(YangUtils.convertYangKeyValueListToMap(interfaceExternalIds,
250                     InterfaceExternalIds::getExternalIdKey, InterfaceExternalIds::getExternalIdValue));
251         } catch (NullPointerException e) {
252             LOG.warn("Incomplete OVSDB interface external_ids", e);
253         }
254     }
255
256     private static void updateInterfaceLldp(final OvsdbTerminationPointAugmentation terminationPoint,
257             final Interface ovsInterface) {
258         try {
259             List<InterfaceLldp> interfaceLldpList =
260                     terminationPoint.getInterfaceLldp();
261             if (interfaceLldpList != null && !interfaceLldpList.isEmpty()) {
262                 try {
263                     ovsInterface.setLldp(YangUtils.convertYangKeyValueListToMap(interfaceLldpList,
264                             InterfaceLldp::getLldpKey, InterfaceLldp::getLldpValue));
265                 } catch (NullPointerException e) {
266                     LOG.warn("Incomplete OVSDB interface lldp", e);
267                 }
268             }
269         } catch (SchemaVersionMismatchException e) {
270             schemaMismatchLog("lldp", "Interface", e);
271         }
272     }
273
274     private static void updateInterfaceOtherConfig(final OvsdbTerminationPointAugmentation terminationPoint,
275             final Interface ovsInterface) {
276
277         List<InterfaceOtherConfigs> interfaceOtherConfigs =
278                 terminationPoint.getInterfaceOtherConfigs();
279         if (interfaceOtherConfigs != null && !interfaceOtherConfigs.isEmpty()) {
280             Map<String, String> otherConfigsMap = new HashMap<>();
281             for (InterfaceOtherConfigs interfaceOtherConfig : interfaceOtherConfigs) {
282                 otherConfigsMap.put(interfaceOtherConfig.getOtherConfigKey(),
283                         interfaceOtherConfig.getOtherConfigValue());
284             }
285             try {
286                 ovsInterface.setOtherConfig(otherConfigsMap);
287             } catch (NullPointerException e) {
288                 LOG.warn("Incomplete OVSDB interface other_config", e);
289             }
290         }
291     }
292
293     private static void updateInterfaceBfd(final OvsdbTerminationPointAugmentation terminationPoint,
294             final Interface ovsInterface) {
295
296         try {
297             List<InterfaceBfd> interfaceBfdList =
298                     terminationPoint.getInterfaceBfd();
299             if (interfaceBfdList != null && !interfaceBfdList.isEmpty()) {
300                 try {
301                     ovsInterface.setBfd(YangUtils.convertYangKeyValueListToMap(interfaceBfdList,
302                             InterfaceBfd::getBfdKey, InterfaceBfd::getBfdValue));
303                 } catch (NullPointerException e) {
304                     LOG.warn("Incomplete OVSDB interface bfd", e);
305                 }
306             }
307         } catch (SchemaVersionMismatchException e) {
308             schemaMismatchLog("bfd", "Interface", e);
309         }
310     }
311
312     private static void updateInterfacePolicing(final OvsdbTerminationPointAugmentation terminationPoint,
313             final Interface ovsInterface) {
314
315         Uint32 ingressPolicingRate = terminationPoint.getIngressPolicingRate();
316         if (ingressPolicingRate != null) {
317             ovsInterface.setIngressPolicingRate(ingressPolicingRate.toJava());
318         }
319         Uint32 ingressPolicingBurst = terminationPoint.getIngressPolicingBurst();
320         if (ingressPolicingBurst != null) {
321             ovsInterface.setIngressPolicingBurst(ingressPolicingBurst.toJava());
322         }
323     }
324
325     private static void updatePortExternalIds(final OvsdbTerminationPointAugmentation terminationPoint,
326             final Port port, final String opendaylightIid) {
327
328         Map<String, String> externalIdMap = new HashMap<>();
329         externalIdMap.put(SouthboundConstants.IID_EXTERNAL_ID_KEY, opendaylightIid);
330         externalIdMap.put(SouthboundConstants.CREATED_BY, SouthboundConstants.ODL);
331         try {
332             YangUtils.copyYangKeyValueListToMap(externalIdMap, terminationPoint.getPortExternalIds(),
333                     PortExternalIds::getExternalIdKey, PortExternalIds::getExternalIdValue);
334         } catch (NullPointerException e) {
335             LOG.warn("Incomplete OVSDB port external_ids", e);
336         }
337         port.setExternalIds(externalIdMap);
338     }
339
340     private static void updatePortVlanTag(final OvsdbTerminationPointAugmentation terminationPoint, final Port port) {
341         if (terminationPoint.getVlanTag() != null) {
342             Set<Long> vlanTag = new HashSet<>();
343             vlanTag.add(terminationPoint.getVlanTag().getValue().longValue());
344             port.setTag(vlanTag);
345         }
346     }
347
348     private static void updatePortVlanTrunk(final OvsdbTerminationPointAugmentation terminationPoint, final Port port) {
349         if (terminationPoint.getTrunks() != null && terminationPoint.getTrunks().size() > 0) {
350             Set<Long> portTrunks = new HashSet<>();
351             List<Trunks> modelTrunks = terminationPoint.getTrunks();
352             for (Trunks trunk : modelTrunks) {
353                 if (trunk.getTrunk() != null) {
354                     portTrunks.add(trunk.getTrunk().getValue().longValue());
355                 }
356             }
357             port.setTrunks(portTrunks);
358         }
359     }
360
361     private static void updatePortVlanMode(final OvsdbTerminationPointAugmentation terminationPoint, final Port port) {
362         if (terminationPoint.getVlanMode() != null) {
363             Set<String> portVlanMode = new HashSet<>();
364             VlanMode modelVlanMode = terminationPoint.getVlanMode();
365             portVlanMode.add(SouthboundConstants.VlanModes.values()[modelVlanMode.getIntValue() - 1].getMode());
366             port.setVlanMode(portVlanMode);
367         }
368     }
369
370     private static void updatePortOtherConfig(final OvsdbTerminationPointAugmentation terminationPoint,
371             final Port ovsPort) {
372         List<PortOtherConfigs> portOtherConfigs =
373                 terminationPoint.getPortOtherConfigs();
374         if (portOtherConfigs != null && !portOtherConfigs.isEmpty()) {
375             try {
376                 ovsPort.setOtherConfig(YangUtils.convertYangKeyValueListToMap(portOtherConfigs,
377                         PortOtherConfigs::getOtherConfigKey, PortOtherConfigs::getOtherConfigValue));
378             } catch (NullPointerException e) {
379                 LOG.warn("Incomplete OVSDB port other_config", e);
380             }
381         }
382     }
383 }