add gnpy results to pce:path-computation-request
[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 == "NO_FEASIBLE_BAUDRATE_WITH_SPACING") && (noPathType == "NO_FEASIBLE_MODE"))
153                         && ((noPathType ==  "MODE_NOT_FEASIBLE") && (noPathType == "NO_SPECTRUM"))) {
154                     List<PathMetric> pathMetricList = noPathCase.getNoPath().getPathProperties().getPathMetric();
155                     LOG.info("GNPy : path is not feasible : {}", noPathType);
156                     for (PathMetric pathMetric : pathMetricList) {
157                         String metricType = pathMetric.getMetricType().getSimpleName();
158                         BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
159                         LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
160                     }
161                 }
162             } else if (response.getResponseType() instanceof PathCase) {
163                 LOG.info("GNPy : path is feasible");
164                 PathCase pathCase = (PathCase) response.getResponseType();
165                 List<PathMetric> pathMetricList = pathCase.getPathProperties().getPathMetric();
166                 for (PathMetric pathMetric : pathMetricList) {
167                     String metricType = pathMetric.getMetricType().getSimpleName();
168                     BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
169                     LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
170                 }
171             }
172         }
173     }
174
175     public HardConstraints analyzeGnpyPath() {
176         HardConstraints hardConstraints = null;
177         if (response != null) {
178             Long responseId = response.getResponseId();
179             LOG.info("Response-Id {}", responseId);
180             if (response.getResponseType() instanceof NoPathCase) {
181                 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
182                 LOG.info("No path feasible {}", noPathCase.toString());
183             } else if (response.getResponseType() instanceof PathCase) {
184                 PathCase pathCase = (PathCase) response.getResponseType();
185                 List<PathMetric> pathMetricList = pathCase.getPathProperties().getPathMetric();
186                 for (PathMetric pathMetric : pathMetricList) {
187                     String metricType = pathMetric.getMetricType().getSimpleName();
188                     BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
189                     LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
190                 }
191
192                 // Includes the list of nodes in the GNPy computed path as constraints for the PCE
193                 List<OrderedHops> orderedHopsList = null;
194                 List<PathRouteObjects> pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
195                 int counter = 0;
196                 for (PathRouteObjects pathRouteObjects : pathRouteObjectList) {
197                     if (pathRouteObjects.getPathRouteObject().getType() instanceof NumUnnumHop) {
198                         NumUnnumHop numUnnumHop = (NumUnnumHop) pathRouteObjects.getPathRouteObject().getType();
199                         String nodeId = numUnnumHop.getNodeId();
200                         org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017
201                                 .ordered.constraints.sp.hop.type.hop.type.Node node = new NodeBuilder()
202                                 .setNodeId(nodeId).build();
203                         HopType hopType = new HopTypeBuilder().setHopType(node).build();
204                         OrderedHops orderedHops = new OrderedHopsBuilder().setHopNumber(counter).setHopType(hopType)
205                                 .build();
206                         LOG.info("- gnpyResult class : Hard Constraint: {} // - Hop Node {}", counter, nodeId);
207                         orderedHopsList.add(orderedHops);
208                         counter++;
209                     }
210                 }
211                 Include include = new IncludeBuilder().setOrderedHops(orderedHopsList).build();
212                 General general = new GeneralBuilder().setInclude(include).build();
213                 hardConstraints = new HardConstraintsBuilder().setCoRoutingOrGeneral(general).build();
214             }
215         }
216         return hardConstraints;
217     }
218
219     /**
220      * Parses the input json with concrete implementation of
221      * {@link JsonParserStream}.
222      *
223      * @param reader
224      *            of the given JSON
225      * @throws Exception
226      *
227      */
228     private Optional<NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?>> parseInputJSON(JsonReader reader,
229             Class<? extends DataObject> objectClass) throws Exception {
230         NormalizedNodeResult result = new NormalizedNodeResult();
231         SchemaContext schemaContext = getSchemaContext(objectClass);
232         try (NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
233                 JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, schemaContext);) {
234             LOG.debug("GNPy: the path to the reader {}", reader.getPath());
235             LOG.debug("GNPy: the reader {}", reader.toString());
236             LOG.debug("GNPy: the jsonParser class {} // jsonParser to string {}", jsonParser.getClass(),
237                     jsonParser.toString());
238             jsonParser.parse(reader);
239         } catch (IOException e) {
240             LOG.warn("GNPy: exception {} occured during parsing Json input stream", e.getMessage());
241             return Optional.empty();
242         }
243         return Optional.ofNullable(result.getResult());
244     }
245
246     private SchemaContext getSchemaContext(Class<? extends DataObject> objectClass) throws Exception {
247         final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
248         Iterable<? extends YangModuleInfo> moduleInfos;
249         SchemaContext schemaContext = null;
250         moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(objectClass));
251         moduleContext.addModuleInfos(moduleInfos);
252         schemaContext = moduleContext.tryToCreateSchemaContext().get();
253         return schemaContext;
254     }
255
256     /**
257      * Transforms the given input {@link NormalizedNode} into the given
258      * {@link DataObject}.
259      *
260      * @param normalizedNode
261      *            normalized node you want to convert
262      * @param rootNode
263      *            {@link QName} of converted normalized node root
264      *
265      *            <p>
266      *            The input object should be {@link ContainerNode}
267      *            </p>
268      */
269     public <T extends DataObject> Optional<T> getDataObject(@Nonnull NormalizedNode<?, ?> normalizedNode,
270             @Nonnull QName rootNode, BindingNormalizedNodeSerializer codecRegistry) {
271         if (normalizedNode != null) {
272             LOG.debug("GNPy: The codecRegistry is ", codecRegistry.toString());
273         } else {
274             LOG.warn("GNPy: The codecRegistry is null");
275         }
276         Preconditions.checkNotNull(normalizedNode);
277         if (normalizedNode instanceof ContainerNode) {
278             YangInstanceIdentifier.PathArgument directChildIdentifier = YangInstanceIdentifier.of(rootNode)
279                     .getLastPathArgument();
280             Optional<NormalizedNode<?, ?>> directChild = NormalizedNodes.getDirectChild(normalizedNode,
281                     directChildIdentifier);
282             if (!directChild.isPresent()) {
283                 throw new IllegalStateException(String.format("Could not get the direct child of %s", rootNode));
284             }
285             normalizedNode = directChild.get();
286             LOG.debug("GNPy: the normalized node is ", normalizedNode.getNodeType());
287         }
288         YangInstanceIdentifier rootNodeYangInstanceIdentifier = YangInstanceIdentifier.of(rootNode);
289         LOG.debug("GNPy: the root Node Yang Instance Identifier is ", rootNodeYangInstanceIdentifier.toString());
290         Map.Entry<?, ?> bindingNodeEntry = codecRegistry.fromNormalizedNode(rootNodeYangInstanceIdentifier,
291                 normalizedNode);
292         if (bindingNodeEntry == null) {
293             LOG.debug("The binding Node Entry is null");
294             return Optional.empty();
295         }
296         return Optional.ofNullable((T) bindingNodeEntry.getValue());
297     }
298
299     public Response getResponse() {
300         return response;
301     }
302 }