119596584e26ac50d3c85406a95c9ac788498f5b
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / transactions / md / HwvtepPhysicalPortUpdateCommand.java
1 /*
2  * Copyright (c) 2015, 2017 Ericsson India Global Services Pvt Ltd. 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.hwvtepsouthbound.transactions.md;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Lists;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepConnectionInstance;
23 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepDeviceInfo;
24 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundMapper;
25 import org.opendaylight.ovsdb.hwvtepsouthbound.HwvtepSouthboundUtil;
26 import org.opendaylight.ovsdb.hwvtepsouthbound.events.PortEvent;
27 import org.opendaylight.ovsdb.hwvtepsouthbound.events.ReconcilePortEvent;
28 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.HwvtepOperationalState;
29 import org.opendaylight.ovsdb.hwvtepsouthbound.transact.PhysicalPortUpdateCommand;
30 import org.opendaylight.ovsdb.lib.message.TableUpdates;
31 import org.opendaylight.ovsdb.lib.notation.UUID;
32 import org.opendaylight.ovsdb.lib.schema.DatabaseSchema;
33 import org.opendaylight.ovsdb.lib.schema.typed.TyperUtils;
34 import org.opendaylight.ovsdb.schema.hardwarevtep.LogicalSwitch;
35 import org.opendaylight.ovsdb.schema.hardwarevtep.PhysicalPort;
36 import org.opendaylight.ovsdb.schema.hardwarevtep.PhysicalSwitch;
37 import org.opendaylight.ovsdb.utils.mdsal.utils.ControllerMdsalUtils;
38 import org.opendaylight.ovsdb.utils.mdsal.utils.TransactionType;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepGlobalAugmentation;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepLogicalSwitchRef;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepNodeName;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalPortAugmentation;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.HwvtepPhysicalPortAugmentationBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.LogicalSwitches;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.global.attributes.Switches;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.PortFaultStatus;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.PortFaultStatusBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.PortFaultStatusKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.VlanBindings;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.VlanBindingsBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.hwvtep.rev150901.hwvtep.physical.port.attributes.VlanBindingsKey;
54 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
55 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
56 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
60 import org.opendaylight.yangtools.yang.binding.DataObject;
61 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 public class HwvtepPhysicalPortUpdateCommand extends AbstractTransactionCommand {
66
67     private static final Logger LOG = LoggerFactory.getLogger(HwvtepPhysicalPortUpdateCommand.class);
68     private final Map<UUID, PhysicalPort> updatedPPRows;
69     private final Map<UUID, PhysicalPort> oldPPRows;
70     private final Map<UUID, PhysicalSwitch> switchUpdatedRows;
71     private final Set<UUID> skipReconciliationPorts;
72     private final ControllerMdsalUtils mdsalUtils;
73
74     public HwvtepPhysicalPortUpdateCommand(final HwvtepConnectionInstance key, final TableUpdates updates,
75             final DatabaseSchema dbSchema) {
76         super(key, updates, dbSchema);
77         updatedPPRows = TyperUtils.extractRowsUpdated(PhysicalPort.class, getUpdates(), getDbSchema());
78         oldPPRows = TyperUtils.extractRowsOld(PhysicalPort.class, getUpdates(), getDbSchema());
79         switchUpdatedRows = TyperUtils.extractRowsUpdated(PhysicalSwitch.class, getUpdates(), getDbSchema());
80         skipReconciliationPorts = new HashSet<>();
81         mdsalUtils = new ControllerMdsalUtils(key.getDataBroker());
82         for (Entry<UUID, PhysicalPort> portUpdateEntry : updatedPPRows.entrySet()) {
83             Optional<InstanceIdentifier<Node>> switchIid = getTerminationPointSwitch(portUpdateEntry.getKey());
84             if (switchIid.isPresent()) {
85                 if (getDeviceInfo().getDeviceOperData(Node.class, switchIid.get()) == null) {
86                     //This is the first update from switch do not have to do reconciliation of this port
87                     //it is taken care by switch reconciliation
88                     skipReconciliationPorts.add(portUpdateEntry.getKey());
89                 }
90             }
91         }
92
93     }
94
95     @Override
96     public void execute(final ReadWriteTransaction transaction) {
97         final InstanceIdentifier<Node> connectionIId = getOvsdbConnectionInstance().getInstanceIdentifier();
98         if (updatedPPRows.isEmpty()) {
99             return;
100         }
101         LOG.trace("PhysicalPortTable updated: {}", updatedPPRows);
102         Optional<Node> node = HwvtepSouthboundUtil.readNode(transaction, connectionIId);
103         if (node.isPresent()) {
104             updateTerminationPoints(transaction, node.get());
105             // TODO: Handle Deletion of VLAN Bindings
106         }
107     }
108
109     private void updateTerminationPoints(final ReadWriteTransaction transaction, final Node node) {
110         for (Entry<UUID, PhysicalPort> portUpdateEntry : updatedPPRows.entrySet()) {
111             PhysicalPort portUpdate = portUpdateEntry.getValue();
112             String portName = portUpdate.getNameColumn().getData();
113             Optional<InstanceIdentifier<Node>> switchIid = getTerminationPointSwitch(portUpdateEntry.getKey());
114             if (!switchIid.isPresent()) {
115                 switchIid = getFromDeviceOperCache(portUpdate.getUuid());
116                 if (!switchIid.isPresent()) {
117                     LOG.debug("Failed to find node from the DeviceOperCache for port {}. Get it from the DS.",
118                             portUpdate);
119                     switchIid = getTerminationPointSwitch(transaction, node, portName);
120                 }
121             }
122             if (switchIid.isPresent()) {
123                 TerminationPointKey tpKey = new TerminationPointKey(new TpId(portName));
124                 TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
125                 tpBuilder.withKey(tpKey);
126                 tpBuilder.setTpId(tpKey.getTpId());
127                 InstanceIdentifier<TerminationPoint> tpPath = getInstanceIdentifier(switchIid.get(), portUpdate);
128                 HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder =
129                         new HwvtepPhysicalPortAugmentationBuilder();
130                 buildTerminationPoint(tpAugmentationBuilder, portUpdate);
131                 setPortFaultStatus(tpAugmentationBuilder, portUpdate);
132                 tpBuilder.addAugmentation(HwvtepPhysicalPortAugmentation.class, tpAugmentationBuilder.build());
133                 if (oldPPRows.containsKey(portUpdateEntry.getKey())) {
134                     transaction.merge(LogicalDatastoreType.OPERATIONAL, tpPath, tpBuilder.build());
135                 } else {
136                     transaction.put(LogicalDatastoreType.OPERATIONAL, tpPath, tpBuilder.build());
137                 }
138                 NodeId psNodeId = tpPath.firstKeyOf(Node.class).getNodeId();
139                 if (getDeviceInfo().getDeviceOperData(TerminationPoint.class, tpPath) == null) {
140                     addToDeviceUpdate(TransactionType.ADD, new PortEvent(portUpdate, psNodeId));
141                 } else {
142                     addToDeviceUpdate(TransactionType.UPDATE, new PortEvent(portUpdate, psNodeId));
143                 }
144                 reconcileToPort(portUpdate, tpPath);
145                 getDeviceInfo().updateDeviceOperData(TerminationPoint.class, tpPath,
146                         portUpdate.getUuid(), portUpdate);
147                 // Update with Deleted VlanBindings
148                 if (oldPPRows.get(portUpdateEntry.getKey()) != null
149                         && oldPPRows.get(portUpdateEntry.getKey()).getVlanBindingsColumn() != null) {
150                     List<InstanceIdentifier<VlanBindings>> vlanBindingsList = new ArrayList<>();
151                     Map<Long, UUID> oldVb = oldPPRows.get(portUpdateEntry.getKey()).getVlanBindingsColumn().getData();
152                     Map<Long, UUID> updatedVb = portUpdateEntry.getValue().getVlanBindingsColumn().getData();
153                     for (Map.Entry<Long, UUID> oldVbEntry : oldVb.entrySet()) {
154                         Long key = oldVbEntry.getKey();
155                         if (!updatedVb.containsKey(key)) {
156                             VlanBindings vlanBindings = createVlanBinding(key, oldVbEntry.getValue());
157                             InstanceIdentifier<VlanBindings> vbIid = getInstanceIdentifier(tpPath, vlanBindings);
158                             vlanBindingsList.add(vbIid);
159                         }
160                         deleteEntries(transaction, vlanBindingsList);
161                     }
162                 }
163                 // Update with Deleted portfaultstatus
164                 deleteEntries(transaction,getPortFaultStatusToRemove(tpPath, portUpdate));
165             } else {
166                 LOG.warn("switchIid was not found for port {}", portUpdate);
167             }
168         }
169     }
170
171     private void reconcileToPort(final PhysicalPort portUpdate,
172                                  final InstanceIdentifier<TerminationPoint> tpPath) {
173         if (skipReconciliationPorts.contains(portUpdate.getUuid())) {
174             //case of port added along with switch add
175             //switch reconciliation will take care of this port along with other ports
176             return;
177         }
178         if (getDeviceInfo().getDeviceOperData(TerminationPoint.class, tpPath) != null) {
179             //case of port update not new port add
180             return;
181
182         }
183         //case of individual port add , reconcile to this port
184         getDeviceInfo().updateDeviceOperData(TerminationPoint.class, tpPath, portUpdate.getUuid(), portUpdate);
185         HwvtepDeviceInfo.DeviceData data = getDeviceInfo().getConfigData(TerminationPoint.class, tpPath);
186         if (data == null || data.getData() == null) {
187             LOG.error("No config data present ");
188         } else {
189             addToDeviceUpdate(TransactionType.ADD,
190                     new ReconcilePortEvent(portUpdate, tpPath.firstKeyOf(Node.class).getNodeId()));
191             LOG.info("addToDeviceUpdate {}", portUpdate);
192             getDeviceInfo().updateDeviceOperData(TerminationPoint.class, tpPath,
193                     portUpdate.getUuid(), portUpdate);
194             getDeviceInfo().scheduleTransaction((transactionBuilder) -> {
195                 InstanceIdentifier psIid = tpPath.firstIdentifierOf(Node.class);
196                 HwvtepOperationalState operState = new HwvtepOperationalState(getOvsdbConnectionInstance());
197                 PhysicalPortUpdateCommand portUpdateCommand = new PhysicalPortUpdateCommand(
198                         operState, Collections.EMPTY_LIST);
199                 TerminationPoint cfgPoint = (TerminationPoint) data.getData();
200                 portUpdateCommand.updatePhysicalPort(transactionBuilder, psIid,
201                             Lists.newArrayList(cfgPoint));
202
203             });
204         }
205     }
206
207     private static <T extends DataObject> void deleteEntries(final ReadWriteTransaction transaction,
208             final List<InstanceIdentifier<T>> entryIids) {
209         for (InstanceIdentifier<T> entryIid : entryIids) {
210             transaction.delete(LogicalDatastoreType.OPERATIONAL, entryIid);
211         }
212     }
213
214     private InstanceIdentifier<VlanBindings> getInstanceIdentifier(final InstanceIdentifier<TerminationPoint> tpPath,
215             final VlanBindings vlanBindings) {
216         return HwvtepSouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(), tpPath, vlanBindings);
217     }
218
219     private static InstanceIdentifier<TerminationPoint> getInstanceIdentifier(final InstanceIdentifier<Node> switchIid,
220             final PhysicalPort port) {
221         return switchIid.child(TerminationPoint.class, new TerminationPointKey(new TpId(port.getName())));
222     }
223
224     private void buildTerminationPoint(final HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder,
225             final PhysicalPort portUpdate) {
226         updatePhysicalPortId(portUpdate, tpAugmentationBuilder);
227         updatePort(portUpdate, tpAugmentationBuilder);
228     }
229
230     private void updatePort(final PhysicalPort portUpdate,
231             final HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder) {
232         updateVlanBindings(portUpdate, tpAugmentationBuilder);
233         tpAugmentationBuilder.setPhysicalPortUuid(new Uuid(portUpdate.getUuid().toString()));
234     }
235
236     private static void updatePhysicalPortId(final PhysicalPort portUpdate,
237             final HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder) {
238         tpAugmentationBuilder.setHwvtepNodeName(new HwvtepNodeName(portUpdate.getName()));
239         if (portUpdate.getDescription() != null) {
240             tpAugmentationBuilder.setHwvtepNodeDescription(portUpdate.getDescription());
241         }
242     }
243
244     private void updateVlanBindings(final PhysicalPort portUpdate,
245             final HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder) {
246         Map<Long, UUID> vlanBindings = portUpdate.getVlanBindingsColumn().getData();
247         if (vlanBindings != null && !vlanBindings.isEmpty()) {
248             List<VlanBindings> vlanBindingsList = new ArrayList<>();
249             for (Map.Entry<Long, UUID> vlanBindingEntry : vlanBindings.entrySet()) {
250                 Long vlanBindingKey = vlanBindingEntry.getKey();
251                 UUID vlanBindingValue = vlanBindingEntry.getValue();
252                 if (vlanBindingValue != null && vlanBindingKey != null) {
253                     vlanBindingsList.add(createVlanBinding(vlanBindingKey, vlanBindingValue));
254                 }
255             }
256             tpAugmentationBuilder.setVlanBindings(vlanBindingsList);
257         }
258     }
259
260     private VlanBindings createVlanBinding(final Long key, final UUID value) {
261         VlanBindingsBuilder vbBuilder = new VlanBindingsBuilder();
262         VlanBindingsKey vbKey = new VlanBindingsKey(new VlanId(key.intValue()));
263         vbBuilder.withKey(vbKey);
264         vbBuilder.setVlanIdKey(vbKey.getVlanIdKey());
265         HwvtepLogicalSwitchRef switchRef = this.getLogicalSwitchRef(value);
266         vbBuilder.setLogicalSwitchRef(switchRef);
267         return vbBuilder.build();
268     }
269
270     private HwvtepLogicalSwitchRef getLogicalSwitchRef(final UUID switchUUID) {
271         LogicalSwitch logicalSwitch = getOvsdbConnectionInstance().getDeviceInfo().getLogicalSwitch(switchUUID);
272         if (logicalSwitch != null) {
273             InstanceIdentifier<LogicalSwitches> switchIid =
274                     HwvtepSouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(), logicalSwitch);
275             return new HwvtepLogicalSwitchRef(switchIid);
276         }
277         LOG.debug("Failed to get LogicalSwitch {}", switchUUID);
278         LOG.trace("Available LogicalSwitches: {}",
279                         getOvsdbConnectionInstance().getDeviceInfo().getLogicalSwitches().values());
280         return null;
281     }
282
283     private Optional<InstanceIdentifier<Node>> getTerminationPointSwitch(final UUID portUUID) {
284         for (PhysicalSwitch updatedPhysicalSwitch : switchUpdatedRows.values()) {
285             if (updatedPhysicalSwitch.getPortsColumn().getData().contains(portUUID)) {
286                 return Optional.of(HwvtepSouthboundMapper.createInstanceIdentifier(getOvsdbConnectionInstance(),
287                         updatedPhysicalSwitch));
288             }
289         }
290         return Optional.absent();
291     }
292
293     private static Optional<InstanceIdentifier<Node>> getTerminationPointSwitch(final ReadWriteTransaction transaction,
294             final Node node, final String tpName) {
295         HwvtepGlobalAugmentation hwvtepNode = node.augmentation(HwvtepGlobalAugmentation.class);
296         List<Switches> switchNodes = hwvtepNode.getSwitches();
297         if (switchNodes != null && !switchNodes.isEmpty()) {
298             for (Switches managedNodeEntry : switchNodes) {
299                 @SuppressWarnings("unchecked")
300                 Node switchNode = HwvtepSouthboundUtil
301                         .readNode(transaction,
302                                 (InstanceIdentifier<Node>) managedNodeEntry.getSwitchRef().getValue()).get();
303                 TerminationPointKey tpKey = new TerminationPointKey(new TpId(tpName));
304                 if (switchNode.getTerminationPoint() != null) {
305                     for (TerminationPoint terminationPoint : switchNode.getTerminationPoint()) {
306                         if (terminationPoint.key().equals(tpKey)) {
307                             return Optional.of((InstanceIdentifier<Node>) managedNodeEntry.getSwitchRef().getValue());
308                         }
309                     }
310                 }
311             }
312         } else {
313             LOG.trace("PhyscialSwitch not present for the Port {}", tpName);
314         }
315         return Optional.absent();
316     }
317
318     private static void setPortFaultStatus(final HwvtepPhysicalPortAugmentationBuilder tpAugmentationBuilder,
319             final PhysicalPort portUpdate) {
320         if (portUpdate.getPortFaultStatusColumn() != null && portUpdate.getPortFaultStatusColumn().getData() != null
321                 && !portUpdate.getPortFaultStatusColumn().getData().isEmpty()) {
322             List<PortFaultStatus> portFaultStatusLst = new ArrayList<>();
323             for (String portFaultStatus : portUpdate.getPortFaultStatusColumn().getData()) {
324                 portFaultStatusLst.add(new PortFaultStatusBuilder().withKey(new PortFaultStatusKey(portFaultStatus))
325                         .setPortFaultStatusKey(portFaultStatus).build());
326             }
327             tpAugmentationBuilder.setPortFaultStatus(portFaultStatusLst);
328         }
329     }
330
331     private List<InstanceIdentifier<PortFaultStatus>> getPortFaultStatusToRemove(
332             final InstanceIdentifier<TerminationPoint> tpPath, final PhysicalPort port) {
333         Preconditions.checkNotNull(tpPath);
334         Preconditions.checkNotNull(port);
335         List<InstanceIdentifier<PortFaultStatus>> result = new ArrayList<>();
336         PhysicalPort oldPort = oldPPRows.get(port.getUuid());
337         if (oldPort != null && oldPort.getPortFaultStatusColumn() != null) {
338             for (String portFltStat : oldPort.getPortFaultStatusColumn().getData()) {
339                 if (port.getPortFaultStatusColumn() == null
340                         || !port.getPortFaultStatusColumn().getData().contains(portFltStat)) {
341                     InstanceIdentifier<PortFaultStatus> iid = tpPath.augmentation(HwvtepPhysicalPortAugmentation.class)
342                             .child(PortFaultStatus.class, new PortFaultStatusKey(portFltStat));
343                     result.add(iid);
344                 }
345             }
346         }
347         return result;
348     }
349
350     private  Optional<InstanceIdentifier<Node>> getFromDeviceOperCache(final UUID uuid) {
351
352         InstanceIdentifier<TerminationPoint> terminationPointIid =
353                 getOvsdbConnectionInstance()
354                 .getDeviceInfo().getDeviceOperKey(TerminationPoint.class, uuid);
355         if (terminationPointIid != null) {
356             return Optional.of(terminationPointIid.firstIdentifierOf(Node.class));
357         }
358         return Optional.absent();
359     }
360 }