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.gson.stream.JsonReader;
12 import java.io.ByteArrayInputStream;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.io.InputStreamReader;
16 import java.math.BigDecimal;
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
19 import java.util.Collection;
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.binding.runtime.api.BindingRuntimeContext;
29 import org.opendaylight.binding.runtime.spi.BindingRuntimeHelpers;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
31 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingCodecContext;
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.common.Uint16;
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.JSONCodecFactorySupplier;
64 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
65 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
66 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
67 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;
82 private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
84 public GnpyResult(String gnpyResponseString, GnpyTopoImpl gnpyTopo) throws GnpyException, Exception {
85 this.mapNodeRefIp = gnpyTopo.getMapNodeRefIp();
86 // Create the schema context
87 Collection<? extends YangModuleInfo> moduleInfos = Collections.singleton(BindingReflections
88 .getModuleInfo(Result.class));
89 BindingRuntimeHelpers.createEffectiveModel(moduleInfos);
91 // Create the binding binding normalized node codec registry
92 BindingRuntimeContext bindingContext =
93 BindingRuntimeHelpers.createRuntimeContext();
94 final BindingNormalizedNodeSerializer codecRegistry = new BindingCodecContext(bindingContext);
96 // Create the data object
97 QName pathQname = QName.create("gnpy:path", "2020-02-02", "result");
98 LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname, pathQname.getNamespace(),
99 pathQname.getModule());
100 YangInstanceIdentifier yangId = YangInstanceIdentifier.of(pathQname);
101 DataObject dataObject = null;
103 // Create the object response
104 InputStream streamGnpyRespnse = new ByteArrayInputStream(gnpyResponseString.getBytes(StandardCharsets.UTF_8));
105 InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse,StandardCharsets.UTF_8);
106 JsonReader jsonReader = new JsonReader(gnpyResultReader);
107 Optional<NormalizedNode<? extends PathArgument, ?>> transformIntoNormalizedNode = parseInputJSON(jsonReader,
109 if (!transformIntoNormalizedNode.isPresent()) {
110 throw new GnpyException("In GnpyResult: the Normalized Node is not present");
112 NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
114 if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
115 dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
117 throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null");
119 List<Response> responses = new ArrayList<>(((Result) dataObject).nonnullResponse().values());
120 if (responses.isEmpty()) {
121 throw new GnpyException("In GnpyResult: the response from GNpy is null!");
123 LOG.info("The response id is {}; ", responses.get(0).getResponseId());
124 this.response = responses.get(0);
128 public boolean getPathFeasibility() {
129 boolean isFeasible = false;
130 if (response != null) {
131 if (response.getResponseType() instanceof NoPathCase) {
132 LOG.info("In GnpyResult: The path is not feasible ");
133 } else if (response.getResponseType() instanceof PathCase) {
135 LOG.info("In GnpyResult: The path is feasible ");
141 public List<PathRouteObjects> analyzeResult() {
142 List<PathRouteObjects> pathRouteObjectList = null;
143 if (response != null) {
144 if (response.getResponseType() instanceof NoPathCase) {
145 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
146 String noPathType = noPathCase.getNoPath().getNoPath();
147 LOG.info("GNPy: No path - {}", noPathType);
148 if (((noPathType.equals("NO_FEASIBLE_BAUDRATE_WITH_SPACING"))
149 && (noPathType.equals("NO_FEASIBLE_MODE"))) && ((noPathType.equals("MODE_NOT_FEASIBLE"))
150 && (noPathType.equals("NO_SPECTRUM")))) {
151 Collection<PathMetric> pathMetricList = noPathCase.getNoPath()
152 .getPathProperties().nonnullPathMetric().values();
153 LOG.info("GNPy : path is not feasible : {}", noPathType);
154 for (PathMetric pathMetric : pathMetricList) {
155 String metricType = pathMetric.getMetricType().getSimpleName();
156 BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
157 LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
160 } else if (response.getResponseType() instanceof PathCase) {
161 LOG.info("GNPy : path is feasible");
162 PathCase pathCase = (PathCase) response.getResponseType();
163 Collection<PathMetric> pathMetricList = pathCase
164 .getPathProperties().nonnullPathMetric().values();
166 for (PathMetric pathMetric : pathMetricList) {
167 String metricType = pathMetric.getMetricType().getSimpleName();
168 BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
169 LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
171 // Path route objects
172 pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
173 LOG.info("in GnpyResult: finishing the computation of pathRouteObjectList");
176 return pathRouteObjectList;
179 public HardConstraints computeHardConstraintsFromGnpyPath(List<PathRouteObjects> pathRouteObjectList) {
180 HardConstraints hardConstraints = null;
181 // Includes the list of nodes in the GNPy computed path as constraints
183 List<OrderedHops> orderedHopsList = new ArrayList<>();
185 for (PathRouteObjects pathRouteObjects : pathRouteObjectList) {
186 if (pathRouteObjects.getPathRouteObject().getType() instanceof NumUnnumHop) {
187 NumUnnumHop numUnnumHop = (org.opendaylight.yang.gen.v1.gnpy.path.rev200202.explicit.route.hop.type
188 .NumUnnumHop) pathRouteObjects.getPathRouteObject().getType();
189 String nodeIp = numUnnumHop.getNumUnnumHop().getNodeId();
191 IpAddress nodeIpAddress = new IpAddress(new Ipv4Address(nodeIp));
192 // find the corresponding node-id (in ord-ntw) corresponding to nodeId (in gnpy response)
193 String nodeId = findOrdNetworkNodeId(nodeIpAddress);
194 if (nodeId != null) {
195 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017
196 .ordered.constraints.sp.hop.type.hop.type.Node node = new NodeBuilder().setNodeId(nodeId)
198 HopType hopType = new HopTypeBuilder().setHopType(node).build();
199 OrderedHops orderedHops = new OrderedHopsBuilder()
200 .setHopNumber(Uint16.valueOf(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 {
249 Collection<? extends YangModuleInfo> moduleInfos = Collections.singleton(BindingReflections
250 .getModuleInfo(objectClass));
251 return BindingRuntimeHelpers.createEffectiveModel(moduleInfos);
255 * Transforms the given input {@link NormalizedNode} into the given {@link DataObject}.
257 * @param <T> a generic
258 * @param normalizedNode a non null representation of the normalizedNode
259 * @param rootNode root node
260 * @param codecRegistry codec registry
261 * @return value of the binding Node Entry
263 @SuppressWarnings("unchecked")
264 public <T extends DataObject> Optional<T> getDataObject(@Nonnull NormalizedNode<?, ?> normalizedNode,
265 @Nonnull QName rootNode, BindingNormalizedNodeSerializer codecRegistry) {
266 if (normalizedNode != null) {
267 LOG.debug("GNPy: The codecRegistry is {}", codecRegistry);
269 LOG.warn("GNPy: The codecRegistry is null");
271 //Preconditions.checkNotNull(normalizedNode);
272 if (normalizedNode instanceof ContainerNode) {
273 YangInstanceIdentifier.PathArgument directChildIdentifier = YangInstanceIdentifier.of(rootNode)
274 .getLastPathArgument();
275 Optional<NormalizedNode<?, ?>> directChild = NormalizedNodes.getDirectChild(normalizedNode,
276 directChildIdentifier);
277 if (!directChild.isPresent()) {
278 throw new IllegalStateException(String.format("Could not get the direct child of %s", rootNode));
280 normalizedNode = directChild.get();
281 LOG.debug("GNPy: the normalized node is {}", normalizedNode.getNodeType());
283 YangInstanceIdentifier rootNodeYangInstanceIdentifier = YangInstanceIdentifier.of(rootNode);
284 LOG.debug("GNPy: the root Node Yang Instance Identifier is {}", rootNodeYangInstanceIdentifier);
285 Map.Entry<?, ?> bindingNodeEntry = codecRegistry.fromNormalizedNode(rootNodeYangInstanceIdentifier,
287 if (bindingNodeEntry == null) {
288 LOG.debug("The binding Node Entry is null");
289 return Optional.empty();
291 return Optional.ofNullable((T) bindingNodeEntry.getValue());
294 public Response getResponse() {