4aa3131b88cabc311fc42dfbde472cd86a8d1e8a
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / gnpy / GnpyResult.java
1 /*
2  * Copyright © 2018 Orange, Inc. 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
9 package org.opendaylight.transportpce.pce.gnpy;
10
11 import com.google.common.base.Preconditions;
12 import com.google.gson.stream.JsonReader;
13
14 import java.io.ByteArrayInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InputStreamReader;
18 import java.math.BigDecimal;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Optional;
24
25 import javassist.ClassPool;
26
27 import javax.annotation.Nonnull;
28
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
30 import org.opendaylight.mdsal.binding.dom.codec.gen.impl.StreamWriterGenerator;
31 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
32 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
33 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
34 import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
35 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
36 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.Result;
37 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.explicit.route.hop.type.num.unnum.hop.NumUnnumHop;
38 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.generic.path.properties.path.properties.PathMetric;
39 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.generic.path.properties.path.properties.PathRouteObjects;
40 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.result.Response;
41 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.result.response.response.type.NoPathCase;
42 import org.opendaylight.yang.gen.v1.gnpy.path.rev190502.result.response.response.type.PathCase;
43 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.General;
44 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.GeneralBuilder;
45 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.Include;
46 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.IncludeBuilder;
47 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.include_.OrderedHops;
48 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.include_.OrderedHopsBuilder;
49 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.HopType;
50 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.HopTypeBuilder;
51 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.hop.type.hop.type.NodeBuilder;
52 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.routing.constraints.sp.HardConstraints;
53 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.routing.constraints.sp.HardConstraintsBuilder;
54 import org.opendaylight.yangtools.yang.binding.DataObject;
55 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
59 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
63 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
64 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
65 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Class for analyzing the result sent by GNPy.
73  *
74  * @author Ahmed Triki ( ahmed.triki@orange.com )
75  *
76  */
77
78 public class GnpyResult {
79
80     private static final Logger LOG = LoggerFactory.getLogger(GnpyResult.class);
81     private Response response = null;
82
83     public GnpyResult(String gnpyResponseString) throws Exception {
84
85         // Create the schema context
86         final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
87         Iterable<? extends YangModuleInfo> moduleInfos;
88         moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(Result.class));
89         moduleContext.addModuleInfos(moduleInfos);
90         SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
91
92         // Create the binding binding normalized node codec registry
93         BindingRuntimeContext bindingRuntimeContext = BindingRuntimeContext.create(moduleContext, schemaContext);
94         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(
95                 StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault())));
96         codecRegistry.onBindingRuntimeContextUpdated(bindingRuntimeContext);
97
98         // Create the data object
99         QName pathQname = QName.create("gnpy:path", "2019-05-02", "result");
100         LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname.toString(), pathQname.getNamespace(),
101                 pathQname.getModule());
102         YangInstanceIdentifier yangId = YangInstanceIdentifier.of(pathQname);
103         DataObject dataObject = null;
104         //Create the object response
105         //Create JsonReader from String
106         InputStream streamGnpyRespnse = new ByteArrayInputStream(gnpyResponseString.getBytes(StandardCharsets.UTF_8));
107         InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse);
108         JsonReader jsonReader = new JsonReader(gnpyResultReader);
109         Optional<NormalizedNode<? extends PathArgument, ?>> transformIntoNormalizedNode = parseInputJSON(jsonReader,
110                 Result.class);
111         NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
112         if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
113             LOG.debug("The key of the generated object",
114                     codecRegistry.fromNormalizedNode(yangId, normalizedNode).getKey());
115             dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
116         } else {
117             LOG.warn("The codec registry from the normalized node is null!");
118         }
119         List<Response> responses = null;
120         responses = ((Result) dataObject).getResponse();
121         if (responses != null) {
122             LOG.info("The response id is {}; ", responses.get(0).getResponseId());
123         } else {
124             LOG.warn("The response is null!");
125         }
126         this.response = responses.get(0);
127         analyzeResult();
128     }
129
130     public boolean getPathFeasibility() {
131         boolean isFeasible = false;
132         if (response != null) {
133             if (response.getResponseType() instanceof NoPathCase) {
134                 isFeasible = false;
135                 LOG.info("The path is not feasible ");
136             } else if (response.getResponseType() instanceof PathCase) {
137                 isFeasible = true;
138                 LOG.info("The path is feasible ");
139             }
140         }
141         return isFeasible;
142     }
143
144     public void analyzeResult() {
145         if (response != null) {
146             Long responseId = response.getResponseId();
147             LOG.info("Response-Id {}", responseId);
148             if (response.getResponseType() instanceof NoPathCase) {
149                 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
150                 String noPathType = noPathCase.getNoPath().getNoPath();
151                 LOG.info("GNPy: No path - {}",noPathType);
152                 if (((noPathType.equals("NO_FEASIBLE_BAUDRATE_WITH_SPACING"))
153                         && (noPathType.equals("NO_FEASIBLE_MODE"))) && ((noPathType.equals("MODE_NOT_FEASIBLE"))
154                         && (noPathType.equals("NO_SPECTRUM")))) {
155                     List<PathMetric> pathMetricList = noPathCase.getNoPath().getPathProperties().getPathMetric();
156                     LOG.info("GNPy : path is not feasible : {}", noPathType);
157                     for (PathMetric pathMetric : pathMetricList) {
158                         String metricType = pathMetric.getMetricType().getSimpleName();
159                         BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
160                         LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
161                     }
162                 }
163             } else if (response.getResponseType() instanceof PathCase) {
164                 LOG.info("GNPy : path is feasible");
165                 PathCase pathCase = (PathCase) response.getResponseType();
166                 List<PathMetric> pathMetricList = pathCase.getPathProperties().getPathMetric();
167                 for (PathMetric pathMetric : pathMetricList) {
168                     String metricType = pathMetric.getMetricType().getSimpleName();
169                     BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
170                     LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
171                 }
172             }
173         }
174     }
175
176     public HardConstraints analyzeGnpyPath() {
177         HardConstraints hardConstraints = null;
178         if (response != null) {
179             Long responseId = response.getResponseId();
180             LOG.info("Response-Id {}", responseId);
181             if (response.getResponseType() instanceof NoPathCase) {
182                 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
183                 LOG.info("No path feasible {}", noPathCase.toString());
184             } else if (response.getResponseType() instanceof PathCase) {
185                 PathCase pathCase = (PathCase) response.getResponseType();
186                 List<PathMetric> pathMetricList = pathCase.getPathProperties().getPathMetric();
187                 for (PathMetric pathMetric : pathMetricList) {
188                     String metricType = pathMetric.getMetricType().getSimpleName();
189                     BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
190                     LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
191                 }
192
193                 // Includes the list of nodes in the GNPy computed path as constraints for the PCE
194                 List<OrderedHops> orderedHopsList = null;
195                 List<PathRouteObjects> pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
196                 int counter = 0;
197                 for (PathRouteObjects pathRouteObjects : pathRouteObjectList) {
198                     if (pathRouteObjects.getPathRouteObject().getType() instanceof NumUnnumHop) {
199                         NumUnnumHop numUnnumHop = (NumUnnumHop) pathRouteObjects.getPathRouteObject().getType();
200                         String nodeId = numUnnumHop.getNodeId();
201                         org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017
202                                 .ordered.constraints.sp.hop.type.hop.type.Node node = new NodeBuilder()
203                                 .setNodeId(nodeId).build();
204                         HopType hopType = new HopTypeBuilder().setHopType(node).build();
205                         OrderedHops orderedHops = new OrderedHopsBuilder().setHopNumber(counter).setHopType(hopType)
206                                 .build();
207                         LOG.info("- gnpyResult class : Hard Constraint: {} // - Hop Node {}", counter, nodeId);
208                         orderedHopsList.add(orderedHops);
209                         counter++;
210                     }
211                 }
212                 Include include = new IncludeBuilder().setOrderedHops(orderedHopsList).build();
213                 General general = new GeneralBuilder().setInclude(include).build();
214                 hardConstraints = new HardConstraintsBuilder().setCoRoutingOrGeneral(general).build();
215             }
216         }
217         return hardConstraints;
218     }
219
220     /**
221      * Parses the input json with concrete implementation of
222      * {@link JsonParserStream}.
223      *
224      * @param reader
225      *            of the given JSON
226      * @throws Exception
227      *
228      */
229     private Optional<NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?>> parseInputJSON(JsonReader reader,
230             Class<? extends DataObject> objectClass) throws Exception {
231         NormalizedNodeResult result = new NormalizedNodeResult();
232         SchemaContext schemaContext = getSchemaContext(objectClass);
233         try (NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
234                 JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, schemaContext);) {
235             LOG.debug("GNPy: the path to the reader {}", reader.getPath());
236             LOG.debug("GNPy: the reader {}", reader.toString());
237             LOG.debug("GNPy: the jsonParser class {} // jsonParser to string {}", jsonParser.getClass(),
238                     jsonParser.toString());
239             jsonParser.parse(reader);
240         } catch (IOException e) {
241             LOG.warn("GNPy: exception {} occured during parsing Json input stream", e.getMessage());
242             return Optional.empty();
243         }
244         return Optional.ofNullable(result.getResult());
245     }
246
247     private SchemaContext getSchemaContext(Class<? extends DataObject> objectClass) throws Exception {
248         final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
249         Iterable<? extends YangModuleInfo> moduleInfos;
250         SchemaContext schemaContext = null;
251         moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(objectClass));
252         moduleContext.addModuleInfos(moduleInfos);
253         schemaContext = moduleContext.tryToCreateSchemaContext().get();
254         return schemaContext;
255     }
256
257     /**
258      * Transforms the given input {@link NormalizedNode} into the given
259      * {@link DataObject}.
260      *
261      * @param normalizedNode
262      *            normalized node you want to convert
263      * @param rootNode
264      *            {@link QName} of converted normalized node root
265      *
266      *            <p>
267      *            The input object should be {@link ContainerNode}
268      *            </p>
269      */
270     public <T extends DataObject> Optional<T> getDataObject(@Nonnull NormalizedNode<?, ?> normalizedNode,
271             @Nonnull QName rootNode, BindingNormalizedNodeSerializer codecRegistry) {
272         if (normalizedNode != null) {
273             LOG.debug("GNPy: The codecRegistry is ", codecRegistry.toString());
274         } else {
275             LOG.warn("GNPy: The codecRegistry is null");
276         }
277         Preconditions.checkNotNull(normalizedNode);
278         if (normalizedNode instanceof ContainerNode) {
279             YangInstanceIdentifier.PathArgument directChildIdentifier = YangInstanceIdentifier.of(rootNode)
280                     .getLastPathArgument();
281             Optional<NormalizedNode<?, ?>> directChild = NormalizedNodes.getDirectChild(normalizedNode,
282                     directChildIdentifier);
283             if (!directChild.isPresent()) {
284                 throw new IllegalStateException(String.format("Could not get the direct child of %s", rootNode));
285             }
286             normalizedNode = directChild.get();
287             LOG.debug("GNPy: the normalized node is ", normalizedNode.getNodeType());
288         }
289         YangInstanceIdentifier rootNodeYangInstanceIdentifier = YangInstanceIdentifier.of(rootNode);
290         LOG.debug("GNPy: the root Node Yang Instance Identifier is ", rootNodeYangInstanceIdentifier.toString());
291         Map.Entry<?, ?> bindingNodeEntry = codecRegistry.fromNormalizedNode(rootNodeYangInstanceIdentifier,
292                 normalizedNode);
293         if (bindingNodeEntry == null) {
294             LOG.debug("The binding Node Entry is null");
295             return Optional.empty();
296         }
297         return Optional.ofNullable((T) bindingNodeEntry.getValue());
298     }
299
300     public Response getResponse() {
301         return response;
302     }
303 }