Handling port up down event for Bug 3558
[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                     Node node = getNodeFromDataStore(delInterface);
285                     if((node != null) &&(node.getNodeConnector().isEmpty())) {
286                         dbDpnEndpoints.remove(node.getId());
287                         LOG.trace("dbDpnEndpoints: {}",dbDpnEndpoints);
288                     }
289                 }
290             }
291         }
292     }
293
294     private Node getNodeFromDataStore(Interface interf) {
295         NodeConnectorId ncId = interf.getAugmentation(BaseIds.class).getOfPortId();
296         //TODO: Replace with MDSAL Util method
297         NodeId nodeId = getNodeIdFromNodeConnectorId(ncId);
298         InstanceIdentifier<Node> ncIdentifier = InstanceIdentifier.builder(Nodes.class)
299                         .child(Node.class, new NodeKey(nodeId)).build();
300
301         Optional<Node> dpn = read(LogicalDatastoreType.OPERATIONAL, ncIdentifier);
302         if(dpn.isPresent()) {
303             Node node = dpn.get();
304             LOG.trace("node: {}",node);
305             return node;
306         }
307         return null;
308     }
309
310     private void updateInterface(final InstanceIdentifier<Interface> identifier,
311                               final Interface original, final Interface update) {
312         InstanceIdentifier<Interface> id = buildId(identifier);
313         Optional<Interface> port = read(LogicalDatastoreType.CONFIGURATION, id);
314         if(port.isPresent()) {
315             Interface interf = port.get();
316             NodeConnector nc = getNodeConnectorFromDataStore(update);
317             updateInterfaceState(identifier, update, nc);
318             /*
319              * Alternative is to get from interf and update map irrespective if NCID changed or not.
320              */
321             if(nc != null) {
322                 // Name doesn't change. Is it present in update?
323                 mapNcToInterfaceName.put(nc.getId(), original.getName());
324                 if(interf.getType().isAssignableFrom(L3tunnel.class)) {
325                     NodeId nodeId = getNodeIdFromNodeConnectorId(nc.getId());
326                     IfL3tunnel l3Tunnel = interf.getAugmentation(IfL3tunnel.class);
327                     dbDpnEndpoints.put(nodeId, l3Tunnel.getLocalIp().getIpv4Address().getValue());
328                     LOG.trace("dbEndpoints: {}",dbDpnEndpoints);
329                 }
330             }
331         }
332     }
333
334     private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
335             InstanceIdentifier<T> path) {
336
337         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
338
339         Optional<T> result = Optional.absent();
340         try {
341             result = tx.read(datastoreType, path).get();
342         } catch (Exception e) {
343             throw new RuntimeException(e);
344         }
345
346         return result;
347     }
348
349     private InstanceIdentifier<Interface> getWildCardPath() {
350         return InstanceIdentifier.create(Interfaces.class).child(Interface.class);
351     }
352
353     @Override
354     protected void remove(InstanceIdentifier<Interface> identifier, Interface del) {
355         LOG.trace("remove - key: " + identifier + ", value=" + del );
356         delInterface(identifier, del);
357     }
358
359     @Override
360     protected void update(InstanceIdentifier<Interface> identifier, Interface original, Interface update) {
361         LOG.trace("update - key: " + identifier + ", original=" + original + ", update=" + update );
362         updateInterface(identifier, original, update);
363     }
364
365     protected <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
366                     InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
367         WriteTransaction tx = broker.newWriteOnlyTransaction();
368         tx.put(datastoreType, path, data, true);
369         Futures.addCallback(tx.submit(), callback);
370     }
371
372     protected <T extends DataObject> void asyncUpdate(LogicalDatastoreType datastoreType,
373                     InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
374         WriteTransaction tx = broker.newWriteOnlyTransaction();
375         tx.merge(datastoreType, path, data, true);
376         Futures.addCallback(tx.submit(), callback);
377     }
378
379     protected <T extends DataObject> void asyncRemove(LogicalDatastoreType datastoreType,
380                     InstanceIdentifier<T> path, FutureCallback<Void> callback) {
381         WriteTransaction tx = broker.newWriteOnlyTransaction();
382         tx.delete(datastoreType, path);
383         Futures.addCallback(tx.submit(), callback);
384     }
385
386     void processPortAdd(NodeConnector port) {
387         NodeConnectorId portId = port.getId();
388         FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
389         LOG.debug("PortAdd: PortId { " + portId.getValue() + "} PortName {" + ofPort.getName() + "}");
390         String ifName = this.mapNcToInterfaceName.get(portId);
391         setInterfaceOperStatus(ifName, OperStatus.Up);
392     }
393
394     void processPortUpdate(NodeConnector oldPort, NodeConnector update) {
395         //TODO: Currently nothing to do here.
396     }
397
398     void processPortDelete(NodeConnector port) {
399         NodeConnectorId portId = port.getId();
400         FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
401         LOG.debug("PortDelete: PortId { "+portId.getValue()+"} PortName {"+ofPort.getName()+"}");
402         String ifName = this.mapNcToInterfaceName.get(portId);
403         setInterfaceOperStatus(ifName, OperStatus.Down);
404     }
405
406     private void setInterfaceOperStatus(String ifName, OperStatus opStatus) {
407         if (ifName != null) {
408             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> id =
409                             IfmUtil.buildStateInterfaceId(ifName);
410             Optional<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface> stateIf =
411                             read(LogicalDatastoreType.OPERATIONAL, id);
412             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface stateIface;
413             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder ifaceBuilder =
414                             new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder();
415             if (stateIf.isPresent()) {
416                 stateIface = ifaceBuilder.setOperStatus(opStatus).setKey(IfmUtil.getStateInterfaceKeyFromName(ifName)).build();
417                 LOG.trace("Setting OperStatus for {} to {} in OPERATIONAL DS", ifName, opStatus);
418                 asyncUpdate(LogicalDatastoreType.OPERATIONAL, id, stateIface, DEFAULT_CALLBACK);
419             }
420         }
421     }
422
423     private Interface getInterfaceByIfName(String ifName) {
424         InstanceIdentifier<Interface> id = buildId(ifName);
425         Optional<Interface> port = read(LogicalDatastoreType.CONFIGURATION, id);
426         if(port.isPresent()) {
427             return port.get();
428         }
429         return null;
430     }
431
432     Long getPortForInterface(String ifName) {
433         Interface iface = getInterfaceByIfName(ifName);
434         return getPortNumForInterface(iface);
435     }
436
437     Long getPortForInterface(Interface intrf) {
438         try {
439             NodeConnector port = getNodeConnectorFromDataStore(intrf);
440             NodeConnectorId id = null;
441             if(port == null) {
442                 id = getNodeConnectorIdFromInterface(intrf);
443             } else {
444                 id = port.getId();
445             }
446             String portNo = IfmUtil.getPortNoFromNodeConnectorId(id);
447             return Long.parseLong(portNo);
448         } catch (NullPointerException e) {
449             LOG.error("Port for Interface {} not found", intrf.getName(), e);
450         }
451         return 0L;
452     }
453
454     public BigInteger getDpnForInterface(Interface intrf) {
455         try {
456             NodeConnector port = getNodeConnectorFromDataStore(intrf);
457             NodeConnectorId id = null;
458             if(port == null) {
459                 id = getNodeConnectorIdFromInterface(intrf);
460             } else {
461                 id = port.getId();
462             }
463             //TODO: This should be an MDSAL Util method
464             return new BigInteger(IfmUtil.getDpnFromNodeConnectorId(id));
465         } catch (NullPointerException e) {
466             LOG.error("dpn for Interface {} not found", intrf.getName(), e);
467         }
468         return BigInteger.ZERO;
469     }
470
471     BigInteger getDpnForInterface(String ifName) {
472         Interface iface = getInterfaceByIfName(ifName);
473         if(iface != null) {
474             return getDpnForInterface(iface);
475         }
476         LOG.error("Interface {} doesn't exist", ifName);
477         return BigInteger.ZERO;
478     }
479
480     String getEndpointIpForDpn(BigInteger dpnId) {
481         //TODO: This should be MDSAL Util function
482         NodeId dpnNodeId = IfmUtil.buildDpnNodeId(dpnId);
483         return dbDpnEndpoints.get(dpnNodeId);
484     }
485
486     List<MatchInfo> getInterfaceIngressRule(String ifName) {
487         Interface iface = getInterfaceByIfName(ifName);
488         List<MatchInfo> matches = new ArrayList<MatchInfo>();
489         Class<? extends InterfaceType> ifType = iface.getType();
490         BigInteger dpn = this.getDpnForInterface(ifName);
491         long portNo = this.getPortNumForInterface(iface).longValue();
492         matches.add(new MatchInfo(MatchFieldType.in_port, new BigInteger[] {dpn, BigInteger.valueOf(portNo)}));
493
494         if (ifType.isInstance(L2vlan.class)) {
495             IfL2vlan vlanIface = iface.getAugmentation(IfL2vlan.class);
496             long vlanVid = vlanIface.getVlanId().longValue();
497             if (vlanVid != 0) {
498                 matches.add(new MatchInfo(MatchFieldType.vlan_vid,
499                             new long[] {vlanVid}));
500                 LOG.trace("L2Vlan: {}",vlanIface);
501             }
502         } else if (ifType.isInstance(L3tunnel.class)) {
503             //TODO: Handle different tunnel types
504             IfL3tunnel ifL3Tunnel = iface.getAugmentation(IfL3tunnel.class);
505             Class<? extends TunnelTypeBase> tunnType = ifL3Tunnel.getTunnelType();
506             LOG.trace("L3Tunnel: {}",ifL3Tunnel);
507         } else if (ifType.isAssignableFrom(StackedVlan.class)) {
508             IfStackedVlan ifStackedVlan = iface.getAugmentation(IfStackedVlan.class);
509             LOG.trace("StackedVlan: {}",ifStackedVlan);
510         } else if (ifType.isAssignableFrom(Mpls.class)) {
511             IfMpls ifMpls = iface.getAugmentation(IfMpls.class);
512             LOG.trace("Mpls: {}",ifMpls);
513         }
514         return matches;
515     }
516
517     public List<ActionInfo> getInterfaceEgressActions(String ifName) {
518         Interface iface = getInterfaceByIfName(ifName);
519
520         List<ActionInfo> listActionInfo = new ArrayList<ActionInfo>();
521         Class<? extends InterfaceType> ifType = iface.getType();
522         BigInteger dpn = this.getDpnForInterface(ifName);
523         long portNo = this.getPortNumForInterface(iface).longValue();
524         if (iface.isEnabled()) {
525
526             if(ifType.isAssignableFrom(L2vlan.class)) {
527                 IfL2vlan vlanIface = iface.getAugmentation(IfL2vlan.class);
528                 LOG.trace("L2Vlan: {}",vlanIface);
529                 long vlanVid = (vlanIface == null) ? 0 : vlanIface.getVlanId();
530                 if (vlanVid != 0) {
531                     listActionInfo.add(new ActionInfo(ActionType.push_vlan, new String[] {}));
532                     listActionInfo.add(new ActionInfo(ActionType.set_field_vlan_vid,
533                             new String[] { Long.toString(vlanVid) }));
534                 }
535                 listActionInfo.add(new ActionInfo(ActionType.output, new String[] { Long.toString(portNo)}));
536
537             } else if (ifType.isAssignableFrom(L3tunnel.class)) {
538                 //TODO: Handle different tunnel types
539                 IfL3tunnel ifL3Tunnel = iface.getAugmentation(IfL3tunnel.class);
540                 Class<? extends TunnelTypeBase> tunnType = ifL3Tunnel.getTunnelType();
541                 LOG.trace("L3Tunnel: {}",ifL3Tunnel);
542                 //TODO: check switch_type and configure accordingly
543                 listActionInfo.add(new ActionInfo(ActionType.output, new String[] { Long.toString(portNo)}));
544
545             } else if (ifType.isAssignableFrom(StackedVlan.class)) {
546                 IfStackedVlan ifStackedVlan = iface.getAugmentation(IfStackedVlan.class);
547                 LOG.trace("StackedVlan: {}",ifStackedVlan);
548                 // TODO: TBD
549             } else if (ifType.isAssignableFrom(Mpls.class)) {
550                 IfMpls ifMpls = iface.getAugmentation(IfMpls.class);
551                 LOG.trace("Mpls: {}",ifMpls);
552                 // TODO: TBD
553             }
554         }
555         return listActionInfo;
556
557     }
558
559     private NodeId getNodeIdFromNodeConnectorId(NodeConnectorId ncId) {
560         return new NodeId(ncId.getValue().substring(0,ncId.getValue().lastIndexOf(":")));
561     }
562
563     private Long getPortNumForInterface(Interface iface) {
564         try {
565             NodeConnector port = getNodeConnectorFromDataStore(iface);
566             FlowCapableNodeConnector ofPort = port.getAugmentation(FlowCapableNodeConnector.class);
567             return ofPort.getPortNumber().getUint32();
568         } catch (Exception e) {
569             LOG.error("OFPort for Interface {} not found", iface.getName());
570         }
571         return 0L;
572     }
573
574 }