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.spi.BindingRuntimeHelpers;
29 import org.opendaylight.mdsal.binding.dom.adapter.AdapterContext;
30 import org.opendaylight.mdsal.binding.dom.adapter.ConstantAdapterContext;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
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<>();
83 private final AdapterContext adapterContext = new ConstantAdapterContext();
85 public GnpyResult(String gnpyResponseString, GnpyTopoImpl gnpyTopo) throws GnpyException, Exception {
86 this.mapNodeRefIp = gnpyTopo.getMapNodeRefIp();
87 // Create the schema context
88 Collection<? extends YangModuleInfo> moduleInfos = Collections.singleton(BindingReflections
89 .getModuleInfo(Result.class));
90 BindingRuntimeHelpers.createEffectiveModel(moduleInfos);
92 // Create the binding binding normalized node codec registry
93 final BindingNormalizedNodeSerializer codecRegistry = adapterContext.currentSerializer();
95 // Create the data object
96 QName pathQname = QName.create("gnpy:path", "2020-02-02", "result");
97 LOG.debug("the Qname is {} / namesapce {} ; module {}; ", pathQname, pathQname.getNamespace(),
98 pathQname.getModule());
99 YangInstanceIdentifier yangId = YangInstanceIdentifier.of(pathQname);
100 DataObject dataObject = null;
102 // Create the object response
103 InputStream streamGnpyRespnse = new ByteArrayInputStream(gnpyResponseString.getBytes(StandardCharsets.UTF_8));
104 InputStreamReader gnpyResultReader = new InputStreamReader(streamGnpyRespnse,StandardCharsets.UTF_8);
105 JsonReader jsonReader = new JsonReader(gnpyResultReader);
106 Optional<NormalizedNode<? extends PathArgument, ?>> transformIntoNormalizedNode = parseInputJSON(jsonReader,
108 if (!transformIntoNormalizedNode.isPresent()) {
109 throw new GnpyException("In GnpyResult: the Normalized Node is not present");
111 NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
113 if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
114 dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
116 throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null");
118 List<Response> responses = new ArrayList<>(((Result) dataObject).nonnullResponse().values());
119 if (responses.isEmpty()) {
120 throw new GnpyException("In GnpyResult: the response from GNpy is null!");
122 LOG.info("The response id is {}; ", responses.get(0).getResponseId());
123 this.response = responses.get(0);
127 public boolean getPathFeasibility() {
128 boolean isFeasible = false;
129 if (response != null) {
130 if (response.getResponseType() instanceof NoPathCase) {
131 LOG.info("In GnpyResult: The path is not feasible ");
132 } else if (response.getResponseType() instanceof PathCase) {
134 LOG.info("In GnpyResult: The path is feasible ");
140 public List<PathRouteObjects> analyzeResult() {
141 List<PathRouteObjects> pathRouteObjectList = null;
142 if (response != null) {
143 if (response.getResponseType() instanceof NoPathCase) {
144 NoPathCase noPathCase = (NoPathCase) response.getResponseType();
145 String noPathType = noPathCase.getNoPath().getNoPath();
146 LOG.info("GNPy: No path - {}", noPathType);
147 if (((noPathType.equals("NO_FEASIBLE_BAUDRATE_WITH_SPACING"))
148 && (noPathType.equals("NO_FEASIBLE_MODE"))) && ((noPathType.equals("MODE_NOT_FEASIBLE"))
149 && (noPathType.equals("NO_SPECTRUM")))) {
150 Collection<PathMetric> pathMetricList = noPathCase.getNoPath()
151 .getPathProperties().nonnullPathMetric().values();
152 LOG.info("GNPy : path is not feasible : {}", noPathType);
153 for (PathMetric pathMetric : pathMetricList) {
154 String metricType = pathMetric.getMetricType().getSimpleName();
155 BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
156 LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
159 } else if (response.getResponseType() instanceof PathCase) {
160 LOG.info("GNPy : path is feasible");
161 PathCase pathCase = (PathCase) response.getResponseType();
162 Collection<PathMetric> pathMetricList = pathCase
163 .getPathProperties().nonnullPathMetric().values();
165 for (PathMetric pathMetric : pathMetricList) {
166 String metricType = pathMetric.getMetricType().getSimpleName();
167 BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
168 LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
170 // Path route objects
171 pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
172 LOG.info("in GnpyResult: finishing the computation of pathRouteObjectList");
175 return pathRouteObjectList;
178 public HardConstraints computeHardConstraintsFromGnpyPath(List<PathRouteObjects> pathRouteObjectList) {
179 HardConstraints hardConstraints = null;
180 // Includes the list of nodes in the GNPy computed path as constraints
182 List<OrderedHops> orderedHopsList = new ArrayList<>();
184 for (PathRouteObjects pathRouteObjects : pathRouteObjectList) {
185 if (pathRouteObjects.getPathRouteObject().getType() instanceof NumUnnumHop) {
186 NumUnnumHop numUnnumHop = (org.opendaylight.yang.gen.v1.gnpy.path.rev200202.explicit.route.hop.type
187 .NumUnnumHop) pathRouteObjects.getPathRouteObject().getType();
188 String nodeIp = numUnnumHop.getNumUnnumHop().getNodeId();
190 IpAddress nodeIpAddress = new IpAddress(new Ipv4Address(nodeIp));
191 // find the corresponding node-id (in ord-ntw) corresponding to nodeId (in gnpy response)
192 String nodeId = findOrdNetworkNodeId(nodeIpAddress);
193 if (nodeId != null) {
194 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.routing.constraints.rev171017
195 .ordered.constraints.sp.hop.type.hop.type.Node node = new NodeBuilder().setNodeId(nodeId)
197 HopType hopType = new HopTypeBuilder().setHopType(node).build();
198 OrderedHops orderedHops = new OrderedHopsBuilder()
199 .setHopNumber(Uint16.valueOf(counter)).setHopType(hopType)
201 orderedHopsList.add(orderedHops);
204 } catch (IllegalArgumentException e) {
205 LOG.debug(" in GnpyResult: the element {} is not a ipv4Address ", nodeIp);
209 Include include = new IncludeBuilder().setOrderedHops(orderedHopsList).build();
210 General general = new GeneralBuilder().setInclude(include).build();
211 hardConstraints = new HardConstraintsBuilder().setCoRoutingOrGeneral(general).build();
212 return hardConstraints;
215 private String findOrdNetworkNodeId(IpAddress nodeIpAddress) {
216 Iterator<Map.Entry<String,IpAddress>> it = this.mapNodeRefIp.entrySet().iterator();
217 while (it.hasNext()) {
218 Entry<String, IpAddress> entry = it.next();
219 if (entry.getValue().equals(nodeIpAddress)) {
220 return entry.getKey();
227 * Parses the input json with concrete implementation of {@link JsonParserStream}.
228 * @param reader of the given JSON
229 * @throws Exception exception
231 private Optional<NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?>> parseInputJSON(JsonReader reader,
232 Class<? extends DataObject> objectClass) throws Exception {
233 NormalizedNodeResult result = new NormalizedNodeResult();
234 SchemaContext schemaContext = getSchemaContext(objectClass);
235 try (NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
236 JsonParserStream jsonParser = JsonParserStream.create(streamWriter,
237 JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02.getShared(schemaContext),
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();
244 return Optional.ofNullable(result.getResult());
247 private SchemaContext getSchemaContext(Class<? extends DataObject> objectClass) throws GnpyException, Exception {
248 Collection<? extends YangModuleInfo> moduleInfos = Collections.singleton(BindingReflections
249 .getModuleInfo(objectClass));
250 return BindingRuntimeHelpers.createEffectiveModel(moduleInfos);
254 * Transforms the given input {@link NormalizedNode} into the given {@link DataObject}.
256 * @param <T> a generic
257 * @param normalizedNode a non null representation of the normalizedNode
258 * @param rootNode root node
259 * @param codecRegistry codec registry
260 * @return value of the binding Node Entry
262 @SuppressWarnings("unchecked")
263 public <T extends DataObject> Optional<T> getDataObject(@Nonnull NormalizedNode<?, ?> normalizedNode,
264 @Nonnull QName rootNode, BindingNormalizedNodeSerializer codecRegistry) {
265 if (normalizedNode != null) {
266 LOG.debug("GNPy: The codecRegistry is {}", codecRegistry);
268 LOG.warn("GNPy: The codecRegistry is null");
270 //Preconditions.checkNotNull(normalizedNode);
271 if (normalizedNode instanceof ContainerNode) {
272 YangInstanceIdentifier.PathArgument directChildIdentifier = YangInstanceIdentifier.of(rootNode)
273 .getLastPathArgument();
274 Optional<NormalizedNode<?, ?>> directChild = NormalizedNodes.getDirectChild(normalizedNode,
275 directChildIdentifier);
276 if (!directChild.isPresent()) {
277 throw new IllegalStateException(String.format("Could not get the direct child of %s", rootNode));
279 normalizedNode = directChild.get();
280 LOG.debug("GNPy: the normalized node is {}", normalizedNode.getNodeType());
282 YangInstanceIdentifier rootNodeYangInstanceIdentifier = YangInstanceIdentifier.of(rootNode);
283 LOG.debug("GNPy: the root Node Yang Instance Identifier is {}", rootNodeYangInstanceIdentifier);
284 Map.Entry<?, ?> bindingNodeEntry = codecRegistry.fromNormalizedNode(rootNodeYangInstanceIdentifier,
286 if (bindingNodeEntry == null) {
287 LOG.debug("The binding Node Entry is null");
288 return Optional.empty();
290 return Optional.ofNullable((T) bindingNodeEntry.getValue());
293 public Response getResponse() {