Fix few code issues
[transportpce.git] / pce / src / main / java / org / opendaylight / transportpce / pce / gnpy / GnpyServiceImpl.java
1 /*
2  * Copyright © 2019 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.common.collect.HashBasedTable;
12 import com.google.common.collect.Table;
13 import java.math.BigDecimal;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Optional;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.transportpce.common.ServiceRateConstant;
25 import org.opendaylight.transportpce.common.fixedflex.GridConstant;
26 import org.opendaylight.transportpce.common.fixedflex.GridUtils;
27 import org.opendaylight.transportpce.pce.constraints.PceConstraints;
28 import org.opendaylight.transportpce.pce.constraints.PceConstraints.ResourcePair;
29 import org.opendaylight.transportpce.pce.gnpy.utils.AToZComparator;
30 import org.opendaylight.transportpce.pce.gnpy.utils.ZToAComparator;
31 import org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev220221.topo.Elements;
32 import org.opendaylight.yang.gen.v1.gnpy.gnpy.network.topology.rev220221.topo.ElementsKey;
33 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.RouteIncludeEro;
34 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.TeHopType;
35 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.TePathDisjointness;
36 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.common.constraints_config.TeBandwidth;
37 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.common.constraints_config.TeBandwidthBuilder;
38 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.explicit.route.hop.Type;
39 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.explicit.route.hop.type.NumUnnumHopBuilder;
40 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.explicit.route.hop.type.num.unnum.hop.NumUnnumHop;
41 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.generic.path.constraints.PathConstraints;
42 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.generic.path.constraints.PathConstraintsBuilder;
43 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.gnpy.specific.parameters.EffectiveFreqSlot;
44 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.gnpy.specific.parameters.EffectiveFreqSlotBuilder;
45 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.path.route.objects.ExplicitRouteObjects;
46 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.path.route.objects.ExplicitRouteObjectsBuilder;
47 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.path.route.objects.explicit.route.objects.RouteObjectIncludeExclude;
48 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.path.route.objects.explicit.route.objects.RouteObjectIncludeExcludeBuilder;
49 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.path.route.objects.explicit.route.objects.RouteObjectIncludeExcludeKey;
50 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.service.PathRequest;
51 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.service.PathRequestBuilder;
52 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.service.PathRequestKey;
53 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.synchronization.info.Synchronization;
54 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.synchronization.info.SynchronizationBuilder;
55 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.synchronization.info.synchronization.Svec;
56 import org.opendaylight.yang.gen.v1.gnpy.path.rev220221.synchronization.info.synchronization.SvecBuilder;
57 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.pce.rev220118.PathComputationRequestInput;
58 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.optical.channel.types.rev211210.FrequencyTHz;
59 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.types.rev181019.ModulationFormat;
60 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.AToZDirection;
61 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ZToADirection;
62 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.atoz.direction.AToZ;
63 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ztoa.direction.ZToA;
64 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.pce.resource.resource.Resource;
65 import org.opendaylight.yangtools.yang.common.Uint32;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69
70 /**
71  * Class to create the service corresponding to GNPy requirements.
72  *
73  * @author Ahmed Triki ( ahmed.triki@orange.com )
74  *
75  */
76
77 public class GnpyServiceImpl {
78     private static final Logger LOG = LoggerFactory.getLogger(GnpyServiceImpl.class);
79
80     private Map<PathRequestKey, PathRequest> pathRequest = new HashMap<>();
81     private List<Synchronization> synchronization = new ArrayList<>();
82     private Map<String, String> mapDisgNodeRefNode = new HashMap<>();
83     private Map<String, List<String>> mapLinkFiber = new HashMap<>();
84     private List<String> trxList = new ArrayList<>();
85     private Map<ElementsKey, Elements> elements = new HashMap<>();
86     private Map<RouteObjectIncludeExcludeKey, RouteObjectIncludeExclude> routeObjectIncludeExcludes = new HashMap<>();
87     private String currentNodeId = null;
88     private AToZComparator atoZComparator =  new AToZComparator();
89     private ZToAComparator ztoAComparator =  new ZToAComparator();
90     private static final Table<Uint32, BigDecimal, String> TRX_MODE_TABLE = initTrxModeTable();
91
92     private static Table<Uint32, BigDecimal, String> initTrxModeTable() {
93         Table<Uint32, BigDecimal, String> trxModeTable = HashBasedTable.create();
94         trxModeTable.put(ServiceRateConstant.RATE_100, GridConstant.SLOT_WIDTH_50, "100 Gbit/s, 27.95 Gbaud, DP-QPSK");
95         trxModeTable.put(ServiceRateConstant.RATE_200, GridConstant.SLOT_WIDTH_50, "200 Gbit/s, 31.57 Gbaud, DP-16QAM");
96         trxModeTable.put(ServiceRateConstant.RATE_200, GridConstant.SLOT_WIDTH_87_5, "200 Gbit/s, DP-QPSK");
97         trxModeTable.put(ServiceRateConstant.RATE_300, GridConstant.SLOT_WIDTH_87_5, "300 Gbit/s, DP-8QAM");
98         trxModeTable.put(ServiceRateConstant.RATE_400, GridConstant.SLOT_WIDTH_87_5, "400 Gbit/s, DP-16QAM");
99         return trxModeTable;
100     }
101
102     public static final Map<Uint32, BigDecimal> RATE_OUTPUTPOWER = Map.of(
103             ServiceRateConstant.RATE_100, GridConstant.OUTPUT_POWER_100GB_W,
104             ServiceRateConstant.RATE_400, GridConstant.OUTPUT_POWER_400GB_W);
105
106     /*
107      * Construct the GnpyServiceImpl
108      */
109     public GnpyServiceImpl(PathComputationRequestInput input, AToZDirection atoz, Uint32 requestId,
110                 GnpyTopoImpl gnpyTopo, PceConstraints pceHardConstraints) throws GnpyException {
111         this.elements = gnpyTopo.getElements();
112         this.mapDisgNodeRefNode = gnpyTopo.getMapDisgNodeRefNode();
113         this.mapLinkFiber = gnpyTopo.getMapLinkFiber();
114         this.trxList = gnpyTopo.getTrxList();
115         this.pathRequest = extractPathRequest(input, atoz, requestId.toJava(), pceHardConstraints);
116         this.synchronization = extractSynchronization(requestId);
117     }
118
119     public GnpyServiceImpl(PathComputationRequestInput input, ZToADirection ztoa, Uint32 requestId,
120                 GnpyTopoImpl gnpyTopo, PceConstraints pceHardConstraints) throws GnpyException {
121         this.elements = gnpyTopo.getElements();
122         this.mapDisgNodeRefNode = gnpyTopo.getMapDisgNodeRefNode();
123         this.mapLinkFiber = gnpyTopo.getMapLinkFiber();
124         this.trxList = gnpyTopo.getTrxList();
125         pathRequest = extractPathRequest(input, ztoa, requestId.toJava(), pceHardConstraints);
126         synchronization = extractSynchronization(requestId);
127     }
128
129     private Map<PathRequestKey, PathRequest> extractPathRequest(
130             PathComputationRequestInput input, AToZDirection atoz, Long requestId,
131             PceConstraints pceHardConstraints) throws GnpyException {
132
133         // Create the source and destination nodes
134         String sourceNode = input.getServiceAEnd().getNodeId();
135         String destNode = input.getServiceZEnd().getNodeId();
136         if (!trxList.contains(sourceNode) || !trxList.contains(destNode)) {
137             throw new GnpyException("In GnpyServiceImpl: source and destination should be transmitter nodes");
138         }
139
140         // Create explicitRouteObjects
141         List<AToZ> listAtoZ = new ArrayList<>(atoz.nonnullAToZ().values());
142         if (listAtoZ.isEmpty()) {
143             extractHardConstraints(pceHardConstraints);
144         } else {
145             Collections.sort(listAtoZ, atoZComparator);
146             extractRouteObjectIcludeAtoZ(listAtoZ);
147         }
148
149         ExplicitRouteObjects explicitRouteObjects = new ExplicitRouteObjectsBuilder()
150             .setRouteObjectIncludeExclude(routeObjectIncludeExcludes).build();
151         //Create Path Constraint
152         PathConstraints pathConstraints = createPathConstraints(atoz.getRate().toJava(),
153                 atoz.getModulationFormat(),
154                 atoz.getAToZMinFrequency(),
155                 atoz.getAToZMaxFrequency());
156
157         // Create the path request
158         Map<PathRequestKey, PathRequest> pathRequestMap = new HashMap<>();
159         PathRequest pathRequestEl = new PathRequestBuilder().setRequestId(requestId.toString())
160             .setSource(sourceNode)
161             .setDestination(destNode)
162             .setSrcTpId(sourceNode)
163             .setDstTpId(destNode)
164             .setBidirectional(false).setPathConstraints(pathConstraints).setPathConstraints(pathConstraints)
165             .setExplicitRouteObjects(explicitRouteObjects).build();
166         pathRequestMap.put(pathRequestEl.key(),pathRequestEl);
167         LOG.debug("In GnpyServiceImpl: path request AToZ is extracted");
168         return pathRequestMap;
169     }
170
171     private Map<PathRequestKey, PathRequest> extractPathRequest(
172             PathComputationRequestInput input, ZToADirection ztoa, Long requestId,
173             PceConstraints pceHardConstraints) throws GnpyException {
174         // Create the source and destination nodes
175         String sourceNode = input.getServiceZEnd().getNodeId();
176         String destNode = input.getServiceAEnd().getNodeId();
177         if (!trxList.contains(sourceNode) || !trxList.contains(destNode)) {
178             throw new GnpyException("In GnpyServiceImpl: source and destination should be transmitter nodes");
179         }
180         // Create explicitRouteObjects
181         @NonNull List<ZToA> listZtoA = new ArrayList<>(ztoa.nonnullZToA().values());
182         if (listZtoA.isEmpty()) {
183             extractHardConstraints(pceHardConstraints);
184         } else {
185             Collections.sort(listZtoA, ztoAComparator);
186             extractRouteObjectIcludeZtoA(listZtoA);
187         }
188
189         ExplicitRouteObjects explicitRouteObjects = new ExplicitRouteObjectsBuilder()
190             .setRouteObjectIncludeExclude(routeObjectIncludeExcludes).build();
191         //Create Path Constraint
192         PathConstraints pathConstraints = createPathConstraints(ztoa.getRate().toJava(),
193                 ztoa.getModulationFormat(),
194                 ztoa.getZToAMinFrequency(),
195                 ztoa.getZToAMaxFrequency());
196
197         //Create the path request
198         Map<PathRequestKey, PathRequest> pathRequestMap = new HashMap<>();
199         PathRequest pathRequestEl = new PathRequestBuilder().setRequestId(requestId.toString())
200             .setSource(sourceNode)
201             .setDestination(destNode)
202             .setSrcTpId(sourceNode)
203             .setDstTpId(destNode)
204             .setBidirectional(false).setPathConstraints(pathConstraints)
205             .setExplicitRouteObjects(explicitRouteObjects).build();
206         pathRequestMap.put(pathRequestEl.key(),pathRequestEl);
207         LOG.debug("In GnpyServiceImpl: path request ZToA is extracted is extracted");
208         return pathRequestMap;
209     }
210
211     //Extract RouteObjectIncludeExclude list in the case of pre-computed path A-to-Z
212     private void extractRouteObjectIcludeAtoZ(Collection<AToZ> listAtoZ) throws GnpyException {
213         Long index = 0L;
214         for (AToZ entry : listAtoZ) {
215             index = createResource(entry.getResource().getResource(),index);
216         }
217     }
218
219     //Extract RouteObjectIncludeExclude list in the case of pre-computed path Z-to-A
220     private void extractRouteObjectIcludeZtoA(@NonNull List<ZToA> listZtoA) throws GnpyException {
221         Long index = 0L;
222         for (ZToA entry : listZtoA) {
223             index = createResource(entry.getResource().getResource(),index);
224         }
225     }
226
227     //Create a new resource node or link
228     private Long createResource(@Nullable Resource resource, Long index) throws GnpyException {
229         Long idx = index;
230         if (resource
231             instanceof
232                 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
233                     .pce.resource.resource.resource.Node) {
234             org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
235                 .pce.resource.resource.resource.Node node =
236                 (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
237                     .pce.resource.resource.resource.Node) resource;
238             if (node.getNodeId() == null) {
239                 throw new GnpyException("In gnpyServiceImpl: nodeId is null");
240             }
241             idx = addNodeToRouteObject(this.mapDisgNodeRefNode.get(node.getNodeId()),idx);
242         }
243
244         if (resource
245             instanceof
246                 org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
247                     .pce.resource.resource.resource.Link) {
248             org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
249                 .pce.resource.resource.resource.Link link =
250                 (org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705
251                     .pce.resource.resource.resource.Link) resource;
252             idx = addLinkToRouteObject(link.getLinkId(),idx);
253         }
254         return idx;
255     }
256
257     //Create RouteObjectIncludeExclude list in the case of hard constraint
258     private void extractHardConstraints(PceConstraints pceHardConstraints) throws GnpyException {
259         List<String> listNodeToInclude = getListToInclude(pceHardConstraints);
260         if (!listNodeToInclude.isEmpty()) {
261             Long index = 0L;
262             for (int i = 0; i < listNodeToInclude.size(); i++) {
263                 String nodeId = listNodeToInclude.get(i);
264                 index = addNodeToRouteObject(nodeId, index);
265             }
266         }
267     }
268
269     //Create the list of nodes to include
270     private List<String> getListToInclude(PceConstraints pceHardConstraints) {
271         List<String> listNodeToInclude = new ArrayList<>();
272         if (pceHardConstraints != null) {
273             List<ResourcePair> listToInclude = pceHardConstraints.getListToInclude();
274             Iterator<ResourcePair> it = listToInclude.iterator();
275             while (it.hasNext()) {
276                 ResourcePair rs = it.next();
277                 if (rs.getType().name().equals("NODE")) {
278                     listNodeToInclude.add(rs.getName());
279                 }
280             }
281         }
282         return listNodeToInclude;
283     }
284
285     //Add a node to the route object
286     private Long addNodeToRouteObject(String nodeRef, Long index) throws GnpyException {
287         Long idx = index;
288         for (Elements element : this.elements.values()) {
289             if (element.getUid().equals(nodeRef)) {
290                 if ((this.currentNodeId == null) || (!this.currentNodeId.equals(nodeRef))) {
291                     this.currentNodeId = nodeRef;
292                     RouteObjectIncludeExclude routeObjectIncludeExclude = addRouteObjectIncludeExclude(nodeRef,
293                             Uint32.valueOf(1), idx);
294                     RouteObjectIncludeExcludeKey key = new RouteObjectIncludeExcludeKey(Uint32.valueOf(idx));
295                     routeObjectIncludeExcludes.put(key, routeObjectIncludeExclude);
296                     idx += 1;
297                 }
298                 return idx;
299             }
300         }
301         throw new GnpyException(String.format("In gnpyServiceImpl : NodeRef %s does not exist",nodeRef));
302     }
303
304     //Add a link to the route object
305     private Long addLinkToRouteObject(String linkId, Long index) throws GnpyException {
306         Long idx = index;
307         if (linkId == null) {
308             throw new GnpyException("In GnpyServiceImpl: the linkId is null");
309         }
310         //Only the ROADM-to-ROADM link are included in the route object
311         if (!mapLinkFiber.containsKey(linkId)) {
312             return idx;
313         }
314         List<String> listSubLink = this.mapLinkFiber.get(linkId);
315         if (listSubLink == null) {
316             throw new GnpyException(String.format("In gnpyServiceImpl addNodeRouteObject : no sublink in %s",linkId));
317         }
318         for (String subLink : listSubLink) {
319             RouteObjectIncludeExclude routeObjectIncludeExclude =
320                 addRouteObjectIncludeExclude(subLink, Uint32.valueOf(1),idx);
321             RouteObjectIncludeExcludeKey key = new RouteObjectIncludeExcludeKey(Uint32.valueOf(idx));
322             routeObjectIncludeExcludes.put(key, routeObjectIncludeExclude);
323             idx += 1;
324         }
325         return idx;
326     }
327
328     // Add routeObjectIncludeExclude
329     private RouteObjectIncludeExclude addRouteObjectIncludeExclude(String nodeId, Uint32 teTpValue, Long index) {
330         NumUnnumHop numUnnumHop = new org.opendaylight.yang.gen.v1.gnpy.path.rev220221.explicit.route.hop.type.num
331             .unnum.hop.NumUnnumHopBuilder()
332                 .setNodeId(nodeId)
333                 .setLinkTpId(teTpValue.toString())
334                 .setHopType(TeHopType.STRICT).build();
335         Type type1 = new NumUnnumHopBuilder().setNumUnnumHop(numUnnumHop).build();
336         // Create routeObjectIncludeExclude element
337         return new RouteObjectIncludeExcludeBuilder()
338             .setIndex(Uint32.valueOf(index)).setExplicitRouteUsage(RouteIncludeEro.class).setType(type1).build();
339     }
340
341     //Create the path constraints
342     private PathConstraints createPathConstraints(Long rate, String modulationFormat, FrequencyTHz minFrequency,
343             FrequencyTHz maxFrequency) {
344         BigDecimal spacing = GridConstant.SLOT_WIDTH_50;
345         int mvalue = GridConstant.NB_SLOTS_100G;
346         int nvalue = 0;
347         if (minFrequency != null && maxFrequency != null && modulationFormat != null) {
348             LOG.info("Creating path constraints for rate {}, modulationFormat {}, min freq {}, max freq {}", rate,
349                     modulationFormat, minFrequency, maxFrequency);
350             ModulationFormat mformat = ModulationFormat.DpQpsk;
351             Optional<ModulationFormat> optionalModulationFormat = ModulationFormat.forName(modulationFormat);
352             if (optionalModulationFormat.isPresent()) {
353                 mformat = optionalModulationFormat.get();
354             }
355             spacing = GridConstant.FREQUENCY_SLOT_WIDTH_TABLE.get(Uint32.valueOf(rate), mformat);
356             FrequencyTHz centralFrequency = GridUtils
357                     .getCentralFrequency(minFrequency.getValue(), maxFrequency.getValue());
358             int centralFrequencyBitSetIndex = GridUtils.getIndexFromFrequency(centralFrequency.getValue());
359             mvalue = (int) Math.ceil(spacing.doubleValue() / (GridConstant.GRANULARITY));
360             nvalue = GridUtils.getNFromFrequencyIndex(centralFrequencyBitSetIndex);
361         }
362         LOG.info("Creating path constraints for rate {}, mvalue {}, nvalue {}, spacing {}", rate,
363                 mvalue, nvalue, spacing);
364         EffectiveFreqSlot effectiveFreqSlot = new EffectiveFreqSlotBuilder()
365                 .setM(Uint32.valueOf(mvalue / 2)).setN(nvalue).build();
366
367         TeBandwidth teBandwidth = new TeBandwidthBuilder()
368                 .setPathBandwidth(BigDecimal.valueOf(rate * 1e9))
369                 .setTechnology("flexi-grid").setTrxType("OpenROADM MSA ver. 5.0")
370                 .setTrxMode(TRX_MODE_TABLE.get(Uint32.valueOf(rate), spacing))
371                 .setOutputPower(GridUtils.convertDbmW(GridConstant.OUTPUT_POWER_100GB_DBM
372                         + 10 * Math.log10(mvalue / (double)GridConstant.NB_SLOTS_100G)))
373                 .setEffectiveFreqSlot(Map.of(effectiveFreqSlot.key(), effectiveFreqSlot))
374                 .setSpacing(spacing.multiply(BigDecimal.valueOf(1e9))).build();
375         return new PathConstraintsBuilder().setTeBandwidth(teBandwidth).build();
376     }
377
378     //Create the synchronization
379     private List<Synchronization> extractSynchronization(Uint32 requestId) {
380         // Create RequestIdNumber
381         List<String> requestIdNumber = new ArrayList<>();
382         requestIdNumber.add(requestId.toString());
383         // Create a synchronization
384         Svec svec = new SvecBuilder().setRelaxable(true)
385             .setDisjointness(new TePathDisjointness(true, true, false))
386             .setRequestIdNumber(requestIdNumber).build();
387         List<Synchronization> synchro = new ArrayList<>();
388         Synchronization synchronization1 = new SynchronizationBuilder()
389                 .setSynchronizationId(Uint32.valueOf(0).toString())
390                 .setSvec(svec).build();
391         synchro.add(synchronization1);
392         return (synchro);
393     }
394
395     public Map<PathRequestKey, PathRequest> getPathRequest() {
396         return pathRequest;
397     }
398
399     public void setPathRequest(Map<PathRequestKey, PathRequest> pathRequest) {
400         this.pathRequest = pathRequest;
401     }
402
403     public List<Synchronization> getSynchronization() {
404         return synchronization;
405     }
406
407     public void setSynchronization(List<Synchronization> synchronization) {
408         this.synchronization = synchronization;
409     }
410
411 }