HONEYCOMB-83: Add Gre Feature within HC
[honeycomb.git] / v3po / v3po2vpp / src / main / java / io / fd / honeycomb / translate / v3po / interfaces / GreCustomizer.java
1 /*
2  * Copyright (c) 2016 Intel and/or its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package io.fd.honeycomb.translate.v3po.interfaces;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.google.common.net.InetAddresses;
22 import io.fd.honeycomb.translate.v3po.util.AbstractInterfaceTypeCustomizer;
23 import io.fd.honeycomb.translate.v3po.util.NamingContext;
24 import io.fd.honeycomb.translate.v3po.util.TranslateUtils;
25 import io.fd.honeycomb.translate.v3po.util.WriteTimeoutException;
26 import io.fd.honeycomb.translate.write.WriteContext;
27 import io.fd.honeycomb.translate.write.WriteFailedException;
28 import java.net.InetAddress;
29 import java.util.concurrent.CompletionStage;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.GreTunnel;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.Gre;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.openvpp.jvpp.VppBaseCallException;
38 import org.openvpp.jvpp.dto.GreAddDelTunnel;
39 import org.openvpp.jvpp.dto.GreAddDelTunnelReply;
40 import org.openvpp.jvpp.future.FutureJVpp;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class GreCustomizer extends AbstractInterfaceTypeCustomizer<Gre> {
45
46     private static final Logger LOG = LoggerFactory.getLogger(GreCustomizer.class);
47     private final NamingContext interfaceContext;
48
49     public GreCustomizer(final FutureJVpp vppApi, final NamingContext interfaceContext) {
50         super(vppApi);
51         this.interfaceContext = interfaceContext;
52     }
53
54     @Override
55     protected Class<? extends InterfaceType> getExpectedInterfaceType() {
56         return GreTunnel.class;
57     }
58
59     @Override
60     protected final void writeInterface(@Nonnull final InstanceIdentifier<Gre> id, @Nonnull final Gre dataAfter,
61                                        @Nonnull final WriteContext writeContext)
62             throws WriteFailedException {
63         final String swIfName = id.firstKeyOf(Interface.class).getName();
64         try {
65             createGreTunnel(id, swIfName, dataAfter, writeContext);
66         } catch (VppBaseCallException | IllegalInterfaceTypeException e) {
67             LOG.warn("Failed to set gre tunnel for interface: {}, gre: {}", swIfName, dataAfter, e);
68             throw new WriteFailedException.CreateFailedException(id, dataAfter, e);
69         }
70     }
71
72     @Override
73     public void updateCurrentAttributes(@Nonnull final InstanceIdentifier<Gre> id, @Nonnull final Gre dataBefore,
74                                         @Nonnull final Gre dataAfter, @Nonnull final WriteContext writeContext)
75             throws WriteFailedException.UpdateFailedException {
76         throw new WriteFailedException.UpdateFailedException(id, dataBefore, dataAfter,
77                 new UnsupportedOperationException("Gre tunnel update is not supported"));
78     }
79
80     @Override
81     public void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<Gre> id, @Nonnull final Gre dataBefore,
82                                         @Nonnull final WriteContext writeContext)
83             throws WriteFailedException {
84         final String swIfName = id.firstKeyOf(Interface.class).getName();
85         try {
86             deleteGreTunnel(id, swIfName, dataBefore, writeContext);
87         } catch (VppBaseCallException e) {
88             LOG.debug("Failed to delete gre tunnel for interface: {}, gre: {}", swIfName, dataBefore);
89             throw new WriteFailedException.DeleteFailedException(id, e);
90         }
91     }
92
93     private void createGreTunnel(final InstanceIdentifier<Gre> id, final String swIfName, final Gre gre,
94                                    final WriteContext writeContext) throws VppBaseCallException, WriteTimeoutException {
95         final byte isIpv6 = (byte) (isIpv6(gre) ? 1 : 0);
96         final InetAddress srcAddress = InetAddresses.forString(getAddressString(gre.getSrc()));
97         final InetAddress dstAddress = InetAddresses.forString(getAddressString(gre.getDst()));
98
99         int outerFibId = gre.getOuterFibId().intValue();
100
101         LOG.debug("Setting gre tunnel for interface: {}. Gre: {}", swIfName, gre);
102         final CompletionStage<GreAddDelTunnelReply> greAddDelTunnelReplyCompletionStage =
103                 getFutureJVpp().greAddDelTunnel(getGreTunnelRequest((byte) 1 /* is add */, srcAddress.getAddress(),
104                         dstAddress.getAddress(), outerFibId, isIpv6));
105
106         final GreAddDelTunnelReply reply =
107                 TranslateUtils.getReplyForWrite(greAddDelTunnelReplyCompletionStage.toCompletableFuture(), id);
108         LOG.debug("Gre tunnel set successfully for: {}, gre: {}", swIfName, gre);
109         if(interfaceContext.containsName(reply.swIfIndex, writeContext.getMappingContext())) {
110             // VPP keeps gre tunnels present even after they are delete(reserving ID for next tunnel)
111             // This may cause inconsistencies in mapping context when configuring tunnels like this:
112             // 1. Add tunnel 2. Delete tunnel 3. Read interfaces (reserved mapping e.g. gre_tunnel0 -> 6
113             // will get into mapping context) 4. Add tunnel (this will add another mapping with the same
114             // reserved ID and context is invalid)
115             // That's why a check has to be performed here removing mapping gre_tunnel0 -> 6 mapping and storing
116             // new name for that ID
117             final String formerName = interfaceContext.getName(reply.swIfIndex, writeContext.getMappingContext());
118             LOG.debug("Removing updated mapping of a gre tunnel, id: {}, former name: {}, new name: {}",
119                 reply.swIfIndex, formerName, swIfName);
120             interfaceContext.removeName(formerName, writeContext.getMappingContext());
121         }
122         // Add new interface to our interface context
123         interfaceContext.addName(reply.swIfIndex, swIfName, writeContext.getMappingContext());
124     }
125
126     private boolean isIpv6(final Gre gre) {
127         if (gre.getSrc().getIpv4Address() == null) {
128             checkArgument(gre.getDst().getIpv4Address() == null, "Inconsistent ip addresses: %s, %s", gre.getSrc(),
129                 gre.getDst());
130             return true;
131         } else {
132             checkArgument(gre.getDst().getIpv6Address() == null, "Inconsistent ip addresses: %s, %s", gre.getSrc(),
133                 gre.getDst());
134             return false;
135         }
136     }
137
138     private String getAddressString(final IpAddress addr) {
139         return addr.getIpv4Address() == null ? addr.getIpv6Address().getValue() : addr.getIpv4Address().getValue();
140     }
141
142     private void deleteGreTunnel(final InstanceIdentifier<Gre> id, final String swIfName, final Gre gre,
143                                    final WriteContext writeContext) throws VppBaseCallException, WriteTimeoutException {
144         final byte isIpv6 = (byte) (isIpv6(gre) ? 1 : 0);
145         final InetAddress srcAddress = InetAddresses.forString(getAddressString(gre.getSrc()));
146         final InetAddress dstAddress = InetAddresses.forString(getAddressString(gre.getDst()));
147
148         int outerFibId = gre.getOuterFibId().intValue();
149
150         LOG.debug("Deleting gre tunnel for interface: {}. Gre: {}", swIfName, gre);
151         final CompletionStage<GreAddDelTunnelReply> greAddDelTunnelReplyCompletionStage =
152                 getFutureJVpp().greAddDelTunnel(getGreTunnelRequest((byte) 0 /* is add */, srcAddress.getAddress(),
153                         dstAddress.getAddress(), outerFibId, isIpv6));
154
155         TranslateUtils.getReplyForWrite(greAddDelTunnelReplyCompletionStage.toCompletableFuture(), id);
156         LOG.debug("Gre tunnel deleted successfully for: {}, gre: {}", swIfName, gre);
157         // Remove interface from our interface context
158         interfaceContext.removeName(swIfName, writeContext.getMappingContext());
159     }
160
161     private static GreAddDelTunnel getGreTunnelRequest(final byte isAdd, final byte[] srcAddr, final byte[] dstAddr,
162                                                     final int outerFibId, final byte isIpv6) {
163         final GreAddDelTunnel greAddDelTunnel = new GreAddDelTunnel();
164         greAddDelTunnel.isAdd = isAdd;
165         greAddDelTunnel.srcAddress = srcAddr;
166         greAddDelTunnel.dstAddress = dstAddr;
167         greAddDelTunnel.outerFibId = outerFibId;
168         greAddDelTunnel.isIpv6 = isIpv6;
169         return greAddDelTunnel;
170     }
171 }