2 * Copyright © 2018 Orange, Inc. and others. All rights reserved.
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
9 package org.opendaylight.transportpce.pce.gnpy;
11 import com.google.common.base.Preconditions;
12 import com.google.gson.stream.JsonReader;
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;
23 import java.util.Optional;
25 import javassist.ClassPool;
27 import javax.annotation.Nonnull;
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;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * Class for analyzing the result sent by GNPy.
74 * @author Ahmed Triki ( ahmed.triki@orange.com )
78 public class GnpyResult {
80 private static final Logger LOG = LoggerFactory.getLogger(GnpyResult.class);
81 private Response response = null;
83 public GnpyResult(String gnpyResponseString) throws Exception {
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();
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);
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,
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();
117 LOG.warn("The codec registry from the normalized node is null!");
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());
124 LOG.warn("The response is null!");
126 this.response = responses.get(0);
130 public boolean getPathFeasibility() {
131 boolean isFeasible = false;
132 if (response != null) {
133 if (response.getResponseType() instanceof NoPathCase) {
135 LOG.info("The path is not feasible ");
136 } else if (response.getResponseType() instanceof PathCase) {
138 LOG.info("The path is feasible ");
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);
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);
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);
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();
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)
206 LOG.info("- gnpyResult class : Hard Constraint: {} // - Hop Node {}", counter, nodeId);
207 orderedHopsList.add(orderedHops);
211 Include include = new IncludeBuilder().setOrderedHops(orderedHopsList).build();
212 General general = new GeneralBuilder().setInclude(include).build();
213 hardConstraints = new HardConstraintsBuilder().setCoRoutingOrGeneral(general).build();
216 return hardConstraints;
220 * Parses the input json with concrete implementation of
221 * {@link JsonParserStream}.
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();
243 return Optional.ofNullable(result.getResult());
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;
257 * Transforms the given input {@link NormalizedNode} into the given
258 * {@link DataObject}.
260 * @param normalizedNode
261 * normalized node you want to convert
263 * {@link QName} of converted normalized node root
266 * The input object should be {@link ContainerNode}
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());
274 LOG.warn("GNPy: The codecRegistry is null");
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));
285 normalizedNode = directChild.get();
286 LOG.debug("GNPy: the normalized node is ", normalizedNode.getNodeType());
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,
292 if (bindingNodeEntry == null) {
293 LOG.debug("The binding Node Entry is null");
294 return Optional.empty();
296 return Optional.ofNullable((T) bindingNodeEntry.getValue());
299 public Response getResponse() {