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;
13 import java.io.ByteArrayInputStream;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.math.BigDecimal;
18 import java.nio.charset.StandardCharsets;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import javax.annotation.Nonnull;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
29 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
30 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
31 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.Result;
34 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.explicit.route.hop.type.NumUnnumHop;
35 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.generic.path.properties.path.properties.PathMetric;
36 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.generic.path.properties.path.properties.PathRouteObjects;
37 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.result.Response;
38 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.result.response.response.type.NoPathCase;
39 import org.opendaylight.yang.gen.v1.gnpy.path.rev200202.result.response.response.type.PathCase;
40 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.General;
41 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.GeneralBuilder;
42 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.Include;
43 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.IncludeBuilder;
44 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.include_.OrderedHops;
45 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.constraints.sp.co.routing.or.general.general.include_.OrderedHopsBuilder;
46 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.HopType;
47 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.HopTypeBuilder;
48 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.ordered.constraints.sp.hop.type.hop.type.NodeBuilder;
49 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.routing.constraints.sp.HardConstraints;
50 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017.routing.constraints.sp.HardConstraintsBuilder;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
53 import org.opendaylight.yangtools.yang.binding.DataObject;
54 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
61 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
62 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
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 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * Class for analyzing the result sent by GNPy.
73 * @author Ahmed Triki ( ahmed.triki@orange.com )
77 public class GnpyResult {
79 private static final Logger LOG = LoggerFactory.getLogger(GnpyResult.class);
80 private Response response = null;
81 private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
83 public GnpyResult(String gnpyResponseString, GnpyTopoImpl gnpyTopo) throws GnpyException, Exception {
84 this.mapNodeRefIp = gnpyTopo.getMapNodeRefIp();
85 // Create the schema context
86 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
87 Iterable<? extends YangModuleInfo> moduleInfos;
89 moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(Result.class));
90 moduleContext.addModuleInfos(moduleInfos);
91 SchemaContext schemaContext = moduleContext.tryToCreateSchemaContext().get();
93 // Create the binding binding normalized node codec registry
94 BindingRuntimeContext bindingRuntimeContext = BindingRuntimeContext.create(moduleContext, schemaContext);
95 final BindingNormalizedNodeCodecRegistry codecRegistry =
96 new BindingNormalizedNodeCodecRegistry(bindingRuntimeContext);
98 // Create the data object
99 QName pathQname = QName.create("gnpy:path", "2020-02-02", "result");
100 LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname, pathQname.getNamespace(),
101 pathQname.getModule());
102 YangInstanceIdentifier yangId = YangInstanceIdentifier.of(pathQname);
103 DataObject dataObject = null;
105 // Create the object response
106 InputStream streamGnpyRespnse = new ByteArrayInputStream(gnpyResponseString.getBytes(StandardCharsets.UTF_8));
107 InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse,StandardCharsets.UTF_8);
108 JsonReader jsonReader = new JsonReader(gnpyResultReader);
109 Optional<NormalizedNode<? extends PathArgument, ?>> transformIntoNormalizedNode = parseInputJSON(jsonReader,
111 if (!transformIntoNormalizedNode.isPresent()) {
112 throw new GnpyException("In GnpyResult: the Normalized Node is not present");
114 NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
116 if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
117 dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
119 throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null");
121 List<Response> responses = null;
122 responses = ((Result) dataObject).getResponse();
123 if (responses == null) {
124 throw new GnpyException("In GnpyResult: the response from GNpy is null!");
126 LOG.info("The response id is {}; ", responses.get(0).getResponseId());
127 this.response = responses.get(0);
131 public boolean getPathFeasibility() {
132 boolean isFeasible = false;
133 if (response != null) {
134 if (response.getResponseType() instanceof NoPathCase) {
135 LOG.info("In GnpyResult: The path is not feasible ");
136 } else if (response.getResponseType() instanceof PathCase) {
138 LOG.info("In GnpyResult: The path is feasible ");
144 public List<PathRouteObjects> analyzeResult() {
145 List<PathRouteObjects> pathRouteObjectList = null;
146 if (response != null) {
147 if (response.getResponseType() instanceof NoPathCase) {
148 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
149 String noPathType = noPathCase.getNoPath().getNoPath();
150 LOG.info("GNPy: No path - {}", noPathType);
151 if (((noPathType.equals("NO_FEASIBLE_BAUDRATE_WITH_SPACING"))
152 && (noPathType.equals("NO_FEASIBLE_MODE"))) && ((noPathType.equals("MODE_NOT_FEASIBLE"))
153 && (noPathType.equals("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();
167 for (PathMetric pathMetric : pathMetricList) {
168 String metricType = pathMetric.getMetricType().getSimpleName();
169 BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
170 LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
172 // Path route objects
173 pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
174 LOG.info("in GnpyResult: finishing the computation of pathRouteObjectList");
177 return pathRouteObjectList;
180 public HardConstraints computeHardConstraintsFromGnpyPath(List<PathRouteObjects> pathRouteObjectList) {
181 HardConstraints hardConstraints = null;
182 // Includes the list of nodes in the GNPy computed path as constraints
184 List<OrderedHops> orderedHopsList = new ArrayList<>();
186 for (PathRouteObjects pathRouteObjects : pathRouteObjectList) {
187 if (pathRouteObjects.getPathRouteObject().getType() instanceof NumUnnumHop) {
188 NumUnnumHop numUnnumHop = (org.opendaylight.yang.gen.v1.gnpy.path.rev200202.explicit.route.hop.type
189 .NumUnnumHop) pathRouteObjects.getPathRouteObject().getType();
190 String nodeIp = numUnnumHop.getNumUnnumHop().getNodeId();
192 IpAddress nodeIpAddress = new IpAddress(new Ipv4Address(nodeIp));
193 // find the corresponding node-id (in ord-ntw) corresponding to nodeId (in gnpy response)
194 String nodeId = findOrdNetworkNodeId(nodeIpAddress);
195 if (nodeId != null) {
196 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017
197 .ordered.constraints.sp.hop.type.hop.type.Node node = new NodeBuilder().setNodeId(nodeId)
199 HopType hopType = new HopTypeBuilder().setHopType(node).build();
200 OrderedHops orderedHops = new OrderedHopsBuilder().setHopNumber(counter).setHopType(hopType)
202 orderedHopsList.add(orderedHops);
205 } catch (IllegalArgumentException e) {
206 LOG.debug(" in GnpyResult: the element {} is not a ipv4Address ", nodeIp);
210 Include include = new IncludeBuilder().setOrderedHops(orderedHopsList).build();
211 General general = new GeneralBuilder().setInclude(include).build();
212 hardConstraints = new HardConstraintsBuilder().setCoRoutingOrGeneral(general).build();
213 return hardConstraints;
216 private String findOrdNetworkNodeId(IpAddress nodeIpAddress) {
217 Iterator<Map.Entry<String,IpAddress>> it = this.mapNodeRefIp.entrySet().iterator();
218 while (it.hasNext()) {
219 Entry<String, IpAddress> entry = it.next();
220 if (entry.getValue().equals(nodeIpAddress)) {
221 return entry.getKey();
228 * Parses the input json with concrete implementation of {@link JsonParserStream}.
229 * @param reader of the given JSON
230 * @throws Exception exception
232 private Optional<NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?>> parseInputJSON(JsonReader reader,
233 Class<? extends DataObject> objectClass) throws Exception {
234 NormalizedNodeResult result = new NormalizedNodeResult();
235 SchemaContext schemaContext = getSchemaContext(objectClass);
236 try (NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
237 JsonParserStream jsonParser = JsonParserStream.create(streamWriter,
238 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
240 jsonParser.parse(reader);
241 } catch (IOException e) {
242 LOG.warn("GNPy: exception {} occured during parsing Json input stream", e.getMessage());
243 return Optional.empty();
245 return Optional.ofNullable(result.getResult());
248 private SchemaContext getSchemaContext(Class<? extends DataObject> objectClass) throws GnpyException, Exception {
250 final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
251 Iterable<? extends YangModuleInfo> moduleInfos;
252 SchemaContext schemaContext = null;
253 moduleInfos = Collections.singleton(BindingReflections.getModuleInfo(objectClass));
254 moduleContext.addModuleInfos(moduleInfos);
255 schemaContext = moduleContext.tryToCreateSchemaContext().get();
256 return schemaContext;
260 * Transforms the given input {@link NormalizedNode} into the given {@link DataObject}.
262 * @param <T> a generic
263 * @param normalizedNode a non null representation of the normalizedNode
264 * @param rootNode root node
265 * @param codecRegistry codec registry
266 * @return value of the binding Node Entry
268 @SuppressWarnings("unchecked")
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);
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);
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() {