QoS Log clean-up
[netvirt.git] / qosservice / impl / src / main / java / org / opendaylight / netvirt / qosservice / QosNeutronUtils.java
1 /*
2  * Copyright (c) 2017 Intel Corporation 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.netvirt.qosservice;
9
10 import com.google.common.base.Optional;
11 import java.math.BigInteger;
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import java.util.concurrent.CopyOnWriteArraySet;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Future;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import javax.inject.Singleton;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
30 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
31 import org.opendaylight.genius.mdsalutil.ActionInfo;
32 import org.opendaylight.genius.mdsalutil.FlowEntity;
33 import org.opendaylight.genius.mdsalutil.InstructionInfo;
34 import org.opendaylight.genius.mdsalutil.MDSALUtil;
35 import org.opendaylight.genius.mdsalutil.MatchInfo;
36 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
37 import org.opendaylight.genius.mdsalutil.NwConstants;
38 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
39 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldDscp;
40 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
41 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
42 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
43 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
44 import org.opendaylight.genius.utils.ServiceIndex;
45 import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
46 import org.opendaylight.netvirt.neutronvpn.interfaces.INeutronVpnManager;
47 import org.opendaylight.ovsdb.utils.southbound.utils.SouthboundUtils;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.BridgeInterfaceInfo;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.BridgeRefInfo;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge._interface.info.BridgeEntry;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge._interface.info.BridgeEntryKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge.ref.info.BridgeRefEntry;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge.ref.info.BridgeRefEntryKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInput;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceInputBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.GetDpidFromInterfaceOutput;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceBindings;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeIngress;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceTypeFlowBased;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflow;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.StypeOpenflowBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfo;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.ServicesInfoKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServices;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesBuilder;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.service.bindings.services.info.BoundServicesKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.NetworkMaps;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.networkmaps.NetworkMap;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.networkmaps.NetworkMapKey;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.ext.rev160613.QosNetworkExtension;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.ext.rev160613.QosPortExtension;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.rev160613.qos.attributes.qos.policies.QosPolicy;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.rev160613.qos.attributes.qos.policies.qos.policy.BandwidthLimitRules;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.rev160613.qos.attributes.qos.policies.qos.policy.BandwidthLimitRulesBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.qos.rev160613.qos.attributes.qos.policies.qos.policy.DscpmarkingRules;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeRef;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentationBuilder;
92 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
93 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
94 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
95 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
96 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPoint;
97 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointBuilder;
98 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.node.TerminationPointKey;
99 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
100 import org.opendaylight.yangtools.yang.common.RpcResult;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103
104 @Singleton
105 public class QosNeutronUtils {
106     private static final Logger LOG = LoggerFactory.getLogger(QosNeutronUtils.class);
107
108     private final ConcurrentMap<Uuid, QosPolicy> qosPolicyMap = new ConcurrentHashMap<>();
109     private final ConcurrentMap<Uuid, ConcurrentMap<Uuid, Port>> qosPortsMap = new ConcurrentHashMap<>();
110     private final ConcurrentMap<Uuid, ConcurrentMap<Uuid, Network>> qosNetworksMap = new ConcurrentHashMap<>();
111     private final CopyOnWriteArraySet<Uuid> qosServiceConfiguredPorts = new CopyOnWriteArraySet<>();
112     private final ConcurrentHashMap<Uuid, Port> neutronPortMap = new ConcurrentHashMap<>();
113     private final ConcurrentHashMap<Uuid, Network> neutronNetworkMap = new ConcurrentHashMap<>();
114
115     private final QosEosHandler qosEosHandler;
116     private final INeutronVpnManager neutronVpnManager;
117     private final OdlInterfaceRpcService odlInterfaceRpcService;
118     private final DataBroker dataBroker;
119     private final ManagedNewTransactionRunner txRunner;
120     private final IMdsalApiManager mdsalUtils;
121     private final JobCoordinator jobCoordinator;
122
123     @Inject
124     public QosNeutronUtils(final QosEosHandler qosEosHandler, final INeutronVpnManager neutronVpnManager,
125             final OdlInterfaceRpcService odlInterfaceRpcService, final DataBroker dataBroker,
126             final IMdsalApiManager mdsalUtils, final JobCoordinator jobCoordinator) {
127         this.qosEosHandler = qosEosHandler;
128         this.neutronVpnManager = neutronVpnManager;
129         this.odlInterfaceRpcService = odlInterfaceRpcService;
130         this.dataBroker = dataBroker;
131         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
132         this.mdsalUtils = mdsalUtils;
133         this.jobCoordinator = jobCoordinator;
134     }
135
136     public void addToQosPolicyCache(QosPolicy qosPolicy) {
137         qosPolicyMap.put(qosPolicy.getUuid(),qosPolicy);
138     }
139
140     public void removeFromQosPolicyCache(QosPolicy qosPolicy) {
141         qosPolicyMap.remove(qosPolicy.getUuid());
142     }
143
144     public Map<Uuid, QosPolicy> getQosPolicyMap() {
145         return qosPolicyMap;
146     }
147
148     public Collection<Port> getQosPorts(Uuid qosUuid) {
149         final ConcurrentMap<Uuid, Port> portMap = qosPortsMap.get(qosUuid);
150         return portMap != null ? portMap.values() : Collections.emptyList();
151     }
152
153     public void addToQosPortsCache(Uuid qosUuid, Port port) {
154         qosPortsMap.computeIfAbsent(qosUuid, key -> new ConcurrentHashMap<>()).putIfAbsent(port.getUuid(), port);
155     }
156
157     public void removeFromQosPortsCache(Uuid qosUuid, Port port) {
158         if (qosPortsMap.containsKey(qosUuid) && qosPortsMap.get(qosUuid).containsKey(port.getUuid())) {
159             qosPortsMap.get(qosUuid).remove(port.getUuid(), port);
160         }
161     }
162
163     public void addToQosNetworksCache(Uuid qosUuid, Network network) {
164         qosNetworksMap.computeIfAbsent(qosUuid, key -> new ConcurrentHashMap<>()).putIfAbsent(network.getUuid(),
165                 network);
166     }
167
168     public void removeFromQosNetworksCache(Uuid qosUuid, Network network) {
169         if (qosNetworksMap.containsKey(qosUuid) && qosNetworksMap.get(qosUuid).containsKey(network.getUuid())) {
170             qosNetworksMap.get(qosUuid).remove(network.getUuid(), network);
171         }
172     }
173
174     @Nonnull
175     public Collection<Network> getQosNetworks(Uuid qosUuid) {
176         final ConcurrentMap<Uuid, Network> networkMap = qosNetworksMap.get(qosUuid);
177         return networkMap != null ? networkMap.values() : Collections.emptyList();
178     }
179
180     @Nonnull
181     public List<Uuid> getSubnetIdsFromNetworkId(Uuid networkId) {
182         InstanceIdentifier<NetworkMap> networkMapId = InstanceIdentifier.builder(NetworkMaps.class)
183                 .child(NetworkMap.class, new NetworkMapKey(networkId)).build();
184         Optional<NetworkMap> optionalNetworkMap = MDSALUtil.read(LogicalDatastoreType.CONFIGURATION,
185                 networkMapId, dataBroker);
186         return optionalNetworkMap.isPresent() ? optionalNetworkMap.get().getSubnetIdList() : Collections.emptyList();
187     }
188
189     @Nonnull
190     protected List<Uuid> getPortIdsFromSubnetId(Uuid subnetId) {
191         InstanceIdentifier<Subnetmap> subnetMapId = InstanceIdentifier
192                 .builder(Subnetmaps.class)
193                 .child(Subnetmap.class, new SubnetmapKey(subnetId)).build();
194         Optional<Subnetmap> optionalSubnetmap = MDSALUtil.read(LogicalDatastoreType.CONFIGURATION,
195                 subnetMapId,dataBroker);
196         return optionalSubnetmap.isPresent() ? optionalSubnetmap.get().getPortList() : Collections.emptyList();
197     }
198
199     public void handleNeutronPortQosAdd(Port port, Uuid qosUuid) {
200         LOG.debug("Handling Port add and QoS associated: port: {} qos: {}", port.getUuid().getValue(),
201                 qosUuid.getValue());
202
203         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
204
205         jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(),
206             () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
207                 // handle Bandwidth Limit Rules update
208                 if (qosPolicy != null && qosPolicy.getBandwidthLimitRules() != null
209                         && !qosPolicy.getBandwidthLimitRules().isEmpty()) {
210                     setPortBandwidthLimits(port, qosPolicy.getBandwidthLimitRules().get(0), tx);
211                 }
212                 // handle DSCP Mark Rules update
213                 if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
214                         && !qosPolicy.getDscpmarkingRules().isEmpty()) {
215                     setPortDscpMarking(port, qosPolicy.getDscpmarkingRules().get(0));
216                 }
217             })));
218     }
219
220     public void handleQosInterfaceAdd(Port port, Uuid qosUuid) {
221         LOG.debug("Handling Port add and QoS associated: port: {} qos: {}", port.getUuid().getValue(),
222                 qosUuid.getValue());
223
224         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
225
226         jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(), () -> {
227             // handle DSCP Mark Rules update
228             if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
229                     && !qosPolicy.getDscpmarkingRules().isEmpty()) {
230                 setPortDscpMarking(port, qosPolicy.getDscpmarkingRules().get(0));
231             }
232             return Collections.emptyList();
233         });
234     }
235
236     public void handleNeutronPortQosUpdate(Port port, Uuid qosUuidNew, Uuid qosUuidOld) {
237         LOG.debug("Handling Port QoS update: port: {} qosservice: {}", port.getUuid().getValue(),
238                 qosUuidNew.getValue());
239
240         QosPolicy qosPolicyNew = qosPolicyMap.get(qosUuidNew);
241         QosPolicy qosPolicyOld = qosPolicyMap.get(qosUuidOld);
242
243         jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(),
244             () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
245                 // handle Bandwidth Limit Rules update
246                 if (qosPolicyNew != null && qosPolicyNew.getBandwidthLimitRules() != null
247                         && !qosPolicyNew.getBandwidthLimitRules().isEmpty()) {
248                     setPortBandwidthLimits(port, qosPolicyNew.getBandwidthLimitRules().get(0), tx);
249                 } else {
250                     if (qosPolicyOld != null && qosPolicyOld.getBandwidthLimitRules() != null
251                             && !qosPolicyOld.getBandwidthLimitRules().isEmpty()) {
252                         BandwidthLimitRulesBuilder bwLimitBuilder = new BandwidthLimitRulesBuilder();
253                         setPortBandwidthLimits(port, bwLimitBuilder
254                                 .setMaxBurstKbps(BigInteger.ZERO)
255                                 .setMaxKbps(BigInteger.ZERO).build(), tx);
256                     }
257                 }
258                 //handle DSCP Mark Rules update
259                 if (qosPolicyNew != null && qosPolicyNew.getDscpmarkingRules() != null
260                         && !qosPolicyNew.getDscpmarkingRules().isEmpty()) {
261                     setPortDscpMarking(port, qosPolicyNew.getDscpmarkingRules().get(0));
262                 } else {
263                     if (qosPolicyOld != null && qosPolicyOld.getDscpmarkingRules() != null
264                             && !qosPolicyOld.getDscpmarkingRules().isEmpty()) {
265                         unsetPortDscpMark(port);
266                     }
267                 }
268             })));
269     }
270
271     public void handleNeutronPortQosRemove(Port port, Uuid qosUuid) {
272         LOG.debug("Handling Port QoS removal: port: {} qosservice: {}", port.getUuid().getValue(), qosUuid.getValue());
273
274         // check for network qosservice to apply
275         Network network =  neutronVpnManager.getNeutronNetwork(port.getNetworkId());
276         if (network != null && network.augmentation(QosNetworkExtension.class) != null) {
277             Uuid networkQosUuid = network.augmentation(QosNetworkExtension.class).getQosPolicyId();
278             if (networkQosUuid != null) {
279                 handleNeutronPortQosUpdate(port, networkQosUuid, qosUuid);
280             }
281         } else {
282             QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
283
284             jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(),
285                 () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
286                     // handle Bandwidth Limit Rules removal
287                     if (qosPolicy != null && qosPolicy.getBandwidthLimitRules() != null
288                             && !qosPolicy.getBandwidthLimitRules().isEmpty()) {
289                         BandwidthLimitRulesBuilder bwLimitBuilder = new BandwidthLimitRulesBuilder();
290                         setPortBandwidthLimits(port, bwLimitBuilder
291                                 .setMaxBurstKbps(BigInteger.ZERO)
292                                 .setMaxKbps(BigInteger.ZERO).build(), tx);
293                     }
294                     // handle DSCP MArk Rules removal
295                     if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
296                             && !qosPolicy.getDscpmarkingRules().isEmpty()) {
297                         unsetPortDscpMark(port);
298                     }
299                 })));
300         }
301     }
302
303     public void handleNeutronPortRemove(Port port, Uuid qosUuid) {
304         LOG.debug("Handling Port removal and Qos associated: port: {} qos: {}", port.getUuid().getValue(),
305                 qosUuid.getValue());
306         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
307
308         jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(), () -> {
309             //check if any DSCP rule in the policy
310             if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
311                     && !qosPolicy.getDscpmarkingRules().isEmpty()) {
312                 unsetPortDscpMark(port);
313             }
314             return Collections.emptyList();
315         });
316     }
317
318     public void handleNeutronPortRemove(Port port, Uuid qosUuid, Interface intrf) {
319         LOG.debug("Handling Port removal and Qos associated: port: {} qos: {}", port.getUuid().getValue(),
320                 qosUuid.getValue());
321         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
322
323         jobCoordinator.enqueueJob("QosPort-" + port.getUuid().getValue(), () -> {
324             if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
325                     && !qosPolicy.getDscpmarkingRules().isEmpty()) {
326                 unsetPortDscpMark(port, intrf);
327             }
328             return Collections.emptyList();
329         });
330     }
331
332
333     public void handleNeutronNetworkQosUpdate(Network network, Uuid qosUuid) {
334         LOG.debug("Handling Network QoS update: net: {} qosservice: {}", network.getUuid().getValue(), qosUuid);
335         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
336         if (qosPolicy == null || (qosPolicy.getBandwidthLimitRules() == null
337                 || qosPolicy.getBandwidthLimitRules().isEmpty())
338                 && (qosPolicy.getDscpmarkingRules() == null
339                 || qosPolicy.getDscpmarkingRules().isEmpty())) {
340             return;
341         }
342         List<Uuid> subnetIds = getSubnetIdsFromNetworkId(network.getUuid());
343         for (Uuid subnetId : subnetIds) {
344             List<Uuid> portIds = getPortIdsFromSubnetId(subnetId);
345             for (Uuid portId : portIds) {
346                 Port port = getNeutronPort(portId);
347                 if (port != null && (port.augmentation(QosPortExtension.class) == null
348                         || port.augmentation(QosPortExtension.class).getQosPolicyId() == null)) {
349                     jobCoordinator.enqueueJob("QosPort-" + portId.getValue(),
350                         () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
351                             if (qosPolicy.getBandwidthLimitRules() != null
352                                     && !qosPolicy.getBandwidthLimitRules().isEmpty()) {
353                                 setPortBandwidthLimits(port, qosPolicy.getBandwidthLimitRules().get(0), tx);
354                             }
355                             if (qosPolicy.getDscpmarkingRules() != null
356                                     && !qosPolicy.getDscpmarkingRules().isEmpty()) {
357                                 setPortDscpMarking(port, qosPolicy.getDscpmarkingRules().get(0));
358                             }
359                         })));
360                 }
361             }
362         }
363     }
364
365     public void handleNeutronNetworkQosRemove(Network network, Uuid qosUuid) {
366         LOG.debug("Handling Network QoS removal: net: {} qosservice: {}", network.getUuid().getValue(),
367                 qosUuid.getValue());
368         QosPolicy qosPolicy = qosPolicyMap.get(qosUuid);
369
370         List<Uuid> subnetIds = getSubnetIdsFromNetworkId(network.getUuid());
371         for (Uuid subnetId : subnetIds) {
372             List<Uuid> portIds = getPortIdsFromSubnetId(subnetId);
373             for (Uuid portId : portIds) {
374                 Port port = getNeutronPort(portId);
375                 if (port != null && (port.augmentation(QosPortExtension.class) == null
376                         || port.augmentation(QosPortExtension.class).getQosPolicyId() == null)) {
377                     jobCoordinator.enqueueJob("QosPort-" + portId.getValue(),
378                         () -> Collections.singletonList(txRunner.callWithNewWriteOnlyTransactionAndSubmit(tx -> {
379                             if (qosPolicy != null && qosPolicy.getBandwidthLimitRules() != null
380                                     && !qosPolicy.getBandwidthLimitRules().isEmpty()) {
381                                 BandwidthLimitRulesBuilder bwLimitBuilder = new BandwidthLimitRulesBuilder();
382                                 setPortBandwidthLimits(port, bwLimitBuilder
383                                         .setMaxBurstKbps(BigInteger.ZERO)
384                                         .setMaxKbps(BigInteger.ZERO).build(), tx);
385                             }
386                             if (qosPolicy != null && qosPolicy.getDscpmarkingRules() != null
387                                     && !qosPolicy.getDscpmarkingRules().isEmpty()) {
388                                 unsetPortDscpMark(port);
389                             }
390                         })));
391                 }
392             }
393         }
394     }
395
396     public void handleNeutronNetworkQosBwRuleRemove(Network network, BandwidthLimitRules zeroBwLimitRule) {
397         LOG.debug("Handling Qos Bandwidth Rule Remove, net: {}", network.getUuid().getValue());
398
399         List<Uuid> subnetIds = getSubnetIdsFromNetworkId(network.getUuid());
400
401         for (Uuid subnetId: subnetIds) {
402             List<Uuid> portIds = getPortIdsFromSubnetId(subnetId);
403             for (Uuid portId : portIds) {
404                 Port port = getNeutronPort(portId);
405                 if (port != null && (port.augmentation(QosPortExtension.class) == null
406                         || port.augmentation(QosPortExtension.class).getQosPolicyId() == null)) {
407                     jobCoordinator.enqueueJob("QosPort-" + portId.getValue(), () -> Collections.singletonList(
408                             txRunner.callWithNewWriteOnlyTransactionAndSubmit(
409                                 tx -> setPortBandwidthLimits(port, zeroBwLimitRule, tx))));
410                 }
411             }
412         }
413     }
414
415     public void handleNeutronNetworkQosDscpRuleRemove(Network network) {
416         LOG.debug("Handling Qos Dscp Rule Remove, net: {}", network.getUuid().getValue());
417
418         List<Uuid> subnetIds = getSubnetIdsFromNetworkId(network.getUuid());
419
420         for (Uuid subnetId: subnetIds) {
421             List<Uuid> portIds = getPortIdsFromSubnetId(subnetId);
422             for (Uuid portId : portIds) {
423                 Port port = getNeutronPort(portId);
424                 if (port != null && (port.augmentation(QosPortExtension.class) == null
425                         || port.augmentation(QosPortExtension.class).getQosPolicyId() == null)) {
426                     jobCoordinator.enqueueJob("QosPort-" + portId.getValue(), () -> {
427                         unsetPortDscpMark(port);
428                         return Collections.emptyList();
429                     });
430                 }
431             }
432         }
433     }
434
435     // TODO Clean up the exception handling
436     @SuppressWarnings("checkstyle:IllegalCatch")
437     public void setPortBandwidthLimits(Port port, BandwidthLimitRules bwLimit, WriteTransaction writeConfigTxn) {
438         if (!qosEosHandler.isQosClusterOwner()) {
439             LOG.debug("Not Qos Cluster Owner. Ignoring setting bandwidth limits");
440             return;
441         }
442         BigInteger dpId = getDpnForInterface(port.getUuid().getValue());
443         if (dpId.equals(BigInteger.ZERO)) {
444             LOG.info("DPN ID for interface {} not found", port.getUuid().getValue());
445             return;
446         }
447
448         LOG.trace("Setting bandwidth limits {} on Port {}", port.getUuid().getValue(), bwLimit);
449         OvsdbBridgeRef bridgeRefEntry = getBridgeRefEntryFromOperDS(dpId);
450         Optional<Node> bridgeNode = MDSALUtil.read(LogicalDatastoreType.OPERATIONAL,
451                 bridgeRefEntry.getValue().firstIdentifierOf(Node.class), dataBroker);
452
453
454         TerminationPoint tp = SouthboundUtils.getTerminationPointByExternalId(bridgeNode.get(),
455                 port.getUuid().getValue());
456         OvsdbTerminationPointAugmentation ovsdbTp = tp.augmentation(OvsdbTerminationPointAugmentation.class);
457
458         OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = new OvsdbTerminationPointAugmentationBuilder();
459         tpAugmentationBuilder.setName(ovsdbTp.getName());
460         tpAugmentationBuilder.setIngressPolicingRate(bwLimit.getMaxKbps().longValue());
461         tpAugmentationBuilder.setIngressPolicingBurst(bwLimit.getMaxBurstKbps().longValue());
462
463         TerminationPointBuilder tpBuilder = new TerminationPointBuilder();
464         tpBuilder.withKey(tp.key());
465         tpBuilder.addAugmentation(OvsdbTerminationPointAugmentation.class, tpAugmentationBuilder.build());
466         try {
467             if (writeConfigTxn != null) {
468                 writeConfigTxn.merge(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier
469                         .create(NetworkTopology.class)
470                         .child(Topology.class, new TopologyKey(SouthboundUtils.OVSDB_TOPOLOGY_ID))
471                         .child(Node.class, bridgeNode.get().key())
472                         .child(TerminationPoint.class, new TerminationPointKey(tp.key())), tpBuilder.build(), true);
473             } else {
474                 MDSALUtil.syncUpdate(dataBroker, LogicalDatastoreType.CONFIGURATION, InstanceIdentifier
475                         .create(NetworkTopology.class)
476                         .child(Topology.class, new TopologyKey(SouthboundUtils.OVSDB_TOPOLOGY_ID))
477                         .child(Node.class, bridgeNode.get().key())
478                         .child(TerminationPoint.class, new TerminationPointKey(tp.key())), tpBuilder.build());
479             }
480         } catch (Exception e) {
481             if (LOG.isDebugEnabled()) {
482                 LOG.debug("Failure while setting BwLimitRule {} to port {} exception ", bwLimit,
483                         port.getUuid().getValue(), e);
484             } else {
485                 LOG.error("Failure while setting BwLimitRule {} to port {}", bwLimit, port.getUuid().getValue());
486             }
487         }
488
489     }
490
491     public void setPortDscpMarking(Port port, DscpmarkingRules dscpMark) {
492         if (!qosEosHandler.isQosClusterOwner()) {
493             LOG.trace("Not Qos Cluster Owner. Ignoring setting DSCP marking");
494             return;
495         }
496
497         BigInteger dpnId = getDpnForInterface(port.getUuid().getValue());
498         String ifName = port.getUuid().getValue();
499         Interface ifState = getInterfaceStateFromOperDS(ifName);
500         Short dscpValue = dscpMark.getDscpMark();
501
502         if (dpnId.equals(BigInteger.ZERO)) {
503             LOG.info("DPN ID for interface {} not found. Cannot set dscp value {} on port {}",
504                     port.getUuid().getValue(), dscpMark, port.getUuid().getValue());
505             return;
506         }
507         int ipVersions = getIpVersions(port);
508         //1. OF rules
509         if (hasIpv4Addr(ipVersions)) {
510             LOG.trace("setting ipv4 flow for port: {}, dscp: {}", ifName, dscpValue);
511             addFlow(dpnId, dscpValue, ifName, NwConstants.ETHTYPE_IPV4, ifState);
512         }
513         if (hasIpv6Addr(ipVersions)) {
514             LOG.trace("setting ipv6 flow for port: {}, dscp: {}", ifName, dscpValue);
515             addFlow(dpnId, dscpValue, ifName, NwConstants.ETHTYPE_IPV6, ifState);
516         }
517
518         if (qosServiceConfiguredPorts.add(port.getUuid())) {
519             // bind qos service to interface
520             bindservice(ifName);
521         }
522     }
523
524     public void unsetPortDscpMark(Port port) {
525         if (!qosEosHandler.isQosClusterOwner()) {
526             LOG.debug("Not Qos Cluster Owner. Ignoring unsetting DSCP marking");
527             return;
528         }
529
530         BigInteger dpnId = getDpnForInterface(port.getUuid().getValue());
531         String ifName = port.getUuid().getValue();
532
533         if (dpnId.equals(BigInteger.ZERO)) {
534             LOG.debug("DPN ID for port {} not found. Cannot unset dscp value", port.getUuid().getValue());
535             return;
536         }
537         LOG.trace("Removing dscp marking rule from Port {}", port.getUuid().getValue());
538         Interface intf = getInterfaceStateFromOperDS(ifName);
539         //unbind service from interface
540         unbindservice(ifName);
541         // 1. OF
542         int ipVersions = getIpVersions(port);
543         if (hasIpv4Addr(ipVersions)) {
544             removeFlow(dpnId, ifName, NwConstants.ETHTYPE_IPV4, intf);
545         }
546         if (hasIpv6Addr(ipVersions)) {
547             removeFlow(dpnId, ifName, NwConstants.ETHTYPE_IPV6, intf);
548         }
549         qosServiceConfiguredPorts.remove(port.getUuid());
550     }
551
552     public void unsetPortDscpMark(Port port, Interface intrf) {
553         if (!qosEosHandler.isQosClusterOwner()) {
554             return;
555         }
556         BigInteger dpnId = getDpIdFromInterface(intrf);
557         String ifName = port.getUuid().getValue();
558
559         if (dpnId.equals(BigInteger.ZERO)) {
560             LOG.error("Unable to retrieve DPN Id for interface {}. Cannot unset dscp value on port", ifName);
561             return;
562         }
563         LOG.trace("Removing dscp marking rule from Port {}", port.getUuid().getValue());
564         unbindservice(ifName);
565         int ipVersions = getIpVersions(port);
566         if (hasIpv4Addr(ipVersions)) {
567             removeFlow(dpnId, ifName, NwConstants.ETHTYPE_IPV4, intrf);
568         }
569         if (hasIpv6Addr(ipVersions)) {
570             removeFlow(dpnId, ifName, NwConstants.ETHTYPE_IPV6, intrf);
571         }
572         qosServiceConfiguredPorts.remove(port.getUuid());
573     }
574
575     private static BigInteger getDpIdFromInterface(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
576                                                            .interfaces.rev140508.interfaces.state.Interface ifState) {
577         String lowerLayerIf = ifState.getLowerLayerIf().get(0);
578         NodeConnectorId nodeConnectorId = new NodeConnectorId(lowerLayerIf);
579         return BigInteger.valueOf(MDSALUtil.getDpnIdFromPortName(nodeConnectorId));
580     }
581
582     public BigInteger getDpnForInterface(String ifName) {
583         BigInteger nodeId = BigInteger.ZERO;
584         try {
585             GetDpidFromInterfaceInput
586                     dpIdInput = new GetDpidFromInterfaceInputBuilder().setIntfName(ifName).build();
587             Future<RpcResult<GetDpidFromInterfaceOutput>>
588                     dpIdOutput = odlInterfaceRpcService.getDpidFromInterface(dpIdInput);
589             RpcResult<GetDpidFromInterfaceOutput> dpIdResult = dpIdOutput.get();
590             if (dpIdResult.isSuccessful()) {
591                 nodeId = dpIdResult.getResult().getDpid();
592             } else {
593                 LOG.error("Could not retrieve DPN Id for interface {}", ifName);
594             }
595         } catch (NullPointerException | InterruptedException | ExecutionException e) {
596             if (LOG.isDebugEnabled()) {
597                 LOG.debug("Exception when getting DPN for interface {} exception ", ifName, e);
598             } else {
599                 LOG.error("Could not retrieve DPN for interface {}", ifName);
600             }
601         }
602         return nodeId;
603     }
604
605     @Nullable
606     private BridgeEntry getBridgeEntryFromConfigDS(BigInteger dpnId) {
607         BridgeEntryKey bridgeEntryKey = new BridgeEntryKey(dpnId);
608         InstanceIdentifier<BridgeEntry> bridgeEntryInstanceIdentifier = getBridgeEntryIdentifier(bridgeEntryKey);
609         LOG.debug("Trying to retrieve bridge entry from config for Id: {}", bridgeEntryInstanceIdentifier);
610         return getBridgeEntryFromConfigDS(bridgeEntryInstanceIdentifier);
611     }
612
613     @Nullable
614     private BridgeEntry getBridgeEntryFromConfigDS(InstanceIdentifier<BridgeEntry> bridgeEntryInstanceIdentifier) {
615         return MDSALUtil.read(LogicalDatastoreType.CONFIGURATION, bridgeEntryInstanceIdentifier, dataBroker).orNull();
616     }
617
618     @Nullable
619     private BridgeRefEntry getBridgeRefEntryFromOperDS(InstanceIdentifier<BridgeRefEntry> dpnBridgeEntryIid) {
620         return MDSALUtil.read(LogicalDatastoreType.OPERATIONAL, dpnBridgeEntryIid, dataBroker).orNull();
621     }
622
623     @Nullable
624     private OvsdbBridgeRef getBridgeRefEntryFromOperDS(BigInteger dpId) {
625         BridgeRefEntryKey bridgeRefEntryKey = new BridgeRefEntryKey(dpId);
626         InstanceIdentifier<BridgeRefEntry> bridgeRefEntryIid = getBridgeRefEntryIdentifier(bridgeRefEntryKey);
627         BridgeRefEntry bridgeRefEntry = getBridgeRefEntryFromOperDS(bridgeRefEntryIid);
628         if (bridgeRefEntry == null) {
629             // bridge ref entry will be null if the bridge is disconnected from controller.
630             // In that case, fetch bridge reference from bridge interface entry config DS
631             BridgeEntry bridgeEntry = getBridgeEntryFromConfigDS(dpId);
632             if (bridgeEntry == null) {
633                 return null;
634             }
635             return  bridgeEntry.getBridgeReference();
636         }
637         return bridgeRefEntry.getBridgeReference();
638     }
639
640     @Nonnull
641     private static InstanceIdentifier<BridgeRefEntry> getBridgeRefEntryIdentifier(BridgeRefEntryKey bridgeRefEntryKey) {
642         return InstanceIdentifier.builder(BridgeRefInfo.class).child(BridgeRefEntry.class, bridgeRefEntryKey).build();
643     }
644
645     @Nonnull
646     private static InstanceIdentifier<BridgeEntry> getBridgeEntryIdentifier(BridgeEntryKey bridgeEntryKey) {
647         return InstanceIdentifier.builder(BridgeInterfaceInfo.class).child(BridgeEntry.class, bridgeEntryKey).build();
648     }
649
650     public void removeStaleFlowEntry(Interface intrf, int ethType) {
651         List<MatchInfo> matches = new ArrayList<>();
652
653         BigInteger dpnId = getDpIdFromInterface(intrf);
654
655         Integer ifIndex = intrf.getIfIndex();
656         matches.add(new MatchMetadata(MetaDataUtil.getLportTagMetaData(ifIndex), MetaDataUtil.METADATA_MASK_LPORT_TAG));
657         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpnId, NwConstants.QOS_DSCP_TABLE,
658                 getQosFlowId(NwConstants.QOS_DSCP_TABLE, dpnId, ifIndex, ethType),
659                 QosConstants.QOS_DEFAULT_FLOW_PRIORITY, "QoSRemoveFlow", 0, 0, NwConstants.COOKIE_QOS_TABLE,
660                 matches, null);
661         mdsalUtils.removeFlow(flowEntity);
662     }
663
664     public void addFlow(BigInteger dpnId, Short dscpValue, String ifName, int ethType, Interface ifState) {
665         if (ifState == null) {
666             LOG.debug("Could not find the ifState for interface {}", ifName);
667             return;
668         }
669         Integer ifIndex = ifState.getIfIndex();
670
671         List<MatchInfo> matches = new ArrayList<>();
672         matches.add(new MatchEthernetType(ethType));
673         matches.add(new MatchMetadata(MetaDataUtil.getLportTagMetaData(ifIndex), MetaDataUtil.METADATA_MASK_LPORT_TAG));
674
675         List<ActionInfo> actionsInfos = new ArrayList<>();
676         actionsInfos.add(new ActionSetFieldDscp(dscpValue));
677         actionsInfos.add(new ActionNxResubmit(NwConstants.LPORT_DISPATCHER_TABLE));
678
679         List<InstructionInfo> instructions = Collections.singletonList(new InstructionApplyActions(actionsInfos));
680         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpnId, NwConstants.QOS_DSCP_TABLE,
681                 getQosFlowId(NwConstants.QOS_DSCP_TABLE, dpnId, ifIndex, ethType),
682                 QosConstants.QOS_DEFAULT_FLOW_PRIORITY, "QoSConfigFlow", 0, 0, NwConstants.COOKIE_QOS_TABLE,
683                 matches, instructions);
684         mdsalUtils.installFlow(flowEntity);
685     }
686
687     public void removeFlow(BigInteger dpnId, String ifName, int ethType, Interface ifState) {
688         if (ifState == null) {
689             LOG.debug("Could not find the ifState for interface {}", ifName);
690             return;
691         }
692         Integer ifIndex = ifState.getIfIndex();
693
694         mdsalUtils.removeFlow(dpnId, NwConstants.QOS_DSCP_TABLE,
695                 new FlowId(getQosFlowId(NwConstants.QOS_DSCP_TABLE, dpnId, ifIndex, ethType)));
696     }
697
698     @Nullable
699     public org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
700             .ietf.interfaces.rev140508.interfaces.state.Interface getInterfaceStateFromOperDS(
701             String interfaceName) {
702         return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL,
703                 createInterfaceStateInstanceIdentifier(interfaceName)).orNull();
704     }
705
706     @Nonnull
707     public static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
708             .ietf.interfaces.rev140508.interfaces.state.Interface> createInterfaceStateInstanceIdentifier(
709             String interfaceName) {
710         return InstanceIdentifier
711                 .builder(InterfacesState.class)
712                 .child(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
713                                 .ietf.interfaces.rev140508.interfaces.state.Interface.class,
714                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang
715                                 .ietf.interfaces.rev140508.interfaces.state.InterfaceKey(
716                                 interfaceName))
717                 .build();
718     }
719
720     public void bindservice(String ifName) {
721         int priority = QosConstants.QOS_DEFAULT_FLOW_PRIORITY;
722         int instructionKey = 0;
723         List<Instruction> instructions = new ArrayList<>();
724         instructions.add(MDSALUtil.buildAndGetGotoTableInstruction(NwConstants.QOS_DSCP_TABLE, ++instructionKey));
725         short qosServiceIndex = ServiceIndex.getIndex(NwConstants.QOS_SERVICE_NAME, NwConstants.QOS_SERVICE_INDEX);
726
727         BoundServices serviceInfo = getBoundServices(
728                 String.format("%s.%s", "qos", ifName), qosServiceIndex,
729                 priority, NwConstants.COOKIE_QOS_TABLE, instructions);
730         MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
731                 buildServiceId(ifName, qosServiceIndex),
732                 serviceInfo);
733     }
734
735     public void unbindservice(String ifName) {
736         MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, buildServiceId(ifName,
737                 ServiceIndex.getIndex(NwConstants.QOS_SERVICE_NAME, NwConstants.QOS_SERVICE_INDEX)));
738     }
739
740     private static InstanceIdentifier<BoundServices> buildServiceId(String interfaceName, short qosServiceIndex) {
741         return InstanceIdentifier.builder(ServiceBindings.class)
742                 .child(ServicesInfo.class, new ServicesInfoKey(interfaceName, ServiceModeIngress.class))
743                 .child(BoundServices.class, new BoundServicesKey(qosServiceIndex)).build();
744     }
745
746     private static BoundServices getBoundServices(String serviceName, short qosServiceIndex, int priority,
747                                                   BigInteger cookieQosTable, List<Instruction> instructions) {
748         StypeOpenflowBuilder augBuilder = new StypeOpenflowBuilder().setFlowCookie(cookieQosTable)
749                 .setFlowPriority(priority).setInstruction(instructions);
750         return new BoundServicesBuilder().withKey(new BoundServicesKey(qosServiceIndex)).setServiceName(serviceName)
751                 .setServicePriority(qosServiceIndex).setServiceType(ServiceTypeFlowBased.class)
752                 .addAugmentation(StypeOpenflow.class, augBuilder.build()).build();
753     }
754
755     @Nonnull
756     public static String getQosFlowId(short tableId, BigInteger dpId, int lportTag, int ethType) {
757         return new StringBuilder().append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(dpId)
758                 .append(NwConstants.FLOWID_SEPARATOR).append(lportTag)
759                 .append(NwConstants.FLOWID_SEPARATOR).append(ethType).toString();
760     }
761
762     public boolean portHasQosPolicy(Port port) {
763         LOG.trace("checking qos policy for port: {}", port.getUuid().getValue());
764
765         boolean isQosPolicy = port.augmentation(QosPortExtension.class) != null
766                 && port.augmentation(QosPortExtension.class).getQosPolicyId() != null;
767
768         LOG.trace("portHasQosPolicy for  port: {} return value {}", port.getUuid().getValue(), isQosPolicy);
769         return isQosPolicy;
770     }
771
772     @Nullable
773     public QosPolicy getQosPolicy(Port port) {
774         Uuid qosUuid = null;
775         QosPolicy qosPolicy = null;
776
777         if (port.augmentation(QosPortExtension.class) != null) {
778             qosUuid = port.augmentation(QosPortExtension.class).getQosPolicyId();
779         } else {
780             Network network = neutronVpnManager.getNeutronNetwork(port.getNetworkId());
781
782             if (network.augmentation(QosNetworkExtension.class) != null) {
783                 qosUuid = network.augmentation(QosNetworkExtension.class).getQosPolicyId();
784             }
785         }
786
787         if (qosUuid != null) {
788             qosPolicy = qosPolicyMap.get(qosUuid);
789         }
790
791         return qosPolicy;
792     }
793
794     public boolean hasDscpMarkingRule(QosPolicy qosPolicy) {
795         if (qosPolicy != null) {
796             return qosPolicy.getDscpmarkingRules() != null && !qosPolicy.getDscpmarkingRules().isEmpty();
797         }
798         return false;
799     }
800
801     public void addToPortCache(Port port) {
802         neutronPortMap.put(port.getUuid(), port);
803     }
804
805     public void removeFromPortCache(Port port) {
806         neutronPortMap.remove(port.getUuid());
807     }
808
809     public Port getNeutronPort(Uuid portUuid) {
810         return neutronPortMap.get(portUuid);
811     }
812
813     public Port getNeutronPort(String portName) {
814         return getNeutronPort(new Uuid(portName));
815     }
816
817     public void addToNetworkCache(Network network) {
818         neutronNetworkMap.put(network.getUuid(), network);
819     }
820
821     public void removeFromNetworkCache(Network network) {
822         neutronNetworkMap.remove(network.getUuid());
823     }
824
825     public Network getNeutronNetwork(Uuid networkUuid) {
826         return neutronNetworkMap.get(networkUuid);
827     }
828
829     public static BigInteger getDpnIdFromLowerLayerIf(String lowerLayerIf) {
830         try {
831             return new BigInteger(lowerLayerIf.substring(lowerLayerIf.indexOf(":") + 1, lowerLayerIf.lastIndexOf(":")));
832         } catch (NullPointerException e) {
833             return null;
834         }
835     }
836
837     public static String getPortNumberFromLowerLayerIf(String lowerLayerIf) {
838         try {
839             return (lowerLayerIf.substring(lowerLayerIf.lastIndexOf(":") + 1));
840         } catch (NullPointerException e) {
841             return null;
842         }
843     }
844
845     public int getIpVersions(Port port) {
846         int versions = 0;
847         for (FixedIps fixedIp: port.getFixedIps()) {
848             if (fixedIp.getIpAddress().getIpv4Address() != null) {
849                 versions |= (1 << QosConstants.IPV4_ADDR_MASK_BIT);
850             } else if (fixedIp.getIpAddress().getIpv6Address() != null) {
851                 versions |= (1 << QosConstants.IPV6_ADDR_MASK_BIT);
852             }
853         }
854         return versions;
855     }
856
857     public boolean hasIpv4Addr(int versions) {
858         if ((versions & (1 << QosConstants.IPV4_ADDR_MASK_BIT)) != 0) {
859             return true;
860         }
861         return false;
862     }
863
864     public boolean hasIpv6Addr(int versions) {
865         if ((versions & (1 << QosConstants.IPV6_ADDR_MASK_BIT)) != 0) {
866             return true;
867         }
868         return false;
869     }
870 }