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