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