get rid of mdsal.binding.dom.codec.impl
[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.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;
24 import java.util.Map;
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;
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     private Map<String, IpAddress> mapNodeRefIp = new HashMap<>();
83     private final AdapterContext adapterContext = new ConstantAdapterContext();
84
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);
91
92         // Create the binding binding normalized node codec registry
93         final BindingNormalizedNodeSerializer codecRegistry = adapterContext.currentSerializer();
94
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;
101
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,
107             Result.class);
108         if (!transformIntoNormalizedNode.isPresent()) {
109             throw new GnpyException("In GnpyResult: the Normalized Node is not present");
110         }
111         NormalizedNode<? extends PathArgument, ?> normalizedNode = transformIntoNormalizedNode.get();
112
113         if (codecRegistry.fromNormalizedNode(yangId, normalizedNode) != null) {
114             dataObject = codecRegistry.fromNormalizedNode(yangId, normalizedNode).getValue();
115         } else {
116             throw new GnpyException("In GnpyResult: the codec registry from the normalized node is null");
117         }
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!");
121         }
122         LOG.info("The response id is {}; ", responses.get(0).getResponseId());
123         this.response = responses.get(0);
124         analyzeResult();
125     }
126
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) {
133                 isFeasible = true;
134                 LOG.info("In GnpyResult: The path is feasible ");
135             }
136         }
137         return isFeasible;
138     }
139
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);
157                     }
158                 }
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();
164                 // Path metrics
165                 for (PathMetric pathMetric : pathMetricList) {
166                     String metricType = pathMetric.getMetricType().getSimpleName();
167                     BigDecimal accumulativeValue = pathMetric.getAccumulativeValue();
168                     LOG.info("Metric type {} // AccumulatriveValue {}", metricType, accumulativeValue);
169                 }
170                 // Path route objects
171                 pathRouteObjectList = pathCase.getPathProperties().getPathRouteObjects();
172                 LOG.info("in GnpyResult: finishing the computation of pathRouteObjectList");
173             }
174         }
175         return pathRouteObjectList;
176     }
177
178     public HardConstraints computeHardConstraintsFromGnpyPath(List<PathRouteObjects> pathRouteObjectList) {
179         HardConstraints hardConstraints = null;
180         // Includes the list of nodes in the GNPy computed path as constraints
181         // for the PCE
182         List<OrderedHops> orderedHopsList = new ArrayList<>();
183         int counter = 0;
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();
189                 try {
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)
196                             .build();
197                         HopType hopType = new HopTypeBuilder().setHopType(node).build();
198                         OrderedHops orderedHops = new OrderedHopsBuilder()
199                                 .setHopNumber(Uint16.valueOf(counter)).setHopType(hopType)
200                             .build();
201                         orderedHopsList.add(orderedHops);
202                         counter++;
203                     }
204                 } catch (IllegalArgumentException e) {
205                     LOG.debug(" in GnpyResult: the element {} is not a ipv4Address ", nodeIp);
206                 }
207             }
208         }
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;
213     }
214
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();
221             }
222         }
223         return null;
224     }
225
226     /**
227      * Parses the input json with concrete implementation of {@link JsonParserStream}.
228      * @param reader of the given JSON
229      * @throws Exception exception
230      */
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),
238                 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();
243         }
244         return Optional.ofNullable(result.getResult());
245     }
246
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);
251     }
252
253     /**
254      * Transforms the given input {@link NormalizedNode} into the given {@link DataObject}.
255      *
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
261      */
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);
267         } else {
268             LOG.warn("GNPy: The codecRegistry is null");
269         }
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));
278             }
279             normalizedNode = directChild.get();
280             LOG.debug("GNPy: the normalized node is {}", normalizedNode.getNodeType());
281         }
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,
285             normalizedNode);
286         if (bindingNodeEntry == null) {
287             LOG.debug("The binding Node Entry is null");
288             return Optional.empty();
289         }
290         return Optional.ofNullable((T) bindingNodeEntry.getValue());
291     }
292
293     public Response getResponse() {
294         return response;
295     }
296 }