f8e94d1e1012dd70988d279126a660327044b5f0
[honeycomb.git] / v3po / v3po2vpp / src / main / java / io / fd / honeycomb / translate / v3po / vppclassifier / ClassifySessionReader.java
1 /*
2  * Copyright (c) 2016 Cisco 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.vppclassifier;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 import static com.google.common.base.Preconditions.checkState;
22 import static io.fd.honeycomb.translate.v3po.interfacesstate.InterfaceUtils.printHexBinary;
23
24 import com.google.common.base.Optional;
25 import com.google.common.primitives.UnsignedInts;
26 import io.fd.honeycomb.translate.read.ReadContext;
27 import io.fd.honeycomb.translate.spi.read.ListReaderCustomizer;
28 import io.fd.honeycomb.translate.v3po.util.FutureJVppCustomizer;
29 import io.fd.honeycomb.translate.read.ReadFailedException;
30 import io.fd.honeycomb.translate.v3po.util.NamingContext;
31 import io.fd.honeycomb.translate.v3po.util.TranslateUtils;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.List;
35 import java.util.stream.Collectors;
36 import javax.annotation.Nonnull;
37 import javax.annotation.Nullable;
38 import javax.xml.bind.DatatypeConverter;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.HexString;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.OpaqueIndex;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppNode;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySession;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionKey;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTable;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableKey;
48 import org.opendaylight.yangtools.concepts.Builder;
49 import org.opendaylight.yangtools.yang.binding.DataObject;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.openvpp.jvpp.VppBaseCallException;
52 import org.openvpp.jvpp.core.dto.ClassifySessionDetails;
53 import org.openvpp.jvpp.core.dto.ClassifySessionDetailsReplyDump;
54 import org.openvpp.jvpp.core.dto.ClassifySessionDump;
55 import org.openvpp.jvpp.core.future.FutureJVppCore;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Reader customizer responsible for classify session read.<br> to VPP.<br> Equivalent to invoking {@code vppctl show
61  * class table verbose} command.
62  */
63 public class ClassifySessionReader extends FutureJVppCustomizer
64     implements ListReaderCustomizer<ClassifySession, ClassifySessionKey, ClassifySessionBuilder>, VppNodeReader {
65
66     private static final Logger LOG = LoggerFactory.getLogger(ClassifySessionReader.class);
67     static final String CACHE_KEY = ClassifySessionReader.class.getName();
68
69     private final NamingContext classifyTableContext;
70
71     public ClassifySessionReader(@Nonnull final FutureJVppCore futureJVppCore,
72                                  @Nonnull final NamingContext classifyTableContext) {
73         super(futureJVppCore);
74         this.classifyTableContext = checkNotNull(classifyTableContext, "classifyTableContext should not be null");
75     }
76
77     @Override
78     public void merge(@Nonnull final Builder<? extends DataObject> builder,
79                       @Nonnull final List<ClassifySession> readData) {
80         ((ClassifyTableBuilder) builder).setClassifySession(readData);
81     }
82
83     @Nonnull
84     @Override
85     public ClassifySessionBuilder getBuilder(@Nonnull final InstanceIdentifier<ClassifySession> id) {
86         return new ClassifySessionBuilder();
87     }
88
89     @Override
90     public void readCurrentAttributes(@Nonnull final InstanceIdentifier<ClassifySession> id,
91                                       @Nonnull final ClassifySessionBuilder builder, @Nonnull final ReadContext ctx)
92         throws ReadFailedException {
93         LOG.debug("Reading attributes for classify session: {}", id);
94
95         final ClassifySessionKey key = id.firstKeyOf(ClassifySession.class);
96         checkArgument(key != null, "could not find ClassifySession key in {}", id);
97
98         final ClassifySessionDetailsReplyDump classifySessionDump = dumpClassifySessions(id, ctx);
99         final byte[] match = DatatypeConverter.parseHexBinary(key.getMatch().getValue().replace(":", ""));
100         final Optional<ClassifySessionDetails> classifySession =
101             findClassifySessionDetailsByMatch(classifySessionDump, match);
102
103         if (classifySession.isPresent()) {
104             final ClassifySessionDetails detail = classifySession.get();
105             builder.setHitNext(readVppNode(detail.hitNextIndex, LOG));
106             if (detail.opaqueIndex != ~0) {
107                 // value is specified:
108                 builder.setOpaqueIndex(readOpaqueIndex(detail.opaqueIndex));
109             }
110             builder.setAdvance(detail.advance);
111             builder.setMatch(key.getMatch());
112
113             if (LOG.isTraceEnabled()) {
114                 LOG.trace("Attributes for classify session {} successfully read: {}", id, builder.build());
115             }
116         }
117     }
118
119     private OpaqueIndex readOpaqueIndex(final int opaqueIndex) {
120         // We first try to map the value to a vpp node, if that fails, simply wrap the u32 value
121         // TODO: HONEYCOMB-118 the approach might fail if the opaqueIndex contains small value that collides
122         // with some of the adjacent nodes
123         final VppNode node = readVppNode(opaqueIndex, LOG);
124         if (node != null) {
125             return new OpaqueIndex(node);
126         } else {
127             return new OpaqueIndex(UnsignedInts.toLong(opaqueIndex));
128         }
129     }
130
131     @Nullable
132     private ClassifySessionDetailsReplyDump dumpClassifySessions(@Nonnull final InstanceIdentifier<?> id,
133                                                                  @Nonnull final ReadContext ctx)
134         throws ReadFailedException {
135         final ClassifyTableKey tableKey = id.firstKeyOf(ClassifyTable.class);
136         checkArgument(tableKey != null, "could not find ClassifyTable key in {}", id);
137
138         final String cacheKey = CACHE_KEY + tableKey;
139
140         ClassifySessionDetailsReplyDump classifySessionDump =
141             (ClassifySessionDetailsReplyDump) ctx.getModificationCache().get(cacheKey);
142         if (classifySessionDump != null) {
143             LOG.debug("Classify sessions is present in cache: {}", cacheKey);
144             return classifySessionDump;
145         }
146
147         final String tableName = tableKey.getName();
148         checkState(classifyTableContext.containsIndex(tableName, ctx.getMappingContext()),
149             "Reading classify sessions for table {}, but table index could not be found in the classify table context",
150             tableName);
151         final int tableId = classifyTableContext.getIndex(tableName, ctx.getMappingContext());
152         LOG.debug("Dumping classify sessions for classify table id={}", tableId);
153
154         try {
155             final ClassifySessionDump dumpRequest = new ClassifySessionDump();
156             dumpRequest.tableId = tableId;
157             classifySessionDump = TranslateUtils
158                 .getReplyForRead(getFutureJVpp().classifySessionDump(dumpRequest).toCompletableFuture(), id);
159
160             // update the cache:
161             ctx.getModificationCache().put(cacheKey, classifySessionDump);
162             return classifySessionDump;
163         } catch (VppBaseCallException e) {
164             throw new ReadFailedException(id, e);
165         }
166     }
167
168     private static Optional<ClassifySessionDetails> findClassifySessionDetailsByMatch(
169         @Nullable final ClassifySessionDetailsReplyDump classifySessionDump, @Nonnull final byte[] match) {
170         if (classifySessionDump != null && classifySessionDump.classifySessionDetails != null) {
171             final List<ClassifySessionDetails> details = classifySessionDump.classifySessionDetails;
172             final List<ClassifySessionDetails> filteredSessions = details.stream()
173                 .filter(singleDetail -> Arrays.equals(singleDetail.match, match)).collect(Collectors.toList());
174             if (filteredSessions.isEmpty()) {
175                 return Optional.absent();
176             } else if (filteredSessions.size() == 1) {
177                 return Optional.of(filteredSessions.get(0));
178             } else {
179                 throw new IllegalStateException(String.format(
180                     "Found %d classify sessions witch given match. Single session expected.",
181                     filteredSessions.size()));
182             }
183         }
184         return Optional.absent();
185     }
186
187     @Nonnull
188     @Override
189     public List<ClassifySessionKey> getAllIds(@Nonnull final InstanceIdentifier<ClassifySession> id,
190                                               @Nonnull final ReadContext ctx) throws ReadFailedException {
191         LOG.debug("Reading list of keys for classify sessions: {}", id);
192
193         final ClassifySessionDetailsReplyDump classifySessionDump = dumpClassifySessions(id, ctx);
194         if (classifySessionDump != null && classifySessionDump.classifySessionDetails != null) {
195             return classifySessionDump.classifySessionDetails.stream()
196                 .map(detail -> new ClassifySessionKey(new HexString(printHexBinary(detail.match))))
197                 .collect(Collectors.toList());
198         } else {
199             return Collections.emptyList();
200         }
201     }
202 }