Merge "Fix for BUG 3623"
[vpnservice.git] / interfacemgr / interfacemgr-impl / src / main / java / org / opendaylight / vpnservice / interfacemgr / InterfaceManager.java
1 /*
2  * Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.vpnservice.interfacemgr;
9
10 import java.math.BigInteger;
11
12 import com.google.common.base.Optional;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Future;
21 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
22 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
23 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
24 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
25 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.idmanager.IdManager;
28 import org.opendaylight.vpnservice.AbstractDataChangeListener;
29 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
30 import org.opendaylight.vpnservice.mdsalutil.ActionType;
31 import org.opendaylight.vpnservice.mdsalutil.MatchFieldType;
32 import org.opendaylight.vpnservice.mdsalutil.MatchInfo;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.L2vlan;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
36 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.OperStatus;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdInput;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdInputBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdOutput;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.pools.IdPool;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.pools.id.pool.GeneratedIds;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.BaseIds;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfL2vlan;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfL3tunnel;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfMpls;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.IfStackedVlan;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.L3tunnel;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.Mpls;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.StackedVlan;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeBase;
61 import org.opendaylight.yangtools.concepts.ListenerRegistration;
62 import org.opendaylight.yangtools.yang.binding.DataObject;
63 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
64 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
65 import org.opendaylight.yangtools.yang.common.RpcResult;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class InterfaceManager extends AbstractDataChangeListener<Interface> implements AutoCloseable {
70     private static final Logger LOG = LoggerFactory.getLogger(InterfaceManager.class);
71     private ListenerRegistration<DataChangeListener> listenerRegistration;
72     private final DataBroker broker;
73     private final IdManager idManager;
74     private final Map<NodeConnectorId, String> mapNcToInterfaceName = new ConcurrentHashMap<>();
75     private final Map<NodeId, String> dbDpnEndpoints = new ConcurrentHashMap<>();
76
77     private static final FutureCallback<Void> DEFAULT_CALLBACK =
78                     new FutureCallback<Void>() {
79                         public void onSuccess(Void result) {
80                             LOG.debug("Success in Datastore write operation");
81                         }
82
83                         public void onFailure(Throwable error) {
84                             LOG.error("Error in Datastore write operation", error);
85                         }
86                     };
87
88     public InterfaceManager(final DataBroker db, final IdManager idmgr) {
89         super(Interface.class);
90         broker = db;
91         idManager = idmgr;
92         registerListener(db);
93     }
94
95     @Override
96     public void close() throws Exception {
97         if (listenerRegistration != null) {
98             try {
99                 listenerRegistration.close();
100             } catch (final Exception e) {
101                 LOG.error("Error when cleaning up DataChangeListener.", e);
102             }
103             listenerRegistration = null;
104         }
105         LOG.info("Interface Manager Closed");
106     }
107
108     private void registerListener(final DataBroker db) {
109         try {
110             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
111                     getWildCardPath(), InterfaceManager.this, DataChangeScope.SUBTREE);
112         } catch (final Exception e) {
113             LOG.error("InterfaceManager DataChange listener registration fail!", e);
114             throw new IllegalStateException("InterfaceManager registration Listener failed.", e);
115         }
116     }
117
118     @Override
119     protected void add(final InstanceIdentifier<Interface> identifier,
120             final Interface imgrInterface) {
121         LOG.trace("Adding interface key: " + identifier + ", value=" + imgrInterface );
122         addInterface(identifier, imgrInterface);
123     }
124
125     private InstanceIdentifier<Interface> buildId(final InstanceIdentifier<Interface> identifier) {
126         //TODO Make this generic and move to AbstractDataChangeListener or Utils.
127         final InterfaceKey key = identifier.firstKeyOf(Interface.class, InterfaceKey.class);
128         return buildId(key.getName());
129     }
130
131     private InstanceIdentifier<Interface> buildId(String interfaceName) {
132         //TODO Make this generic and move to AbstractDataChangeListener or Utils.
133         InstanceIdentifierBuilder<Interface> idBuilder =
134                 InstanceIdentifier.builder(Interfaces.class).child(Interface.class, new InterfaceKey(interfaceName));
135         InstanceIdentifier<Interface> id = idBuilder.build();
136         return id;
137     }
138
139
140     private void addInterface(final InstanceIdentifier<Interface> identifier,
141                               final Interface interf) {
142         NodeConnector nodeConn = getNodeConnectorFromDataStore(interf);
143         NodeConnectorId ncId = null;
144         updateInterfaceState(identifier, interf, nodeConn);
145         if (nodeConn == null) {
146             ncId = getNodeConnectorIdFromInterface(interf);
147         } else {
148             ncId = nodeConn.getId();
149         }
150         mapNcToInterfaceName.put(ncId, interf.getName());
151         if(interf.getType().isAssignableFrom(L3tunnel.class)) {
152             NodeId nodeId = getNodeIdFromNodeConnectorId(ncId);
153             IfL3tunnel l3Tunnel = interf.getAugmentation(IfL3tunnel.class);
154             dbDpnEndpoints.put(nodeId, l3Tunnel.getLocalIp().getIpv4Address().getValue());
155             LOG.trace("dbDpnEndpoints: {}",dbDpnEndpoints);
156         }
157     }
158
159     private void updateInterfaceState(InstanceIdentifier<Interface> identifier,
160                     Interface interf, NodeConnector nodeConn) {
161         /* Update InterfaceState
162          * 1. Get interfaces-state Identifier
163          * 2. Add interface to interfaces-state/interface
164          * 3. Get interface-id from id manager
165          * 4. Update interface-state with following:
166          *    admin-status = set to enable value
167          *    oper-status = Down [?]
168          *    if-index = interface-id
169         */
170         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id =
171                         IfmUtil.buildStateInterfaceId(interf.getName());
172         Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> stateIf =
173                         read(LogicalDatastoreType.OPERATIONAL, id);
174         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface stateIface;
175         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder ifaceBuilder =
176                         new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder();
177         if(!stateIf.isPresent()) {
178             // TODO: Get interface-id from IdManager
179             String ifName = interf.getName();
180             ifaceBuilder.setAdminStatus((interf.isEnabled()) ?  org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus.Up :
181                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus.Down);
182             ifaceBuilder.setOperStatus(getOperStatus(nodeConn));
183
184             ifaceBuilder.setIfIndex(getIfIndex(ifName)).setName(ifName).setType(interf.getType());
185             ifaceBuilder.setKey(IfmUtil.getStateInterfaceKeyFromName(ifName));
186             stateIface = ifaceBuilder.build();
187             LOG.trace("Adding stateIface {} and id {} to OPERATIONAL DS", stateIface, id);
188             asyncWrite(LogicalDatastoreType.OPERATIONAL, id, stateIface, DEFAULT_CALLBACK);
189         } else {
190             if(interf.isEnabled() != null) {
191                 ifaceBuilder.setAdminStatus((interf.isEnabled()) ?  org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus.Up :
192                     org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface.AdminStatus.Down);
193             }
194             if(interf.getType() != null) {
195                 ifaceBuilder.setType(interf.getType());
196             }
197             ifaceBuilder.setOperStatus(getOperStatus(nodeConn));
198             stateIface = ifaceBuilder.build();
199             LOG.trace("updating OPERATIONAL data store with stateIface {} and id {}", stateIface, id);
200             asyncUpdate(LogicalDatastoreType.OPERATIONAL, id, stateIface, DEFAULT_CALLBACK);
201         }
202     }
203
204     private Integer getIfIndex(String ifName) {
205         GetUniqueIdInput getIdInput = new GetUniqueIdInputBuilder()
206         .setPoolName(IfmConstants.IFM_IDPOOL_NAME).setIdKey(ifName)
207         .build();
208         //TODO: Proper error handling once IdManager code is complete
209         try {
210             Future<RpcResult<GetUniqueIdOutput>> result = idManager.getUniqueId(getIdInput);
211             RpcResult<GetUniqueIdOutput> rpcResult = result.get();
212             return rpcResult.getResult().getIdValue().intValue();
213         } catch (NullPointerException | InterruptedException | ExecutionException e) {
214             LOG.trace("",e);
215         }
216         /* This currently returns null, so let us get it from IdManager DS
217          * TODO: Start-delete-me
218          */
219
220         InstanceIdentifier<IdPool> id = IfmUtil.getPoolId(IfmConstants.IFM_IDPOOL_NAME);
221         Optional<IdPool> globalPool = read(LogicalDatastoreType.OPERATIONAL, id );
222         Long newIdValue = null;
223         if (globalPool.isPresent()) {
224             IdPool pool = globalPool.get();
225             List<GeneratedIds> generatedIds = pool.getGeneratedIds();
226             if ((generatedIds != null) && !generatedIds.isEmpty()) {
227                 for (GeneratedIds gen_id : generatedIds) {
228                     if (gen_id.getIdKey().equals(ifName)) {
229                         newIdValue = gen_id.getIdValue();
230                         LOG.debug("Id {} found for interface %s ", newIdValue, ifName);
231                         return newIdValue.intValue();
232                     }
233                 }
234             }
235         }
236         //TODO: End-delete-me
237         LOG.debug("Unable to get valid ifIndex for interface {}", ifName);
238         return IfmConstants.DEFAULT_IFINDEX;
239     }
240
241     private OperStatus getOperStatus(NodeConnector nodeConn) {
242         LOG.trace("nodeConn is {}", nodeConn);
243         if(nodeConn == null) {
244             return OperStatus.Down;
245         }else {
246             return OperStatus.Up;
247         }
248     }
249
250     private NodeConnector getNodeConnectorFromDataStore(Interface interf) {
251         NodeConnectorId ncId = interf.getAugmentation(BaseIds.class).getOfPortId();
252         //TODO: Replace with MDSAL Util method
253         NodeId nodeId = getNodeIdFromNodeConnectorId(ncId);
254         InstanceIdentifier<NodeConnector> ncIdentifier = InstanceIdentifier.builder(Nodes.class)
255                         .child(Node.class, new NodeKey(nodeId))
256                         .child(NodeConnector.class, new NodeConnectorKey(ncId)).build();
257
258         Optional<NodeConnector> nc = read(LogicalDatastoreType.OPERATIONAL, ncIdentifier);
259         if(nc.isPresent()) {
260             NodeConnector nodeConn = nc.get();
261             LOG.trace("nodeConnector: {}",nodeConn);
262             return nodeConn;
263         }
264         return null;
265     }
266
267     private NodeConnectorId getNodeConnectorIdFromInterface(Interface interf) {
268         return interf.getAugmentation(BaseIds.class).getOfPortId();
269     }
270
271     private void delInterface(final InstanceIdentifier<Interface> identifier,
272                               final Interface delInterface) {
273         InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id =
274                         IfmUtil.buildStateInterfaceId(delInterface.getName());
275         Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> stateIf =
276                         read(LogicalDatastoreType.OPERATIONAL, id);
277         if(stateIf.isPresent()) {
278             LOG.trace("deleting interfaces:state OPERATIONAL data store with id {}", id);
279             asyncRemove(LogicalDatastoreType.OPERATIONAL, id, DEFAULT_CALLBACK);
280             NodeConnectorId ncId = getNodeConnectorIdFromInterface(delInterface);
281             if(ncId != null) {
282                 mapNcToInterfaceName.remove(ncId);
283                 if(delInterface.getType().isAssignableFrom(L3tunnel.class)) {
284                     NodeId nodeId = getNodeIdFromNodeConnectorId(ncId);
285                     dbDpnEndpoints.remove(nodeId);
286                     LOG.trace("dbDpnEndpoints: {}",dbDpnEndpoints);
287                 }
288             }
289         }
290     }
291
292     private Node getNodeFromDataStore(Interface interf) {
293         NodeConnectorId ncId = interf.getAugmentation(BaseIds.class).getOfPortId();
294         //TODO: Replace with MDSAL Util method
295         NodeId nodeId = getNodeIdFromNodeConnectorId(ncId);
296         InstanceIdentifier<Node> ncIdentifier = InstanceIdentifier.builder(Nodes.class)
297                         .child(Node.class, new NodeKey(nodeId)).build();
298
299         Optional<Node> dpn = read(LogicalDatastoreType.OPERATIONAL, ncIdentifier);
300         if(dpn.isPresent()) {
301             Node node = dpn.get();
302             LOG.trace("node: {}",node);
303             return node;
304         }
305         return null;
306     }
307
308     private void updateInterface(final InstanceIdentifier<Interface> identifier,
309                               final Interface original, final Interface update) {
310         InstanceIdentifier<Interface> id = buildId(identifier);
311         Optional<Interface> port = read(LogicalDatastoreType.CONFIGURATION, id);
312         if(port.isPresent()) {
313             Interface interf = port.get();
314             NodeConnector nc = getNodeConnectorFromDataStore(update);
315             updateInterfaceState(identifier, update, nc);
316             /*
317              * Alternative is to get from interf and update map irrespective if NCID changed or not.
318              */
319             if(nc != null) {
320                 // Name doesn't change. Is it present in update?
321                 mapNcToInterfaceName.put(nc.getId(), original.getName());
322                 if(interf.getType().isAssignableFrom(L3tunnel.class)) {
323                     NodeId nodeId = getNodeIdFromNodeConnectorId(nc.getId());
324                     IfL3tunnel l3Tunnel = interf.getAugmentation(IfL3tunnel.class);
325                     dbDpnEndpoints.put(nodeId, l3Tunnel.getLocalIp().getIpv4Address().getValue());
326                     LOG.trace("dbEndpoints: {}",dbDpnEndpoints);
327                 }
328             }
329         }
330     }
331
332     private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
333             InstanceIdentifier<T> path) {
334
335         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
336
337         Optional<T> result = Optional.absent();
338         try {
339             result = tx.read(datastoreType, path).get();
340         } catch (Exception e) {
341             throw new RuntimeException(e);
342         }
343
344         return result;
345     }
346
347     private InstanceIdentifier<Interface> getWildCardPath() {
348         return InstanceIdentifier.create(Interfaces.class).child(Interface.class);
349     }
350
351     @Override
352     protected void remove(InstanceIdentifier<Interface> identifier, Interface del) {
353         LOG.trace("remove - key: " + identifier + ", value=" + del );
354         delInterface(identifier, del);
355     }
356
357     @Override
358     protected void update(InstanceIdentifier<Interface> identifier, Interface original, Interface update) {
359         LOG.trace("update - key: " + identifier + ", original=" + original + ", update=" + update );
360         updateInterface(identifier, original, update);
361     }
362
363     protected <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
364                     InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
365         WriteTransaction tx = broker.newWriteOnlyTransaction();
366         tx.put(datastoreType, path, data, true);
367         Futures.addCallback(tx.submit(), callback);
368     }
369
370     protected <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
371                     InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
372         WriteTransaction tx = broker.newWriteOnlyTransaction();
373         tx.merge(datastoreType, path, data, true);
374         Futures.addCallback(tx.submit(), callback);
375     }
376
377     protected <T extends DataObject> void asyncRemove(LogicalDatastoreType datastoreType,
378                     InstanceIdentifier<T> path, FutureCallback<Void> callback) {
379         WriteTransaction tx = broker.newWriteOnlyTransaction();
380         tx.delete(datastoreType, path);
381         Futures.addCallback(tx.submit(), callback);
382     }
383
384     void processPortAdd(NodeConnector port) {
385         NodeConnectorId portId = port.getId();
386         FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
387         LOG.debug("PortAdd: PortId { " + portId.getValue() + "} PortName {" + ofPort.getName() + "}");
388         String ifName = this.mapNcToInterfaceName.get(portId);
389         setInterfaceOperStatus(ifName, OperStatus.Up);
390     }
391
392     void processPortUpdate(NodeConnector oldPort, NodeConnector update) {
393         //TODO: Currently nothing to do here.
394     }
395
396     void processPortDelete(NodeConnector port) {
397         NodeConnectorId portId = port.getId();
398         FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
399         LOG.debug("PortDelete: PortId { "+portId.getValue()+"} PortName {"+ofPort.getName()+"}");
400         String ifName = this.mapNcToInterfaceName.get(portId);
401         setInterfaceOperStatus(ifName, OperStatus.Down);
402     }
403
404     private void setInterfaceOperStatus(String ifName, OperStatus opStatus) {
405         if (ifName != null) {
406             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id =
407                             IfmUtil.buildStateInterfaceId(ifName);
408             Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> stateIf =
409                             read(LogicalDatastoreType.OPERATIONAL, id);
410             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface stateIface;
411             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder ifaceBuilder =
412                             new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder();
413             if (stateIf.isPresent()) {
414                 stateIface = ifaceBuilder.setOperStatus(opStatus).setKey(IfmUtil.getStateInterfaceKeyFromName(ifName)).build();
415                 LOG.trace("Setting OperStatus for {} to {} in OPERATIONAL DS", ifName, opStatus);
416                 asyncUpdate(LogicalDatastoreType.OPERATIONAL, id, stateIface, DEFAULT_CALLBACK);
417             }
418         }
419     }
420
421     private Interface getInterfaceByIfName(String ifName) {
422         InstanceIdentifier<Interface> id = buildId(ifName);
423         Optional<Interface> port = read(LogicalDatastoreType.CONFIGURATION, id);
424         if(port.isPresent()) {
425             return port.get();
426         }
427         return null;
428     }
429
430     Long getPortForInterface(String ifName) {
431         Interface iface = getInterfaceByIfName(ifName);
432         return getPortNumForInterface(iface);
433     }
434
435     Long getPortForInterface(Interface intrf) {
436         try {
437             NodeConnector port = getNodeConnectorFromDataStore(intrf);
438             NodeConnectorId id = null;
439             if(port == null) {
440                 id = getNodeConnectorIdFromInterface(intrf);
441             } else {
442                 id = port.getId();
443             }
444             String portNo = IfmUtil.getPortNoFromNodeConnectorId(id);
445             return Long.parseLong(portNo);
446         } catch (NullPointerException e) {
447             LOG.error("Port for Interface {} not found", intrf.getName(), e);
448         }
449         return 0L;
450     }
451
452     public BigInteger getDpnForInterface(Interface intrf) {
453         try {
454             NodeConnector port = getNodeConnectorFromDataStore(intrf);
455             NodeConnectorId id = null;
456             if(port == null) {
457                 id = getNodeConnectorIdFromInterface(intrf);
458             } else {
459                 id = port.getId();
460             }
461             //TODO: This should be an MDSAL Util method
462             return new BigInteger(IfmUtil.getDpnFromNodeConnectorId(id));
463         } catch (NullPointerException e) {
464             LOG.error("dpn for Interface {} not found", intrf.getName(), e);
465         }
466         return BigInteger.ZERO;
467     }
468
469     BigInteger getDpnForInterface(String ifName) {
470         Interface iface = getInterfaceByIfName(ifName);
471         if(iface != null) {
472             return getDpnForInterface(iface);
473         }
474         LOG.error("Interface {} doesn't exist", ifName);
475         return BigInteger.ZERO;
476     }
477
478     String getEndpointIpForDpn(BigInteger dpnId) {
479         //TODO: This should be MDSAL Util function
480         NodeId dpnNodeId = IfmUtil.buildDpnNodeId(dpnId);
481         return dbDpnEndpoints.get(dpnNodeId);
482     }
483
484     List<MatchInfo> getInterfaceIngressRule(String ifName) {
485         Interface iface = getInterfaceByIfName(ifName);
486         List<MatchInfo> matches = new ArrayList<MatchInfo>();
487         Class<? extends InterfaceType> ifType = iface.getType();
488         BigInteger dpn = this.getDpnForInterface(ifName);
489         long portNo = this.getPortNumForInterface(iface).longValue();
490         matches.add(new MatchInfo(MatchFieldType.in_port, new BigInteger[] {dpn, BigInteger.valueOf(portNo)}));
491
492         if (ifType.isInstance(L2vlan.class)) {
493             IfL2vlan vlanIface = iface.getAugmentation(IfL2vlan.class);
494             long vlanVid = vlanIface.getVlanId().longValue();
495             if (vlanVid != 0) {
496                 matches.add(new MatchInfo(MatchFieldType.vlan_vid,
497                             new long[] {vlanVid}));
498                 LOG.trace("L2Vlan: {}",vlanIface);
499             }
500         } else if (ifType.isInstance(L3tunnel.class)) {
501             //TODO: Handle different tunnel types
502             IfL3tunnel ifL3Tunnel = iface.getAugmentation(IfL3tunnel.class);
503             Class<? extends TunnelTypeBase> tunnType = ifL3Tunnel.getTunnelType();
504             LOG.trace("L3Tunnel: {}",ifL3Tunnel);
505         } else if (ifType.isAssignableFrom(StackedVlan.class)) {
506             IfStackedVlan ifStackedVlan = iface.getAugmentation(IfStackedVlan.class);
507             LOG.trace("StackedVlan: {}",ifStackedVlan);
508         } else if (ifType.isAssignableFrom(Mpls.class)) {
509             IfMpls ifMpls = iface.getAugmentation(IfMpls.class);
510             LOG.trace("Mpls: {}",ifMpls);
511         }
512         return matches;
513     }
514
515     public List<ActionInfo> getInterfaceEgressActions(String ifName) {
516         Interface iface = getInterfaceByIfName(ifName);
517
518         List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
519         Class<? extends InterfaceType> ifType = iface.getType();
520         BigInteger dpn = this.getDpnForInterface(ifName);
521         long portNo = this.getPortNumForInterface(iface).longValue();
522         if (iface.isEnabled()) {
523
524             if(ifType.isAssignableFrom(L2vlan.class)) {
525                 IfL2vlan vlanIface = iface.getAugmentation(IfL2vlan.class);
526                 LOG.trace("L2Vlan: {}",vlanIface);
527                 long vlanVid = (vlanIface == null) ? 0 : vlanIface.getVlanId();
528                 if (vlanVid != 0) {
529                     listActionInfo.add(new ActionInfo(ActionType.push_vlan, new String[] {}));
530                     listActionInfo.add(new ActionInfo(ActionType.set_field_vlan_vid,
531                             new String[] { Long.toString(vlanVid) }));
532                 }
533                 listActionInfo.add(new ActionInfo(ActionType.output, new String[] { Long.toString(portNo)}));
534
535             } else if (ifType.isAssignableFrom(L3tunnel.class)) {
536                 //TODO: Handle different tunnel types
537                 IfL3tunnel ifL3Tunnel = iface.getAugmentation(IfL3tunnel.class);
538                 Class<? extends TunnelTypeBase> tunnType = ifL3Tunnel.getTunnelType();
539                 LOG.trace("L3Tunnel: {}",ifL3Tunnel);
540                 //TODO: check switch_type and configure accordingly
541                 listActionInfo.add(new ActionInfo(ActionType.output, new String[] { Long.toString(portNo)}));
542
543             } else if (ifType.isAssignableFrom(StackedVlan.class)) {
544                 IfStackedVlan ifStackedVlan = iface.getAugmentation(IfStackedVlan.class);
545                 LOG.trace("StackedVlan: {}",ifStackedVlan);
546                 // TODO: TBD
547             } else if (ifType.isAssignableFrom(Mpls.class)) {
548                 IfMpls ifMpls = iface.getAugmentation(IfMpls.class);
549                 LOG.trace("Mpls: {}",ifMpls);
550                 // TODO: TBD
551             }
552         }
553         return listActionInfo;
554
555     }
556
557     private NodeId getNodeIdFromNodeConnectorId(NodeConnectorId ncId) {
558         return new NodeId(ncId.getValue().substring(0,ncId.getValue().lastIndexOf(":")));
559     }
560
561     private Long getPortNumForInterface(Interface iface) {
562         try {
563             NodeConnector port = getNodeConnectorFromDataStore(iface);
564             FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
565             return ofPort.getPortNumber().getUint32();
566         } catch (Exception e) {
567             LOG.error("OFPort for Interface {} not found", iface.getName());
568         }
569         return 0L;
570     }
571
572 }