50f702ec4f1837249ef0984558e3fd93483eaf57
[genius.git] / itm / itm-impl / src / main / java / org / opendaylight / genius / itm / rpc / ItmManagerRpcService.java
1 /*
2  * Copyright (c) 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.genius.itm.rpc;
9
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
16 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.genius.itm.confighelpers.ItmExternalTunnelAddWorker;
19 import org.opendaylight.genius.itm.confighelpers.ItmExternalTunnelDeleteWorker;
20 import org.opendaylight.genius.itm.globals.ITMConstants;
21 import org.opendaylight.genius.itm.impl.ItmUtils;
22 import org.opendaylight.genius.mdsalutil.*;
23 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeMplsOverGre;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.ExternalTunnelList;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.TunnelList;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.DPNTEPsInfo;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.dpn.endpoints.dpn.teps.info.TunnelEndPoints;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnel;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.external.tunnel.list.ExternalTunnelKey;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnel;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.op.rev160406.tunnel.list.InternalTunnelKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.DcGatewayIpList;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.TransportZones;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIp;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIpBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.dc.gateway.ip.list.DcGatewayIpKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZone;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.TransportZoneKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.Subnets;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.SubnetsKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.DeviceVteps;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.DeviceVtepsBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rev160406.transport.zones.transport.zone.subnets.DeviceVtepsKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.*;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.opendaylight.yangtools.yang.common.RpcError;
52 import org.opendaylight.yangtools.yang.common.RpcResult;
53 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 import java.math.BigInteger;
58 import java.util.ArrayList;
59 import java.util.List;
60 import java.util.concurrent.Future;
61
62 public class ItmManagerRpcService implements ItmRpcService {
63
64     private static final Logger LOG = LoggerFactory.getLogger(ItmManagerRpcService.class);
65     DataBroker dataBroker;
66     private IMdsalApiManager mdsalManager;
67
68
69     public void setMdsalManager(IMdsalApiManager mdsalManager) {
70         this.mdsalManager = mdsalManager;
71     }
72
73     IdManagerService idManagerService;
74
75     public ItmManagerRpcService(DataBroker dataBroker, IdManagerService idManagerService) {
76         this.dataBroker = dataBroker;
77         this.idManagerService = idManagerService;
78     }
79
80     @Override
81     public Future<RpcResult<GetTunnelInterfaceNameOutput>> getTunnelInterfaceName(GetTunnelInterfaceNameInput input) {
82         RpcResultBuilder<GetTunnelInterfaceNameOutput> resultBld = null;
83         BigInteger sourceDpn = input.getSourceDpid() ;
84         BigInteger destinationDpn = input.getDestinationDpid() ;
85         InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(
86                 TunnelList.class)
87                 .child(InternalTunnel.class, new InternalTunnelKey(destinationDpn, sourceDpn, input.getTunnelType()));
88
89         Optional<InternalTunnel> tnl = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
90
91         if( tnl != null && tnl.isPresent())
92         {
93             InternalTunnel tunnel = tnl.get();
94             GetTunnelInterfaceNameOutputBuilder output = new GetTunnelInterfaceNameOutputBuilder() ;
95             output.setInterfaceName(tunnel.getTunnelInterfaceName()) ;
96             resultBld = RpcResultBuilder.success();
97             resultBld.withResult(output.build()) ;
98         }else {
99             resultBld = RpcResultBuilder.failed();
100         }
101
102         return Futures.immediateFuture(resultBld.build());
103     }
104
105
106     @Override
107     public Future<RpcResult<Void>> removeExternalTunnelEndpoint(
108             RemoveExternalTunnelEndpointInput input) {
109         //Ignore the Futures for now
110         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
111         List<DPNTEPsInfo> meshedDpnList = ItmUtils.getTunnelMeshInfo(dataBroker) ;
112         ItmExternalTunnelDeleteWorker.deleteTunnels(dataBroker, idManagerService,meshedDpnList , input.getDestinationIp(), input.getTunnelType());
113         InstanceIdentifier<DcGatewayIp> extPath= InstanceIdentifier.builder(DcGatewayIpList.class).child(DcGatewayIp.class, new DcGatewayIpKey(input.getDestinationIp())).build();
114         WriteTransaction t = dataBroker.newWriteOnlyTransaction();
115         t.delete(LogicalDatastoreType.CONFIGURATION, extPath);
116         ListenableFuture<Void> futureCheck = t.submit();
117         Futures.addCallback(futureCheck, new FutureCallback<Void>() {
118
119             @Override public void onSuccess(Void aVoid) {
120                 result.set(RpcResultBuilder.<Void>success().build());
121             }
122
123             @Override public void onFailure(Throwable error) {
124                 String msg = String.format("Unable to delete DcGatewayIp {} in datastore "+ input.getDestinationIp() + "and tunnel type " + input.getTunnelType());
125                 LOG.error("Unable to delete DcGatewayIp {} in datastore for ip "+ input.getDestinationIp() + "and tunnel type " + input.getTunnelType());
126                 result.set(RpcResultBuilder.<Void>failed()
127                         .withError(RpcError.ErrorType.APPLICATION, msg, error).build());
128             }
129         });
130         return result;
131     }
132
133     @Override
134     public Future<RpcResult<Void>> removeExternalTunnelFromDpns(
135             RemoveExternalTunnelFromDpnsInput input) {
136         //Ignore the Futures for now
137         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
138         List<DPNTEPsInfo> cfgDpnList = ItmUtils.getDPNTEPListFromDPNId(dataBroker, input.getDpnId()) ;
139         ItmExternalTunnelDeleteWorker.deleteTunnels(dataBroker, idManagerService, cfgDpnList, input.getDestinationIp(), input.getTunnelType());
140         result.set(RpcResultBuilder.<Void>success().build());
141         return result;
142     }
143
144     @Override
145     public Future<RpcResult<Void>> buildExternalTunnelFromDpns(
146             BuildExternalTunnelFromDpnsInput input) {
147         //Ignore the Futures for now
148         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
149         List<ListenableFuture<Void>> extTunnelResultList = ItmExternalTunnelAddWorker.buildTunnelsFromDpnToExternalEndPoint(dataBroker, idManagerService,input.getDpnId(), input.getDestinationIp(), input.getTunnelType());
150         for (ListenableFuture<Void> extTunnelResult : extTunnelResultList) {
151             Futures.addCallback(extTunnelResult, new FutureCallback<Void>(){
152
153                 @Override
154                 public void onSuccess(Void aVoid) {
155                     result.set(RpcResultBuilder.<Void>success().build());
156                 }
157
158                 @Override
159                 public void onFailure(Throwable error) {
160                     String msg = String.format("Unable to create ext tunnel");
161                     LOG.error("create ext tunnel failed. {}. {}", msg, error);
162                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, msg, error).build());
163                 }
164             });
165         }
166         result.set(RpcResultBuilder.<Void>success().build());
167         return result;
168     }
169
170     @Override
171     public Future<RpcResult<Void>> addExternalTunnelEndpoint(
172             AddExternalTunnelEndpointInput input) {
173         // TODO Auto-generated method stub
174
175         //Ignore the Futures for now
176         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
177         List<DPNTEPsInfo> meshedDpnList = ItmUtils.getTunnelMeshInfo(dataBroker) ;
178         ItmExternalTunnelAddWorker.buildTunnelsToExternalEndPoint(dataBroker, idManagerService,meshedDpnList, input.getDestinationIp(), input.getTunnelType()) ;InstanceIdentifier<DcGatewayIp> extPath= InstanceIdentifier.builder(DcGatewayIpList.class).child(DcGatewayIp.class, new DcGatewayIpKey(input.getDestinationIp())).build();
179         DcGatewayIp dcGatewayIp = new DcGatewayIpBuilder().setIpAddress(input.getDestinationIp()).setTunnnelType(input.getTunnelType()).build();
180         WriteTransaction t = dataBroker.newWriteOnlyTransaction();
181         t.put(LogicalDatastoreType.CONFIGURATION, extPath,dcGatewayIp, true);
182         ListenableFuture<Void> futureCheck = t.submit();
183         Futures.addCallback(futureCheck, new FutureCallback<Void>() {
184
185             @Override public void onSuccess(Void aVoid) {
186                 result.set(RpcResultBuilder.<Void>success().build());
187             }
188
189             @Override public void onFailure(Throwable error) {
190                 String msg = String.format("Unable to create DcGatewayIp {} in datastore for ip "+ input.getDestinationIp() + "and tunnel type " + input.getTunnelType());
191                 LOG.error("Unable to create DcGatewayIp {} in datastore for ip "+ input.getDestinationIp() + "and tunnel type " + input.getTunnelType());
192                 result.set(RpcResultBuilder.<Void>failed()
193                         .withError(RpcError.ErrorType.APPLICATION, msg, error).build());
194             }
195         });
196         return result;
197     }
198
199     @Override
200     public Future<RpcResult<GetExternalTunnelInterfaceNameOutput>> getExternalTunnelInterfaceName(
201             GetExternalTunnelInterfaceNameInput input) {
202         final SettableFuture<RpcResult<GetExternalTunnelInterfaceNameOutput>> result = SettableFuture.create() ;
203         RpcResultBuilder<GetExternalTunnelInterfaceNameOutput> resultBld;
204         String sourceNode = input.getSourceNode();
205         String dstNode = input.getDestinationNode();
206         InstanceIdentifier<ExternalTunnel> path = InstanceIdentifier.create(
207                 ExternalTunnelList.class)
208                 .child(ExternalTunnel.class, new ExternalTunnelKey(dstNode, sourceNode, input.getTunnelType()));
209
210         Optional<ExternalTunnel> ext = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
211
212         if( ext != null && ext.isPresent())
213         {
214             ExternalTunnel exTunnel = ext.get();
215             GetExternalTunnelInterfaceNameOutputBuilder output = new GetExternalTunnelInterfaceNameOutputBuilder() ;
216             output.setInterfaceName(exTunnel.getTunnelInterfaceName()) ;
217             resultBld = RpcResultBuilder.success();
218             resultBld.withResult(output.build()) ;
219         }else {
220             resultBld = RpcResultBuilder.failed();
221         }
222
223         return Futures.immediateFuture(resultBld.build());
224     }
225
226     @Override
227     public Future<RpcResult<java.lang.Void>> createTerminatingServiceActions(final CreateTerminatingServiceActionsInput input) {
228         LOG.info("create terminatingServiceAction on DpnId = {} for service id {} and instructions {}", input.getDpnId() , input.getServiceId(), input.getInstruction());
229         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
230         int serviceId = input.getServiceId() ;
231         List<MatchInfo> mkMatches = getTunnelMatchesForServiceId(serviceId);
232         byte[] vxLANHeader = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
233         // Flags Byte
234         byte Flags = (byte) 0x08;
235         vxLANHeader[0] = Flags;
236
237         // Extract the serviceId details and imprint on the VxLAN Header
238         vxLANHeader[4] = (byte) (serviceId >> 16);
239         vxLANHeader[5] = (byte) (serviceId >> 8);
240         vxLANHeader[6] = (byte) (serviceId >> 0);
241
242         // Matching metadata
243 //        mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
244 //                new BigInteger(1, vxLANHeader),
245 //                MetaDataUtil.METADA_MASK_VALID_TUNNEL_ID_BIT_AND_TUNNEL_ID }));
246
247         Flow terminatingServiceTableFlow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
248                 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,serviceId), 5, String.format("%s:%d","ITM Flow Entry ",serviceId),
249                 0, 0, ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(serviceId)),mkMatches, input.getInstruction());
250
251         ListenableFuture<Void> installFlowResult = mdsalManager.installFlow(input.getDpnId(), terminatingServiceTableFlow);
252         Futures.addCallback(installFlowResult, new FutureCallback<Void>(){
253
254             @Override
255             public void onSuccess(Void aVoid) {
256                 result.set(RpcResultBuilder.<Void>success().build());
257             }
258
259             @Override
260             public void onFailure(Throwable error) {
261                 String msg = String.format("Unable to install terminating service flow for %s", input.getDpnId());
262                 LOG.error("create terminating service actions failed. {}. {}", msg, error);
263                 result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, msg, error).build());
264             }
265         });
266         // result.set(RpcResultBuilder.<Void>success().build());
267         return result;
268     }
269
270     @Override
271     public Future<RpcResult<java.lang.Void>> removeTerminatingServiceActions(final RemoveTerminatingServiceActionsInput input) {
272         LOG.info("remove terminatingServiceActions called with DpnId = {} and serviceId = {}", input.getDpnId(), input.getServiceId());
273         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
274         Flow terminatingServiceTableFlow = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
275                 getFlowRef(NwConstants.INTERNAL_TUNNEL_TABLE,input.getServiceId()), 5, String.format("%s:%d","ITM Flow Entry ",input.getServiceId()),
276                 0, 0, ITMConstants.COOKIE_ITM.add(BigInteger.valueOf(input.getServiceId())),getTunnelMatchesForServiceId(input.getServiceId()), null );
277
278         ListenableFuture<Void> installFlowResult = mdsalManager.removeFlow(input.getDpnId(), terminatingServiceTableFlow);
279         Futures.addCallback(installFlowResult, new FutureCallback<Void>(){
280
281             @Override
282             public void onSuccess(Void aVoid) {
283                 result.set(RpcResultBuilder.<Void>success().build());
284             }
285
286             @Override
287             public void onFailure(Throwable error) {
288                 String msg = String.format("Unable to remove terminating service flow for %s", input.getDpnId());
289                 LOG.error("remove terminating service actions failed. {}. {}", msg, error);
290                 result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, msg, error).build());
291             }
292         });
293         //result.set(RpcResultBuilder.<Void>success().build());
294
295         return result ;
296     }
297
298
299     public List<MatchInfo> getTunnelMatchesForServiceId(int serviceId) {
300         List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
301         byte[] vxLANHeader = new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
302
303         // Flags Byte
304         byte Flags = (byte) 0x08;
305         vxLANHeader[0] = Flags;
306
307         // Extract the serviceId details and imprint on the VxLAN Header
308         vxLANHeader[4] = (byte) (serviceId >> 16);
309         vxLANHeader[5] = (byte) (serviceId >> 8);
310         vxLANHeader[6] = (byte) (serviceId >> 0);
311
312         // Matching metadata
313         mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[]{
314                 BigInteger.valueOf(serviceId)}));
315
316         return mkMatches;
317     }
318
319     private String getFlowRef(long termSvcTable, int svcId) {
320         return new StringBuffer().append(termSvcTable).append(svcId).toString();
321     }
322
323     @Override
324     public Future<RpcResult<GetInternalOrExternalInterfaceNameOutput>> getInternalOrExternalInterfaceName(
325             GetInternalOrExternalInterfaceNameInput input) {
326         RpcResultBuilder<GetInternalOrExternalInterfaceNameOutput> resultBld = RpcResultBuilder.failed();
327         BigInteger srcDpn = input.getSourceDpid() ;
328         String srcNode = srcDpn.toString();
329         IpAddress dstIp = input.getDestinationIp() ;
330         InstanceIdentifier<ExternalTunnel> path1 = InstanceIdentifier.create(
331                 ExternalTunnelList.class)
332                 .child(ExternalTunnel.class, new ExternalTunnelKey(String.valueOf(dstIp), srcDpn.toString(), TunnelTypeMplsOverGre.class));
333
334         Optional<ExternalTunnel> ext = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path1, dataBroker);
335
336         if( ext != null && ext.isPresent())
337         {
338             ExternalTunnel extTunnel = ext.get();
339             GetInternalOrExternalInterfaceNameOutputBuilder output = new GetInternalOrExternalInterfaceNameOutputBuilder().setInterfaceName(extTunnel.getTunnelInterfaceName() );
340             resultBld = RpcResultBuilder.success();
341             resultBld.withResult(output.build()) ;
342         } else {
343             List<DPNTEPsInfo> meshedDpnList = ItmUtils.getTunnelMeshInfo(dataBroker);
344             // Look for external tunnels if not look for internal tunnel
345             for (DPNTEPsInfo teps : meshedDpnList) {
346                 TunnelEndPoints firstEndPt = teps.getTunnelEndPoints().get(0);
347                 if (dstIp.equals(firstEndPt.getIpAddress())) {
348                     InstanceIdentifier<InternalTunnel> path = InstanceIdentifier.create(
349                             TunnelList.class)
350                             .child(InternalTunnel.class, new InternalTunnelKey(teps.getDPNID(), srcDpn, input.getTunnelType()));
351
352                     Optional<InternalTunnel>
353                             tnl =
354                             ItmUtils.read(LogicalDatastoreType.CONFIGURATION, path, dataBroker);
355                     if (tnl != null && tnl.isPresent()) {
356                         InternalTunnel tunnel = tnl.get();
357                         GetInternalOrExternalInterfaceNameOutputBuilder
358                                 output =
359                                 new GetInternalOrExternalInterfaceNameOutputBuilder()
360                                         .setInterfaceName(tunnel.getTunnelInterfaceName());
361                         resultBld = RpcResultBuilder.success();
362                         resultBld.withResult(output.build());
363                         break;
364                     }
365                 }
366             }
367         }
368         return Futures.immediateFuture(resultBld.build());
369     }
370
371     @Override
372     public Future<RpcResult<java.lang.Void>> deleteL2GwDevice(DeleteL2GwDeviceInput input) {
373         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
374         boolean foundVxlanTzone = false;
375         try {
376             final IpAddress hwIp = input.getIpAddress();
377             final String node_id = input.getNodeId();
378             InstanceIdentifier<TransportZones> containerPath = InstanceIdentifier.create(TransportZones.class);
379             Optional<TransportZones> tZonesOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, containerPath, dataBroker);
380             if (tZonesOptional.isPresent()) {
381                 TransportZones tZones = tZonesOptional.get();
382                 if (tZones.getTransportZone() == null || tZones.getTransportZone().isEmpty()) {
383                     LOG.error("No teps configured");
384                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No teps Configured").build());
385                     return result;
386                 }
387                 for (TransportZone tzone : tZones.getTransportZone()) {
388                     if (!(tzone.getTunnelType().equals(TunnelTypeVxlan.class)))
389                         continue;
390                     foundVxlanTzone = true;
391                     String transportZone = tzone.getZoneName();
392                     if (tzone.getSubnets() == null || tzone.getSubnets().isEmpty()) {
393                         result.set(RpcResultBuilder.<Void>failed()
394                                 .withError(RpcError.ErrorType.APPLICATION, "No subnets Configured").build());
395                         return result;
396                     }
397                     SubnetsKey subnetsKey = tzone.getSubnets().get(0).getKey();
398                     DeviceVtepsKey deviceVtepKey = new DeviceVtepsKey(hwIp, node_id);
399                     InstanceIdentifier<DeviceVteps> path = InstanceIdentifier.builder(TransportZones.class)
400                             .child(TransportZone.class, new TransportZoneKey(transportZone))
401                             .child(Subnets.class, subnetsKey).child(DeviceVteps.class, deviceVtepKey)
402                             .build();
403                     WriteTransaction t = dataBroker.newWriteOnlyTransaction();
404                     //TO DO: add retry if it fails
405
406                     t.delete(LogicalDatastoreType.CONFIGURATION, path);
407
408                     ListenableFuture<Void> futureCheck = t.submit();
409                     Futures.addCallback(futureCheck, new FutureCallback<Void>() {
410
411                         @Override public void onSuccess(Void aVoid) {
412                             result.set(RpcResultBuilder.<Void>success().build());
413                         }
414
415                         @Override public void onFailure(Throwable error) {
416                             String msg = String.format("Unable to delete HwVtep {} from datastore", node_id);
417                             LOG.error("Unable to delete HwVtep {}, {} from datastore", node_id, hwIp);
418                             result.set(RpcResultBuilder.<Void>failed()
419                                     .withError(RpcError.ErrorType.APPLICATION, msg, error).build());
420                         }
421                     });
422
423                 }
424             }
425             else {
426                 result.set(RpcResultBuilder.<Void>failed()
427                         .withError(RpcError.ErrorType.APPLICATION, "No TransportZones configured").build());
428                 return result;
429             }
430
431             if(foundVxlanTzone == false)
432                 result.set(RpcResultBuilder.<Void>failed()
433                         .withError(RpcError.ErrorType.APPLICATION, "No VxLan TransportZones configured")
434                         .build());
435
436             return result;
437         } catch (Exception e) {
438             RpcResultBuilder<java.lang.Void> resultBuilder = RpcResultBuilder.<Void>failed().
439                     withError(RpcError.ErrorType.APPLICATION, "Deleting l2 Gateway to DS Failed", e);
440             return Futures.immediateFuture(resultBuilder.build());
441         }
442     }
443
444     @Override
445     public Future<RpcResult<java.lang.Void>> addL2GwDevice(AddL2GwDeviceInput input) {
446
447         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
448         boolean foundVxlanTzone = false;
449         try {
450             final IpAddress hwIp = input.getIpAddress();
451             final String node_id = input.getNodeId();
452             //iterate through all transport zones and put TORs under vxlan
453             //if no vxlan tzone is cnfigured, return an error.
454             InstanceIdentifier<TransportZones> containerPath = InstanceIdentifier.create(TransportZones.class);
455             Optional<TransportZones> tZonesOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, containerPath,
456                     dataBroker);
457             if (tZonesOptional.isPresent()) {
458                 TransportZones tZones = tZonesOptional.get();
459                 if (tZones.getTransportZone() == null || tZones.getTransportZone().isEmpty()) {
460                     LOG.error("No transportZone configured");
461                     result.set(RpcResultBuilder.<Void>failed()
462                             .withError(RpcError.ErrorType.APPLICATION, "No transportZone Configured").build());
463                     return result;
464                 }
465                 for (TransportZone tzone : tZones.getTransportZone()) {
466                     if (!(tzone.getTunnelType().equals(TunnelTypeVxlan.class)))
467                         continue;
468                     foundVxlanTzone = true;
469                     String transportZone = tzone.getZoneName();
470                     if (tzone.getSubnets() == null || tzone.getSubnets().isEmpty()) {
471                         result.set(RpcResultBuilder.<Void>failed()
472                                 .withError(RpcError.ErrorType.APPLICATION, "No subnets Configured").build());
473                         return result;
474                     }
475                     SubnetsKey subnetsKey = tzone.getSubnets().get(0).getKey();
476                     DeviceVtepsKey deviceVtepKey = new DeviceVtepsKey(hwIp, node_id);
477                     InstanceIdentifier<DeviceVteps> path = InstanceIdentifier.builder(TransportZones.class)
478                             .child(TransportZone.class, new TransportZoneKey(transportZone))
479                             .child(Subnets.class, subnetsKey).child(DeviceVteps.class, deviceVtepKey)
480                             .build();
481                     DeviceVteps deviceVtep = new DeviceVtepsBuilder().setKey(deviceVtepKey).setIpAddress(hwIp)
482                             .setNodeId(node_id).setTopologyId(input.getTopologyId()).build();
483                     WriteTransaction t = dataBroker.newWriteOnlyTransaction();
484                     //TO DO: add retry if it fails
485                     t.put(LogicalDatastoreType.CONFIGURATION, path, deviceVtep, true);
486
487                     ListenableFuture<Void> futureCheck = t.submit();
488                     Futures.addCallback(futureCheck, new FutureCallback<Void>() {
489
490                         @Override public void onSuccess(Void aVoid) {
491                             result.set(RpcResultBuilder.<Void>success().build());
492                         }
493
494                         @Override public void onFailure(Throwable error) {
495                             String msg = String.format("Unable to write HwVtep {} to datastore", node_id);
496                             LOG.error("Unable to write HwVtep {}, {} to datastore", node_id, hwIp);
497                             result.set(RpcResultBuilder.<Void>failed()
498                                     .withError(RpcError.ErrorType.APPLICATION, msg, error).build());
499                         }
500                     });
501
502                 }
503             }
504             else {
505                 result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No TransportZones configured").build());
506                 return result;
507             }
508
509             if(foundVxlanTzone == false)
510                 result.set(RpcResultBuilder.<Void>failed()
511                         .withError(RpcError.ErrorType.APPLICATION, "No VxLan TransportZones configured")
512                         .build());
513
514             return result;
515         } catch (Exception e) {
516             RpcResultBuilder<java.lang.Void> resultBuilder = RpcResultBuilder.<Void>failed().
517                     withError(RpcError.ErrorType.APPLICATION, "Adding l2 Gateway to DS Failed", e);
518             return Futures.immediateFuture(resultBuilder.build());
519         }
520     }
521
522     @Override
523     public Future<RpcResult<java.lang.Void>> addL2GwMlagDevice(AddL2GwMlagDeviceInput input)
524     {
525
526         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
527         try {
528             final IpAddress hwIp = input.getIpAddress();
529             final List<String> node_id = input.getNodeId();
530             InstanceIdentifier<TransportZones> containerPath = InstanceIdentifier.create(TransportZones.class);
531             Optional<TransportZones> tZonesOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, containerPath, dataBroker);
532             if (tZonesOptional.isPresent()) {
533                 TransportZones tZones = tZonesOptional.get();
534                 if (tZones.getTransportZone() == null || tZones.getTransportZone().isEmpty()) {
535                     LOG.error("No teps configured");
536                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No teps Configured").build());
537                     return result;
538                 }
539                 String transportZone = tZones.getTransportZone().get(0).getZoneName();
540                 if (tZones.getTransportZone().get(0).getSubnets() == null || tZones.getTransportZone().get(0).getSubnets().isEmpty()) {
541                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No subnets Configured").build());
542                     return result;
543                 }
544                 SubnetsKey subnetsKey = tZones.getTransportZone().get(0).getSubnets().get(0).getKey();
545                 DeviceVtepsKey deviceVtepKey = new DeviceVtepsKey(hwIp, node_id.get(0));
546                 InstanceIdentifier<DeviceVteps> path =
547                         InstanceIdentifier.builder(TransportZones.class)
548                                 .child(TransportZone.class, new TransportZoneKey(transportZone))
549                                 .child(Subnets.class, subnetsKey).child(DeviceVteps.class, deviceVtepKey).build();
550                 DeviceVteps deviceVtep = new DeviceVtepsBuilder().setKey(deviceVtepKey).setIpAddress(hwIp).setNodeId(node_id.get(0)).setTopologyId(input.getTopologyId()).build();
551                 WriteTransaction t = dataBroker.newWriteOnlyTransaction();
552                 //TO DO: add retry if it fails
553                 LOG.trace("writing hWvtep{}",deviceVtep);
554                 t.put(LogicalDatastoreType.CONFIGURATION, path, deviceVtep, true);
555
556                 if(node_id.size() == 2) {
557                     LOG.trace("second node-id {}",node_id.get(1));
558                     DeviceVtepsKey deviceVtepKey2 = new DeviceVtepsKey(hwIp, node_id.get(1));
559                     InstanceIdentifier<DeviceVteps> path2 = InstanceIdentifier.builder(TransportZones.class)
560                             .child(TransportZone.class, new TransportZoneKey(transportZone))
561                             .child(Subnets.class, subnetsKey).child(DeviceVteps.class, deviceVtepKey2).build();
562                     DeviceVteps deviceVtep2 = new DeviceVtepsBuilder().setKey(deviceVtepKey2).setIpAddress(hwIp).setNodeId(node_id.get(1))
563                             .setTopologyId(input.getTopologyId()).build();
564                     //TO DO: add retry if it fails
565                     LOG.trace("writing {}",deviceVtep2);
566                     t.put(LogicalDatastoreType.CONFIGURATION, path2, deviceVtep2, true);
567                 }ListenableFuture<Void> futureCheck = t.submit();
568                 Futures.addCallback(futureCheck, new FutureCallback<Void>() {
569
570                     @Override
571                     public void onSuccess(Void aVoid) {
572                         result.set(RpcResultBuilder.<Void>success().build());
573                     }
574
575                     @Override
576                     public void onFailure(Throwable error) {
577                         String msg = String.format("Unable to write HwVtep {} to datastore", node_id);
578                         LOG.error("Unable to write HwVtep {}, {} to datastore", node_id , hwIp);
579                         result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, msg, error).build());
580                     }
581                 });
582             }
583             return result;
584         } catch (Exception e) {
585             RpcResultBuilder<java.lang.Void> resultBuilder = RpcResultBuilder.<Void>failed().
586                     withError(RpcError.ErrorType.APPLICATION, "Adding l2 Gateway to DS Failed", e);
587             return Futures.immediateFuture(resultBuilder.build());
588         }
589     }
590     @Override
591     public Future<RpcResult<Void>> deleteL2GwMlagDevice(DeleteL2GwMlagDeviceInput input) {
592
593         final SettableFuture<RpcResult<Void>> result = SettableFuture.create();
594         try {
595             final IpAddress hwIp = input.getIpAddress();
596             final List<String> node_id = input.getNodeId();
597             InstanceIdentifier<TransportZones> containerPath = InstanceIdentifier.create(TransportZones.class);
598             Optional<TransportZones> tZonesOptional = ItmUtils.read(LogicalDatastoreType.CONFIGURATION, containerPath, dataBroker);
599             if (tZonesOptional.isPresent()) {
600                 TransportZones tZones = tZonesOptional.get();
601                 if (tZones.getTransportZone() == null || tZones.getTransportZone().isEmpty()) {
602                     LOG.error("No teps configured");
603                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No teps Configured").build());
604                     return result;
605                 }
606                 String transportZone = tZones.getTransportZone().get(0).getZoneName();
607                 if (tZones.getTransportZone().get(0).getSubnets() == null || tZones.getTransportZone().get(0).getSubnets().isEmpty()) {
608                     result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, "No subnets Configured").build());
609                     return result;
610                 }
611                 SubnetsKey subnetsKey = tZones.getTransportZone().get(0).getSubnets().get(0).getKey();
612                 DeviceVtepsKey deviceVtepKey = new DeviceVtepsKey(hwIp, node_id.get(0));
613                 InstanceIdentifier<DeviceVteps> path =
614                         InstanceIdentifier.builder(TransportZones.class)
615                                 .child(TransportZone.class, new TransportZoneKey(transportZone))
616                                 .child(Subnets.class, subnetsKey).child(DeviceVteps.class,
617                                 deviceVtepKey).build();
618                 WriteTransaction t = dataBroker.newWriteOnlyTransaction();
619                 //TO DO: add retry if it fails
620                 t.delete(LogicalDatastoreType.CONFIGURATION, path);
621
622                 DeviceVtepsKey deviceVtepKey2 = new DeviceVtepsKey(hwIp, node_id.get(1));
623                 InstanceIdentifier<DeviceVteps> path2 =
624                         InstanceIdentifier.builder(TransportZones.class)
625                                 .child(TransportZone.class, new TransportZoneKey(transportZone))
626                                 .child(Subnets.class, subnetsKey).child(DeviceVteps.class,
627                                 deviceVtepKey2).build();
628                 //TO DO: add retry if it fails
629                 t.delete(LogicalDatastoreType.CONFIGURATION, path2);
630
631                 ListenableFuture<Void> futureCheck = t.submit();
632                 Futures.addCallback(futureCheck, new FutureCallback<Void>() {
633
634                     @Override
635                     public void onSuccess(Void aVoid) {
636                         result.set(RpcResultBuilder.<Void>success().build());
637                     }
638
639                     @Override
640                     public void onFailure(Throwable error) {
641                         String msg = String.format("Unable to write HwVtep {} to datastore", node_id);
642                         LOG.error("Unable to write HwVtep {}, {} to datastore", node_id , hwIp);
643                         result.set(RpcResultBuilder.<Void>failed().withError(RpcError.ErrorType.APPLICATION, msg, error).build());
644                     }
645                 });
646             }
647             return result;
648         } catch (Exception e) {
649             RpcResultBuilder<java.lang.Void> resultBuilder = RpcResultBuilder.<Void>failed().
650                     withError(RpcError.ErrorType.APPLICATION, "Deleting l2 Gateway to DS Failed", e);
651             return Futures.immediateFuture(resultBuilder.build());
652         }
653     }
654
655     @Override
656     public Future<RpcResult<IsTunnelInternalOrExternalOutput>> isTunnelInternalOrExternal(
657             IsTunnelInternalOrExternalInput input) {
658         RpcResultBuilder<IsTunnelInternalOrExternalOutput> resultBld;
659         String tunIfName = input.getTunnelInterfaceName();
660         long tunVal = 0;
661         IsTunnelInternalOrExternalOutputBuilder output = new IsTunnelInternalOrExternalOutputBuilder().setTunnelType(tunVal);
662
663         if(ItmUtils.itmCache.getInternalTunnel(tunIfName) != null) {
664             tunVal = 1;
665         } else if (ItmUtils.itmCache.getExternalTunnel(tunIfName) != null) {
666             tunVal = 2;
667         }
668         output.setTunnelType(tunVal);
669         resultBld = RpcResultBuilder.success();
670         resultBld.withResult(output.build());
671         return Futures.immediateFuture(resultBld.build());
672     }
673
674 }