Fixes
[vpnservice.git] / fibmanager / fibmanager-impl / src / main / java / org / opendaylight / vpnservice / fibmanager / FibManager.java
1 /*
2  * Copyright (c) 2015 - 2016 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.fibmanager;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14
15 import java.math.BigInteger;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.Future;
23
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
26 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.vpnmanager.api.IVpnManager;
31 import org.opendaylight.vpnservice.mdsalutil.AbstractDataChangeListener;
32 import org.opendaylight.vpnservice.itm.globals.ITMConstants;
33 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
34 import org.opendaylight.vpnservice.mdsalutil.ActionType;
35 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
36 import org.opendaylight.vpnservice.mdsalutil.InstructionInfo;
37 import org.opendaylight.vpnservice.mdsalutil.InstructionType;
38 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
39 import org.opendaylight.vpnservice.mdsalutil.MatchFieldType;
40 import org.opendaylight.vpnservice.mdsalutil.MatchInfo;
41 import org.opendaylight.vpnservice.mdsalutil.MetaDataUtil;
42 import org.opendaylight.vpnservice.mdsalutil.NwConstants;
43 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.PrefixToInterface;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceOpData;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.VpnIds;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.VpnIdsKey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnList;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.ItmRpcService;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.FibEntries;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTables;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTablesKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.vrfentries.VrfEntry;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeBase;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeMplsOverGre;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceInputBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetTunnelTypeInputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetTunnelTypeOutput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.OdlInterfaceRpcService;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.l3nexthop.rev150409.l3nexthop.vpnnexthops.VpnNexthop;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.yang.binding.DataObject;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
71 import org.opendaylight.yangtools.yang.common.RpcResult;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 public class FibManager extends AbstractDataChangeListener<VrfEntry> implements AutoCloseable{
76   private static final Logger LOG = LoggerFactory.getLogger(FibManager.class);
77   private static final String FLOWID_PREFIX = "L3.";
78   private ListenerRegistration<DataChangeListener> listenerRegistration;
79   private final DataBroker broker;
80   private IMdsalApiManager mdsalManager;
81   private IVpnManager vpnmanager;
82   private NexthopManager nextHopManager;
83   private ItmRpcService itmManager;
84   private OdlInterfaceRpcService interfaceManager;
85   private static final BigInteger COOKIE_VM_LFIB_TABLE = new BigInteger("8000002", 16);
86   private static final BigInteger COOKIE_VM_FIB_TABLE =  new BigInteger("8000003", 16);
87   private static final int DEFAULT_FIB_FLOW_PRIORITY = 10;
88   private static final BigInteger METADATA_MASK_CLEAR = new BigInteger("000000FFFFFFFFFF", 16);
89   private static final BigInteger CLEAR_METADATA = BigInteger.valueOf(0);
90   public static final BigInteger COOKIE_TUNNEL = new BigInteger("9000000", 16);
91
92
93   private static final FutureCallback<Void> DEFAULT_CALLBACK =
94       new FutureCallback<Void>() {
95         public void onSuccess(Void result) {
96           LOG.debug("Success in Datastore write operation");
97         }
98
99         public void onFailure(Throwable error) {
100           LOG.error("Error in Datastore write operation", error);
101         };
102       };
103
104   public FibManager(final DataBroker db) {
105     super(VrfEntry.class);
106     broker = db;
107     registerListener(db);
108   }
109
110   @Override
111   public void close() throws Exception {
112     if (listenerRegistration != null) {
113       try {
114         listenerRegistration.close();
115       } catch (final Exception e) {
116         LOG.error("Error when cleaning up DataChangeListener.", e);
117       }
118       listenerRegistration = null;
119     }
120     LOG.info("Fib Manager Closed");
121   }
122
123   public void setNextHopManager(NexthopManager nextHopManager) {
124     this.nextHopManager = nextHopManager;
125   }
126
127   public void setMdsalManager(IMdsalApiManager mdsalManager) {
128     this.mdsalManager = mdsalManager;
129   }
130
131   public void setVpnmanager(IVpnManager vpnmanager) {
132     this.vpnmanager = vpnmanager;
133   }
134
135   public void setITMRpcService(ItmRpcService itmManager) {
136       this.itmManager = itmManager;
137   }
138   
139   public void setInterfaceManager(OdlInterfaceRpcService ifManager) {
140       this.interfaceManager = ifManager;
141   }
142
143   private void registerListener(final DataBroker db) {
144     try {
145       listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
146                                                            getWildCardPath(), FibManager.this, DataChangeScope.SUBTREE);
147     } catch (final Exception e) {
148       LOG.error("FibManager DataChange listener registration fail!", e);
149       throw new IllegalStateException("FibManager registration Listener failed.", e);
150     }
151   }
152
153   private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
154                                                   InstanceIdentifier<T> path) {
155
156     ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
157
158     Optional<T> result = Optional.absent();
159     try {
160       result = tx.read(datastoreType, path).get();
161     } catch (Exception e) {
162       throw new RuntimeException(e);
163     }
164
165     return result;
166   }
167
168   private InstanceIdentifier<VrfEntry> getWildCardPath() {
169     return InstanceIdentifier.create(FibEntries.class).child(VrfTables.class).child(VrfEntry.class);
170   }
171
172   private <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
173                                                  InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
174     WriteTransaction tx = broker.newWriteOnlyTransaction();
175     tx.put(datastoreType, path, data, true);
176     Futures.addCallback(tx.submit(), callback);
177   }
178
179   @Override
180   protected void add(final InstanceIdentifier<VrfEntry> identifier,
181                      final VrfEntry vrfEntry) {
182     LOG.trace("key: " + identifier + ", value=" + vrfEntry );
183     createFibEntries(identifier, vrfEntry);
184   }
185
186   @Override
187   protected void remove(InstanceIdentifier<VrfEntry> identifier, VrfEntry vrfEntry) {
188     LOG.trace("key: " + identifier + ", value=" + vrfEntry);
189     deleteFibEntries(identifier, vrfEntry);
190   }
191
192   @Override
193   protected void update(InstanceIdentifier<VrfEntry> identifier, VrfEntry original, VrfEntry update) {
194     LOG.trace("key: " + identifier + ", original=" + original + ", update=" + update );
195     createFibEntries(identifier, update);
196   }
197
198   private void createFibEntries(final InstanceIdentifier<VrfEntry> identifier,
199                                 final VrfEntry vrfEntry) {
200     final VrfTablesKey vrfTableKey = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
201     Preconditions.checkNotNull(vrfTableKey, "VrfTablesKey cannot be null or empty!");
202     Preconditions.checkNotNull(vrfEntry, "VrfEntry cannot be null or empty!");
203
204     VpnInstanceOpDataEntry vpnInstance = getVpnInstance(vrfTableKey.getRouteDistinguisher());
205     Preconditions.checkNotNull(vpnInstance, "Vpn Instance not available!");
206     Preconditions.checkNotNull(vpnInstance.getVpnId(), "Vpn Instance with rd " + vpnInstance.getVrfId() + "has null vpnId!");
207
208     Collection<VpnToDpnList> vpnToDpnList = vpnInstance.getVpnToDpnList();
209     BigInteger localDpnId = createLocalFibEntry(vpnInstance.getVpnId(),
210               vrfTableKey.getRouteDistinguisher(), vrfEntry);
211     if (vpnToDpnList != null) {
212       for (VpnToDpnList curDpn : vpnToDpnList) {
213         if (!curDpn.getDpnId().equals(localDpnId)) {
214           createRemoteFibEntry(localDpnId, curDpn.getDpnId(), vpnInstance.getVpnId(),
215                                vrfTableKey, vrfEntry);
216         }
217       }
218     }
219   }
220
221   public BigInteger createLocalFibEntry(Long vpnId, String rd, VrfEntry vrfEntry) {
222     BigInteger localDpnId = BigInteger.ZERO;
223     Prefixes localNextHopInfo = getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
224     boolean staticRoute = false;
225
226     //If the vrf entry is a static/extra route, the nexthop of the entry would be a adjacency in the vpn
227     if(localNextHopInfo == null) {
228       localNextHopInfo = getPrefixToInterface(vpnId, vrfEntry.getNextHopAddress() + "/32");
229       staticRoute = true;
230     }
231
232     if(localNextHopInfo != null) {
233       localDpnId = localNextHopInfo.getDpnId();
234       long groupId = nextHopManager.createLocalNextHop(vpnId, localDpnId, localNextHopInfo.getVpnInterfaceName(),
235                                                         (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix());
236       List<ActionInfo> actionInfos = new ArrayList<ActionInfo>();
237
238       actionInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId)}));
239
240       makeConnectedRoute(localDpnId, vpnId, vrfEntry, rd, actionInfos, NwConstants.ADD_FLOW);
241       makeLFibTableEntry(localDpnId, vrfEntry.getLabel(), groupId, vrfEntry.getNextHopAddress(), NwConstants.ADD_FLOW);
242
243       LOG.debug("Installing tunnel table entry on dpn {} for interface {} with label {}", 
244                       localDpnId, localNextHopInfo.getVpnInterfaceName(), vrfEntry.getLabel());
245       makeTunnelTableEntry(localDpnId, vrfEntry.getLabel(), groupId);
246
247     }
248     return localDpnId;
249   }
250
251   private void makeTunnelTableEntry(BigInteger dpId, long label, long groupId/*String egressInterfaceName*/) {
252       List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
253       actionsInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
254
255
256       createTerminatingServiceActions(dpId, (int)label, actionsInfos);
257
258       LOG.debug("Terminating service Entry for dpID {} : label : {} egress : {} installed successfully {}",
259               dpId, label, groupId);
260   }
261
262   public void createTerminatingServiceActions( BigInteger destDpId, int label, List<ActionInfo> actionsInfos) {
263       List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
264
265       LOG.info("create terminatingServiceAction on DpnId = {} and serviceId = {} and actions = {}", destDpId , label,actionsInfos);
266
267       // Matching metadata
268       // FIXME vxlan vni bit set is not working properly with OVS.need to revisit
269       mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {BigInteger.valueOf(label)}));
270
271       List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
272       mkInstructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
273
274       FlowEntity terminatingServiceTableFlowEntity = MDSALUtil.buildFlowEntity(destDpId, NwConstants.INTERNAL_TUNNEL_TABLE,
275                       getFlowRef(destDpId, NwConstants.INTERNAL_TUNNEL_TABLE,label), 5, String.format("%s:%d","TST Flow Entry ",label),
276                       0, 0, COOKIE_TUNNEL.add(BigInteger.valueOf(label)),mkMatches, mkInstructions);
277
278       mdsalManager.installFlow(terminatingServiceTableFlowEntity);
279  }
280
281   private void removeTunnelTableEntry(BigInteger dpId, long label) {
282     FlowEntity flowEntity;
283     LOG.info("remove terminatingServiceActions called with DpnId = {} and label = {}", dpId , label);
284     List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
285     // Matching metadata
286     mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {BigInteger.valueOf(label)}));
287     flowEntity = MDSALUtil.buildFlowEntity(dpId,
288                                            NwConstants.INTERNAL_TUNNEL_TABLE,
289                                            getFlowRef(dpId, NwConstants.INTERNAL_TUNNEL_TABLE, (int)label),
290                                            5, String.format("%s:%d","TST Flow Entry ",label), 0, 0,
291                                            COOKIE_TUNNEL.add(BigInteger.valueOf(label)), mkMatches, null);
292     mdsalManager.removeFlow(flowEntity);
293     LOG.debug("Terminating service Entry for dpID {} : label : {} removed successfully {}",dpId, label);
294   }
295
296   public BigInteger deleteLocalFibEntry(Long vpnId, String rd, VrfEntry vrfEntry) {
297     BigInteger localDpnId = BigInteger.ZERO;
298     VpnNexthop localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getDestPrefix());
299     boolean staticRoute = false;
300
301     //If the vrf entry is a static/extra route, the nexthop of the entry would be a adjacency in the vpn
302     if(localNextHopInfo == null) {
303       localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getNextHopAddress() + "/32");
304       staticRoute = true;
305     }
306
307     if(localNextHopInfo != null) {
308       localDpnId = localNextHopInfo.getDpnId();
309       if (getPrefixToInterface(vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix()) == null) {
310         makeConnectedRoute(localDpnId, vpnId, vrfEntry, rd, null /* invalid */,
311                            NwConstants.DEL_FLOW);
312         makeLFibTableEntry(localDpnId, vrfEntry.getLabel(), 0 /* invalid */,
313                            vrfEntry.getNextHopAddress(), NwConstants.DEL_FLOW);
314         removeTunnelTableEntry(localDpnId, vrfEntry.getLabel());
315         deleteLocalAdjacency(localDpnId, vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix());
316       }
317     }
318     return localDpnId;
319   }
320
321   private InstanceIdentifier<Prefixes> getPrefixToInterfaceIdentifier(Long vpnId, String ipPrefix) {
322     return InstanceIdentifier.builder(PrefixToInterface.class)
323         .child(VpnIds.class, new VpnIdsKey(vpnId)).child(Prefixes.class, new PrefixesKey(ipPrefix)).build();
324   }
325
326   private Prefixes getPrefixToInterface(Long vpnId, String ipPrefix) {
327     Optional<Prefixes> localNextHopInfoData =
328         read(LogicalDatastoreType.OPERATIONAL, getPrefixToInterfaceIdentifier(vpnId, ipPrefix));
329     return  localNextHopInfoData.isPresent() ? localNextHopInfoData.get() : null;
330   }
331   
332
333   private Class<? extends TunnelTypeBase> getTunnelType(String ifName) {
334         try {
335             Future<RpcResult<GetTunnelTypeOutput>> result = interfaceManager.getTunnelType(
336                           new GetTunnelTypeInputBuilder().setIntfName(ifName).build());
337           RpcResult<GetTunnelTypeOutput> rpcResult = result.get();
338           if(!rpcResult.isSuccessful()) {
339               LOG.warn("RPC Call to getTunnelInterfaceId returned with Errors {}", rpcResult.getErrors());
340           } else {
341               return rpcResult.getResult().getTunnelType();
342           }
343           
344       } catch (InterruptedException | ExecutionException e) {
345           LOG.warn("Exception when getting tunnel interface Id for tunnel type {}", e);
346       }
347   
348   return null;
349
350   }
351   private void createRemoteFibEntry(final BigInteger localDpnId, final BigInteger remoteDpnId,
352                                     final long vpnId, final VrfTablesKey vrfTableKey,
353                                     final VrfEntry vrfEntry) {
354     String rd = vrfTableKey.getRouteDistinguisher();
355     LOG.debug("adding route " + vrfEntry.getDestPrefix() + " " + rd);
356     /********************************************/
357     String tunnelInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
358     if(tunnelInterface == null) {
359       LOG.error("Could not get interface for nexthop: {} in vpn {}",
360                                    vrfEntry.getNextHopAddress(), rd);
361       LOG.warn("Failed to add Route: {} in vpn: {}",
362                              vrfEntry.getDestPrefix(), rd);
363       return;
364     }
365       List<ActionInfo> actionInfos = new ArrayList<>();
366         Class<? extends TunnelTypeBase> tunnel_type = getTunnelType(tunnelInterface);
367     if (tunnel_type.equals(TunnelTypeMplsOverGre.class)) {
368         LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
369         actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
370         actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
371     } else {
372         int label = vrfEntry.getLabel().intValue();
373         BigInteger tunnelId;
374         // FIXME vxlan vni bit set is not working properly with OVS.need to revisit
375         if(tunnel_type.equals(TunnelTypeVxlan.class)) {
376                 tunnelId = BigInteger.valueOf(label);
377         } else {
378                 tunnelId = BigInteger.valueOf(label);
379         }
380         LOG.debug("adding set tunnel id action for label {}", label);
381         actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[]{
382                 tunnelId}));
383     }
384     actionInfos.addAll(nextHopManager.getEgressActionsForInterface(tunnelInterface));
385 /*
386     List<ActionInfo> actionInfos = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
387     if(actionInfos == null) {
388       LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
389                                    vrfEntry.getNextHopAddress(), rd);
390       LOG.warn("Failed to add Route: {} in vpn: {}",
391                              vrfEntry.getDestPrefix(), rd);
392       return;
393     }
394     BigInteger dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getDestPrefix());
395     if(dpnId == null) {
396         //This route may be extra route... try to query with nexthop Ip
397         LOG.debug("Checking for extra route to install remote fib entry {}", vrfEntry.getDestPrefix());
398         dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getNextHopAddress() + "/32");
399     }
400     if(dpnId == null) {
401         LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
402         actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
403         actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
404     } else {
405         int label = vrfEntry.getLabel().intValue();
406         LOG.debug("adding set tunnel id action for label {}", label);
407         actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[] {
408                 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet(label),
409                 MetaDataUtil.METADA_MASK_VALID_TUNNEL_ID_BIT_AND_TUNNEL_ID }));
410     }
411 **/
412       makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, actionInfos, NwConstants.ADD_FLOW);
413     LOG.debug(
414         "Successfully added fib entry for " + vrfEntry.getDestPrefix() + " vpnId " + vpnId);
415   }
416
417   private void deleteFibEntries(final InstanceIdentifier<VrfEntry> identifier,
418                                 final VrfEntry vrfEntry) {
419     final VrfTablesKey vrfTableKey = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
420     Preconditions.checkNotNull(vrfTableKey, "VrfTablesKey cannot be null or empty!");
421     Preconditions.checkNotNull(vrfEntry, "VrfEntry cannot be null or empty!");
422
423     VpnInstanceOpDataEntry vpnInstance = getVpnInstance(vrfTableKey.getRouteDistinguisher());
424     Preconditions.checkNotNull(vpnInstance, "Vpn Instance not available!");
425     Collection<VpnToDpnList> vpnToDpnList = vpnInstance.getVpnToDpnList();
426     BigInteger localDpnId = deleteLocalFibEntry(vpnInstance.getVpnId(),
427               vrfTableKey.getRouteDistinguisher(), vrfEntry);
428     if (vpnToDpnList != null) {
429       for (VpnToDpnList curDpn : vpnToDpnList) {
430         if (!curDpn.getDpnId().equals(localDpnId)) {
431           deleteRemoteRoute(localDpnId, curDpn.getDpnId(), vpnInstance.getVpnId(), vrfTableKey, vrfEntry);
432         }
433       }
434
435     }
436   }
437
438   public void deleteRemoteRoute(final BigInteger localDpnId, final BigInteger remoteDpnId,
439                                 final long vpnId, final VrfTablesKey vrfTableKey,
440                                 final VrfEntry vrfEntry) {
441     LOG.debug("deleting route "+ vrfEntry.getDestPrefix() + " "+vpnId);
442     String rd = vrfTableKey.getRouteDistinguisher();
443     String egressInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
444     if(egressInterface == null) {
445       LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
446                 vrfEntry.getNextHopAddress(), rd);
447       LOG.warn("Failed to delete Route: {} in vpn: {}",
448                vrfEntry.getDestPrefix(), rd);
449       return;
450     }
451
452     makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW);
453     LOG.debug("Successfully delete fib entry for "+ vrfEntry.getDestPrefix() + " vpnId "+vpnId);
454   }
455
456   private long getIpAddress(byte[] rawIpAddress) {
457     return (((rawIpAddress[0] & 0xFF) << (3 * 8)) + ((rawIpAddress[1] & 0xFF) << (2 * 8))
458             + ((rawIpAddress[2] & 0xFF) << (1 * 8)) + (rawIpAddress[3] & 0xFF)) & 0xffffffffL;
459   }
460
461   private void makeConnectedRoute(BigInteger dpId, long vpnId, VrfEntry vrfEntry, String rd,
462                                   List<ActionInfo> actionInfos, int addOrRemove) {
463     LOG.trace("makeConnectedRoute: vrfEntry {}",vrfEntry);
464     String values[] = vrfEntry.getDestPrefix().split("/");
465     String ipAddress = values[0];
466     int prefixLength = (values.length == 1) ? 0 : Integer.parseInt(values[1]);
467     LOG.debug("Adding route to DPN. ip {} masklen {}", ipAddress, prefixLength);
468     InetAddress destPrefix = null;
469     try {
470       destPrefix = InetAddress.getByName(ipAddress);
471     } catch (UnknownHostException e) {
472       LOG.error("UnknowHostException in addRoute. Failed  to add Route for ipPrefix {}", vrfEntry.getDestPrefix());
473       return;
474     }
475
476     List<MatchInfo> matches = new ArrayList<MatchInfo>();
477
478     matches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
479         BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID }));
480
481     matches.add(new MatchInfo(MatchFieldType.eth_type,
482                               new long[] { 0x0800L }));
483
484     if(prefixLength != 0) {
485       matches.add(new MatchInfo(MatchFieldType.ipv4_dst, new long[] {
486           getIpAddress(destPrefix.getAddress()), prefixLength }));
487     }
488
489     List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
490     if(addOrRemove == NwConstants.ADD_FLOW) {
491       instructions.add(new InstructionInfo(InstructionType.write_actions, actionInfos));
492     }
493
494     String flowRef = getFlowRef(dpId, NwConstants.L3_FIB_TABLE, rd, destPrefix);
495
496     FlowEntity flowEntity;
497
498     int priority = DEFAULT_FIB_FLOW_PRIORITY + prefixLength;
499     flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_FIB_TABLE, flowRef,
500                                            priority, flowRef, 0, 0,
501                                            COOKIE_VM_FIB_TABLE, matches, instructions);
502
503     if (addOrRemove == NwConstants.ADD_FLOW) {
504       /* We need to call sync API to install flow so that 2 DS operations on the same object do not
505       * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
506       * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
507       * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
508       * wait indefinitely. */
509       // FIXME: sync calls.
510       //mdsalManager.syncInstallFlow(flowEntity, 1);
511       mdsalManager.installFlow(flowEntity);
512     } else {
513       // FIXME: sync calls.
514       // mdsalManager.syncRemoveFlow(flowEntity, 1);
515       mdsalManager.removeFlow(flowEntity);
516     }
517   }
518
519   private void makeLFibTableEntry(BigInteger dpId, long label, long groupId,
520                                   String nextHop, int addOrRemove) {
521     List<MatchInfo> matches = new ArrayList<MatchInfo>();
522     matches.add(new MatchInfo(MatchFieldType.eth_type,
523                               new long[] { 0x8847L }));
524     matches.add(new MatchInfo(MatchFieldType.mpls_label, new String[]{Long.toString(label)}));
525
526     List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
527     List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
528     actionsInfos.add(new ActionInfo(ActionType.pop_mpls, new String[]{}));
529     actionsInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
530     instructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
531
532     // Install the flow entry in L3_LFIB_TABLE
533     String flowRef = getFlowRef(dpId, NwConstants.L3_LFIB_TABLE, label, nextHop);
534
535     FlowEntity flowEntity;
536     flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_LFIB_TABLE, flowRef,
537                                            DEFAULT_FIB_FLOW_PRIORITY, flowRef, 0, 0,
538                                            COOKIE_VM_LFIB_TABLE, matches, instructions);
539
540     if (addOrRemove == NwConstants.ADD_FLOW) {
541       /* We need to call sync API to install flow so that 2 DS operations on the same object do not
542       * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
543       * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
544       * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
545       * wait indefinitely. */
546
547       // FIXME:
548       // mdsalManager.syncInstallFlow(flowEntity, 1);
549       mdsalManager.installFlow(flowEntity);
550     } else {
551       // FIXME:
552       // mdsalManager.syncRemoveFlow(flowEntity, 1);
553       mdsalManager.removeFlow(flowEntity);
554     }
555     LOG.debug("LFIB Entry for dpID {} : label : {} group {} modified successfully {}",dpId, label, groupId );
556   }
557
558   private void deleteLocalAdjacency(final BigInteger dpId, final long vpnId, final String ipAddress) {
559     LOG.trace("deleteLocalAdjacency called with dpid {}, vpnId{}, ipAddress {}",dpId, vpnId, ipAddress);
560     try {
561       nextHopManager.removeLocalNextHop(dpId, vpnId, ipAddress);
562     } catch (NullPointerException e) {
563       LOG.trace("", e);
564     }
565   }
566
567   public void populateFibOnNewDpn(BigInteger dpnId, long vpnId, String rd) {
568     LOG.trace("New dpn {} for vpn {} : populateFibOnNewDpn", dpnId, rd);
569     InstanceIdentifier<VrfTables> id = buildVrfId(rd);
570     Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
571     if(vrfTable.isPresent()) {
572       for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
573         // Passing null as we don't know the dpn
574         // to which prefix is attached at this point
575         createRemoteFibEntry(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
576       }
577     }
578   }
579
580   public void cleanUpDpnForVpn(BigInteger dpnId, long vpnId, String rd) {
581     LOG.trace("Remove dpn {} for vpn {} : cleanUpDpnForVpn", dpnId, rd);
582     InstanceIdentifier<VrfTables> id = buildVrfId(rd);
583     Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
584     if(vrfTable.isPresent()) {
585       for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
586         // Passing null as we don't know the dpn
587         // to which prefix is attached at this point
588         deleteRemoteRoute(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
589       }
590     }
591   }
592
593   public static InstanceIdentifier<VrfTables> buildVrfId(String rd) {
594     InstanceIdentifierBuilder<VrfTables> idBuilder =
595         InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd));
596     InstanceIdentifier<VrfTables> id = idBuilder.build();
597     return id;
598   }
599
600   private String getFlowRef(BigInteger dpnId, short tableId, long label, String nextHop) {
601     return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
602         .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
603         .append(label).append(NwConstants.FLOWID_SEPARATOR)
604         .append(nextHop).toString();
605   }
606
607   private String getFlowRef(BigInteger dpnId, short tableId, String rd, InetAddress destPrefix) {
608     return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
609         .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
610         .append(rd).append(NwConstants.FLOWID_SEPARATOR)
611         .append(destPrefix.getHostAddress()).toString();
612   }
613
614   protected String resolveAdjacency(final BigInteger localDpnId, final BigInteger remoteDpnId,
615                                               final long vpnId, final VrfEntry vrfEntry) {
616     String adjacency = null;
617     LOG.trace("resolveAdjacency called with localdpid{} remotedpid {}, vpnId{}, VrfEntry {}", localDpnId, remoteDpnId, vpnId, vrfEntry);;
618     try {
619       adjacency =
620           nextHopManager.getRemoteNextHopPointer(localDpnId, remoteDpnId, vpnId,
621                                                  vrfEntry.getDestPrefix(),
622                                                  vrfEntry.getNextHopAddress());
623     } catch (NullPointerException e) {
624       LOG.trace("", e);
625     }
626     return adjacency;
627   }
628
629   protected VpnInstanceOpDataEntry getVpnInstance(String rd) {
630     InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier.create(VpnInstanceOpData.class).child(
631         VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd));
632     Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = read(LogicalDatastoreType.OPERATIONAL, id);
633     if(vpnInstanceOpData.isPresent()) {
634       return vpnInstanceOpData.get();
635     }
636     return null;
637   }
638
639     public void processNodeAdd(BigInteger dpnId) {
640         LOG.debug("Received notification to install TableMiss entries for dpn {} ", dpnId);
641         makeTableMissFlow(dpnId, NwConstants.ADD_FLOW);
642         makeL3IntfTblMissFlow(dpnId, NwConstants.ADD_FLOW);
643     }
644
645     private void makeTableMissFlow(BigInteger dpnId, int addOrRemove) {
646         final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
647         // Instruction to goto L3 InterfaceTable
648         List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
649         instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NwConstants.L3_INTERFACE_TABLE }));
650         List<MatchInfo> matches = new ArrayList<MatchInfo>();
651         FlowEntity flowEntityLfib = MDSALUtil.buildFlowEntity(dpnId, NwConstants.L3_LFIB_TABLE,
652                 getFlowRef(dpnId, NwConstants.L3_LFIB_TABLE, NwConstants.TABLE_MISS_FLOW),
653                 NwConstants.TABLE_MISS_PRIORITY, "Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
654
655         FlowEntity flowEntityFib = MDSALUtil.buildFlowEntity(dpnId,NwConstants.L3_FIB_TABLE, getFlowRef(dpnId, NwConstants.L3_FIB_TABLE, NwConstants.TABLE_MISS_FLOW),
656                 NwConstants.TABLE_MISS_PRIORITY, "FIB Table Miss Flow", 0, 0, COOKIE_VM_FIB_TABLE,
657                 matches, instructions);
658
659         if (addOrRemove == NwConstants.ADD_FLOW) {
660             LOG.debug("Invoking MDSAL to install Table Miss Entries");
661             mdsalManager.installFlow(flowEntityLfib);
662             mdsalManager.installFlow(flowEntityFib);
663         } else {
664             mdsalManager.removeFlow(flowEntityLfib);
665             mdsalManager.removeFlow(flowEntityFib);
666
667         }
668     }
669
670     private String getFlowRef(BigInteger dpnId, short tableId, int tableMiss) {
671         return new StringBuffer().append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
672                 .append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(tableMiss)
673                 .append(FLOWID_PREFIX).toString();
674     }
675
676   /*
677    * Install flow entry in protocol table to forward mpls
678    * coming through gre tunnel to LFIB table.
679    */
680   private void makeProtocolTableFlow(BigInteger dpnId, int addOrRemove) {
681     final BigInteger COOKIE_PROTOCOL_TABLE = new BigInteger("1070000", 16);
682     // Instruction to goto L3 InterfaceTable
683     List<InstructionInfo> instructions = new ArrayList<>();
684     instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] {NwConstants.L3_LFIB_TABLE}));
685     List<MatchInfo> matches = new ArrayList<MatchInfo>();
686     matches.add(new MatchInfo(MatchFieldType.eth_type,
687                               new long[] { 0x8847L }));
688     FlowEntity flowEntityToLfib = MDSALUtil.buildFlowEntity(dpnId, NwConstants.L3_PROTOCOL_TABLE,
689                                                           getFlowRef(dpnId, NwConstants.L3_PROTOCOL_TABLE,
690                                                                   NwConstants.L3_LFIB_TABLE),
691                                                           DEFAULT_FIB_FLOW_PRIORITY,
692                                                           "Protocol Table For LFIB",
693                                                           0, 0,
694                                                           COOKIE_PROTOCOL_TABLE,
695                                                           matches, instructions);
696
697     if (addOrRemove == NwConstants.ADD_FLOW) {
698       LOG.debug("Invoking MDSAL to install Protocol Entries for dpn {}", dpnId);
699       mdsalManager.installFlow(flowEntityToLfib);
700     } else {
701       mdsalManager.removeFlow(flowEntityToLfib);
702     }
703   }
704
705   public List<String> printFibEntries() {
706     List<String> result = new ArrayList<String>();
707     result.add(String.format("   %-7s  %-20s  %-20s  %-7s", "RD", "Prefix", "Nexthop", "Label"));
708     result.add("-------------------------------------------------------------------");
709     InstanceIdentifier<FibEntries> id = InstanceIdentifier.create(FibEntries.class);
710     Optional<FibEntries> fibEntries = read(LogicalDatastoreType.OPERATIONAL, id);
711     if (fibEntries.isPresent()) {
712       List<VrfTables> vrfTables = fibEntries.get().getVrfTables();
713       for (VrfTables vrfTable : vrfTables) {
714         for (VrfEntry vrfEntry : vrfTable.getVrfEntry()) {
715           result.add(String.format("   %-7s  %-20s  %-20s  %-7s", vrfTable.getRouteDistinguisher(),
716                   vrfEntry.getDestPrefix(), vrfEntry.getNextHopAddress(), vrfEntry.getLabel()));
717         }
718       }
719     }
720     return result;
721   }
722
723   private void makeL3IntfTblMissFlow(BigInteger dpnId, int addOrRemove) {
724     List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
725     List<MatchInfo> matches = new ArrayList<MatchInfo>();
726     final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
727     // Instruction to clear metadata except SI and LportTag bits
728     instructions.add(new InstructionInfo(InstructionType.write_metadata, new BigInteger[] {
729                     CLEAR_METADATA, METADATA_MASK_CLEAR }));
730     // Instruction to clear action
731     instructions.add(new InstructionInfo(InstructionType.clear_actions));
732     // Instruction to goto L3 InterfaceTable
733
734     instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { NwConstants.LPORT_DISPATCHER_TABLE }));
735
736     FlowEntity flowEntityL3Intf = MDSALUtil.buildFlowEntity(dpnId, NwConstants.L3_INTERFACE_TABLE,
737             getFlowRef(dpnId, NwConstants.L3_INTERFACE_TABLE, NwConstants.TABLE_MISS_FLOW),
738             NwConstants.TABLE_MISS_PRIORITY, "L3 Interface Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
739     if (addOrRemove == NwConstants.ADD_FLOW) {
740       LOG.info("Invoking MDSAL to install L3 interface Table Miss Entries");
741       mdsalManager.installFlow(flowEntityL3Intf);
742     } else {
743       mdsalManager.removeFlow(flowEntityL3Intf);
744     }
745   }
746
747 }