Merge "Drop the service name from ODU connection name"
[transportpce.git] / renderer / src / main / java / org / opendaylight / transportpce / renderer / provisiondevice / DeviceRendererServiceImpl.java
1 /*
2  * Copyright © 2017 AT&T 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 package org.opendaylight.transportpce.renderer.provisiondevice;
9
10 import com.google.common.collect.Sets;
11 import com.google.common.util.concurrent.FluentFuture;
12 import java.util.ArrayList;
13 import java.util.Arrays;
14 import java.util.HashMap;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentLinkedQueue;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.ForkJoinPool;
25 import java.util.concurrent.ForkJoinTask;
26 import java.util.concurrent.Future;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import java.util.concurrent.atomic.AtomicBoolean;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.mdsal.binding.api.DataBroker;
32 import org.opendaylight.mdsal.binding.api.ReadTransaction;
33 import org.opendaylight.mdsal.binding.api.WriteTransaction;
34 import org.opendaylight.mdsal.common.api.CommitInfo;
35 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
36 import org.opendaylight.transportpce.common.StringConstants;
37 import org.opendaylight.transportpce.common.Timeouts;
38 import org.opendaylight.transportpce.common.crossconnect.CrossConnect;
39 import org.opendaylight.transportpce.common.device.DeviceTransactionManager;
40 import org.opendaylight.transportpce.common.fixedflex.GridConstant;
41 import org.opendaylight.transportpce.common.fixedflex.GridUtils;
42 import org.opendaylight.transportpce.common.fixedflex.SpectrumInformation;
43 import org.opendaylight.transportpce.common.mapping.PortMapping;
44 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaceException;
45 import org.opendaylight.transportpce.common.openroadminterfaces.OpenRoadmInterfaces;
46 import org.opendaylight.transportpce.networkmodel.service.NetworkModelService;
47 import org.opendaylight.transportpce.renderer.openroadminterface.OpenRoadmInterfaceFactory;
48 import org.opendaylight.transportpce.renderer.provisiondevice.servicepath.ServiceListTopology;
49 import org.opendaylight.transportpce.renderer.provisiondevice.servicepath.ServicePathDirection;
50 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.ServiceNodelist;
51 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service.nodelist.NodelistBuilder;
52 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service.nodelist.NodelistKey;
53 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.CreateOtsOmsInput;
54 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.CreateOtsOmsOutput;
55 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.CreateOtsOmsOutputBuilder;
56 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.RendererRollbackInput;
57 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.RendererRollbackOutput;
58 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.RendererRollbackOutputBuilder;
59 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.ServicePathInput;
60 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.ServicePathOutput;
61 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.ServicePathOutputBuilder;
62 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.az.api.info.AEndApiInfo;
63 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.az.api.info.ZEndApiInfo;
64 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.renderer.rollback.output.FailedToRollback;
65 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.renderer.rollback.output.FailedToRollbackBuilder;
66 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.device.renderer.rev211004.renderer.rollback.output.FailedToRollbackKey;
67 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.OpenroadmNodeVersion;
68 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220316.mapping.Mapping;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.service.types.rev211210.service.Topology;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev211210.ServiceList;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev211210.service.list.Services;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev211210.service.list.ServicesBuilder;
73 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev211210.service.list.ServicesKey;
74 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.link.tp.LinkTp;
75 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.link.tp.LinkTpBuilder;
76 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.node.interfaces.NodeInterface;
77 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.node.interfaces.NodeInterfaceBuilder;
78 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.node.interfaces.NodeInterfaceKey;
79 import org.opendaylight.yang.gen.v1.http.org.transportpce.common.types.rev210930.optical.renderer.nodes.Nodes;
80 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84
85 public class DeviceRendererServiceImpl implements DeviceRendererService {
86     private static final String IS_NOT_MOUNTED_ON_THE_CONTROLLER = " is not mounted on the controller";
87     private static final Logger LOG = LoggerFactory.getLogger(DeviceRendererServiceImpl.class);
88     private static final String PT_07 = "07";
89     private final DataBroker dataBroker;
90     private final DeviceTransactionManager deviceTransactionManager;
91     private final OpenRoadmInterfaceFactory openRoadmInterfaceFactory;
92     private final OpenRoadmInterfaces openRoadmInterfaces;
93     private final CrossConnect crossConnect;
94     private final PortMapping portMapping;
95     private final NetworkModelService networkModelService;
96
97     public DeviceRendererServiceImpl(DataBroker dataBroker, DeviceTransactionManager deviceTransactionManager,
98             OpenRoadmInterfaceFactory openRoadmInterfaceFactory, OpenRoadmInterfaces openRoadmInterfaces,
99             CrossConnect crossConnect, PortMapping portMapping, NetworkModelService networkModelService) {
100         this.dataBroker = dataBroker;
101         this.deviceTransactionManager = deviceTransactionManager;
102         this.openRoadmInterfaceFactory = openRoadmInterfaceFactory;
103         this.openRoadmInterfaces = openRoadmInterfaces;
104         this.crossConnect = crossConnect;
105         this.portMapping = portMapping;
106         this.networkModelService = networkModelService;
107     }
108
109     @SuppressWarnings("rawtypes")
110     // FIXME check if the ForkJoinTask raw type can be avoided
111     // Raw types use are discouraged since they lack type safety.
112     // Resulting Problems are observed at run time and not at compile time
113     @Override
114     public ServicePathOutput setupServicePath(ServicePathInput input, ServicePathDirection direction) {
115         LOG.info("setup service path for input {} and direction {}", input, direction);
116         List<Nodes> nodes = new ArrayList<>();
117         if (input.getNodes() != null) {
118             nodes.addAll(input.getNodes());
119         }
120         SpectrumInformation spectrumInformation = GridUtils.initSpectrumInformationFromServicePathInput(input);
121         // Register node for suppressing alarms
122         if (!alarmSuppressionNodeRegistration(input)) {
123             LOG.warn("Alarm suppresion node registration failed!!!!");
124         }
125         ConcurrentLinkedQueue<String> results = new ConcurrentLinkedQueue<>();
126         Map<NodeInterfaceKey,NodeInterface> nodeInterfaces = new ConcurrentHashMap<>();
127         Set<String> nodesProvisioned = Sets.newConcurrentHashSet();
128         CopyOnWriteArrayList<LinkTp> otnLinkTps = new CopyOnWriteArrayList<>();
129         ServiceListTopology topology = new ServiceListTopology();
130         AtomicBoolean success = new AtomicBoolean(true);
131         ForkJoinPool forkJoinPool = new ForkJoinPool();
132         ForkJoinTask forkJoinTask = forkJoinPool.submit(() -> nodes.parallelStream().forEach(node -> {
133             String nodeId = node.getNodeId();
134             // take the index of the node
135             int nodeIndex = nodes.indexOf(node);
136             LOG.info("Starting provisioning for node : {}", nodeId);
137             AEndApiInfo apiInfoA = null;
138             ZEndApiInfo apiInfoZ = null;
139             if (input.getAEndApiInfo() != null && input.getAEndApiInfo().getNodeId().contains(nodeId)) {
140                 apiInfoA = input.getAEndApiInfo();
141             }
142             if (input.getZEndApiInfo() != null && input.getZEndApiInfo().getNodeId().contains(nodeId)) {
143                 apiInfoZ = input.getZEndApiInfo();
144             }
145             List<String> createdEthInterfaces = new ArrayList<>();
146             List<String> createdOtuInterfaces = new ArrayList<>();
147             List<String> createdOduInterfaces = new ArrayList<>();
148             List<String> createdOchInterfaces = new ArrayList<>();
149             List<String> createdConnections = new ArrayList<>();
150             int crossConnectFlag = 0;
151             try {
152                 // if the node is currently mounted then proceed
153                 if (this.deviceTransactionManager.isDeviceMounted(nodeId)) {
154                     String srcTp = node.getSrcTp();
155                     String destTp = node.getDestTp();
156                     if ((destTp != null) && destTp.contains(StringConstants.NETWORK_TOKEN)) {
157                         LOG.info("Adding supporting OCH interface for node {}, dest tp {}, spectrumInformation {}",
158                                 nodeId, destTp, spectrumInformation);
159                         crossConnectFlag++;
160                         String supportingOchInterface = this.openRoadmInterfaceFactory.createOpenRoadmOchInterface(
161                                 nodeId, destTp, spectrumInformation);
162                         // Split the string based on # pass the last element as the supported Interface
163                         // This is needed for 7.1 device models with B100G, we have OTSI, OTSI-group combined as OCH
164                         String[] listOfSuppOchInf = supportingOchInterface.split("#");
165                         createdOchInterfaces = Arrays.asList(listOfSuppOchInf);
166                         // Taking the last element
167                         supportingOchInterface = createdOchInterfaces.get(createdOchInterfaces.size() - 1);
168                         String supportingOtuInterface = this.openRoadmInterfaceFactory.createOpenRoadmOtu4Interface(
169                                 nodeId, destTp, supportingOchInterface, apiInfoA, apiInfoZ);
170                         createdOtuInterfaces.add(supportingOtuInterface);
171                         if (srcTp == null) {
172                             otnLinkTps.add(new LinkTpBuilder().setNodeId(nodeId).setTpId(destTp).build());
173                         } else {
174                             // This is needed for 7.1 device models for 400GE, since we have ODUC4 and ODUflex
175                             // are combined
176                             createdOduInterfaces = Arrays.asList(this.openRoadmInterfaceFactory
177                                 .createOpenRoadmOdu4HOInterface(
178                                     nodeId, destTp, false, apiInfoA, apiInfoZ, PT_07).split("#"));
179                         }
180                     }
181                     if ((srcTp != null) && srcTp.contains(StringConstants.CLIENT_TOKEN)) {
182                         LOG.info("Adding supporting EThernet interface for node {}, src tp {}", nodeId, srcTp);
183                         crossConnectFlag++;
184                         // create OpenRoadm Xponder Client Interfaces
185                         createdEthInterfaces.add(this.openRoadmInterfaceFactory.createOpenRoadmEthInterface(
186                                 nodeId, srcTp));
187                     }
188                     if ((srcTp != null) && srcTp.contains(StringConstants.NETWORK_TOKEN)) {
189                         LOG.info("Adding supporting OCH interface for node {}, src tp {}, spectrumInformation {}",
190                                 nodeId, srcTp, spectrumInformation);
191                         crossConnectFlag++;
192                         // create OpenRoadm Xponder Line Interfaces
193                         String supportingOchInterface = this.openRoadmInterfaceFactory.createOpenRoadmOchInterface(
194                                 nodeId, srcTp, spectrumInformation);
195                         createdOchInterfaces.add(supportingOchInterface);
196                         String supportingOtuInterface = this.openRoadmInterfaceFactory.createOpenRoadmOtu4Interface(
197                                 nodeId, srcTp, supportingOchInterface, apiInfoA, apiInfoZ);
198                         createdOtuInterfaces.add(supportingOtuInterface);
199                         if (destTp == null) {
200                             otnLinkTps.add(new LinkTpBuilder().setNodeId(nodeId).setTpId(srcTp).build());
201                         } else {
202                             createdOduInterfaces.add(this.openRoadmInterfaceFactory.createOpenRoadmOdu4HOInterface(
203                                     nodeId, srcTp, false, apiInfoA, apiInfoZ, PT_07));
204                         }
205                     }
206                     if ((destTp != null) && destTp.contains(StringConstants.CLIENT_TOKEN)) {
207                         LOG.info("Adding supporting EThernet interface for node {}, dest tp {}", nodeId, destTp);
208                         crossConnectFlag++;
209                         // create OpenRoadm Xponder Client Interfaces
210                         createdEthInterfaces.add(this.openRoadmInterfaceFactory.createOpenRoadmEthInterface(
211                                 nodeId, destTp));
212                     }
213                     if ((srcTp != null) && (srcTp.contains(StringConstants.TTP_TOKEN)
214                             || srcTp.contains(StringConstants.PP_TOKEN))) {
215                         LOG.info("Adding supporting OCH interface for node {}, src tp {}, spectrumInformation {}",
216                                 nodeId, srcTp, spectrumInformation);
217                         createdOchInterfaces.addAll(this.openRoadmInterfaceFactory.createOpenRoadmOchInterfaces(
218                                 nodeId, srcTp, spectrumInformation));
219                     }
220                     if ((destTp != null) && (destTp.contains(StringConstants.TTP_TOKEN)
221                             || destTp.contains(StringConstants.PP_TOKEN))) {
222                         LOG.info("Adding supporting OCH interface for node {}, dest tp {}, spectrumInformation {}",
223                                 nodeId, destTp, spectrumInformation);
224                         createdOchInterfaces.addAll(this.openRoadmInterfaceFactory.createOpenRoadmOchInterfaces(
225                                 nodeId, destTp, spectrumInformation));
226                     }
227                     if (crossConnectFlag < 1) {
228                         LOG.info("Creating cross connect between source {} and destination {} for node {}", srcTp,
229                                 destTp, nodeId);
230                         Optional<String> connectionNameOpt =
231                                 this.crossConnect.postCrossConnect(nodeId, srcTp, destTp, spectrumInformation);
232                         if (connectionNameOpt.isPresent()) {
233                             nodesProvisioned.add(nodeId);
234                             createdConnections.add(connectionNameOpt.get());
235                         } else {
236                             processErrorMessage("Unable to post Roadm-connection for node " + nodeId, forkJoinPool,
237                                     results);
238                             success.set(false);
239                         }
240                     }
241                 } else {
242                     processErrorMessage(nodeId + IS_NOT_MOUNTED_ON_THE_CONTROLLER, forkJoinPool, results);
243                     success.set(false);
244                 }
245             } catch (OpenRoadmInterfaceException ex) {
246                 processErrorMessage("Setup service path failed! Exception:" + ex.toString(), forkJoinPool, results);
247                 success.set(false);
248             }
249             NodeInterface nodeInterface = new NodeInterfaceBuilder()
250                 .withKey(new NodeInterfaceKey(nodeId))
251                 .setNodeId(nodeId)
252                 .setConnectionId(createdConnections)
253                 .setEthInterfaceId(createdEthInterfaces)
254                 .setOtuInterfaceId(createdOtuInterfaces)
255                 .setOduInterfaceId(createdOduInterfaces)
256                 .setOchInterfaceId(createdOchInterfaces)
257                 .build();
258             nodeInterfaces.put(nodeInterface.key(),nodeInterface);
259         }));
260         try {
261             forkJoinTask.get();
262         } catch (InterruptedException | ExecutionException e) {
263             LOG.error("Error while setting up service paths!", e);
264         }
265         forkJoinPool.shutdown();
266
267         if (success.get()) {
268             results.add("Interfaces created successfully for nodes: " + String.join(", ", nodesProvisioned));
269         }
270         // setting topology in the service list data store
271         try {
272             setTopologyForService(input.getServiceName(), topology.getTopology());
273         } catch (InterruptedException | TimeoutException | ExecutionException e) {
274             LOG.warn("Failed to write topologies for service {}.", input.getServiceName(), e);
275         }
276         if (!alarmSuppressionNodeRemoval(input.getServiceName())) {
277             LOG.error("Alarm suppresion node removal failed!!!!");
278         }
279         return new ServicePathOutputBuilder()
280                 .setNodeInterface(nodeInterfaces)
281                 .setSuccess(success.get())
282                 .setResult(String.join("\n", results))
283                 .setLinkTp(otnLinkTps)
284                 .build();
285     }
286
287     private ConcurrentLinkedQueue<String> processErrorMessage(String message, ForkJoinPool forkJoinPool,
288             ConcurrentLinkedQueue<String> messages) {
289         LOG.warn("Received error message {}", message);
290         messages.add(message);
291         forkJoinPool.shutdown();
292         return messages;
293     }
294
295     @SuppressWarnings("rawtypes")
296     // FIXME check if the ForkJoinTask raw type can be avoided
297     // Raw types use are discouraged since they lack type safety.
298     // Resulting Problems are observed at run time and not at compile time
299     @Override
300     public ServicePathOutput deleteServicePath(ServicePathInput input) {
301         if (!alarmSuppressionNodeRegistration(input)) {
302             LOG.warn("Alarm suppression node registration failed!!!!");
303         }
304         List<Nodes> nodes = input.getNodes();
305         AtomicBoolean success = new AtomicBoolean(true);
306         ConcurrentLinkedQueue<String> results = new ConcurrentLinkedQueue<>();
307         CopyOnWriteArrayList<LinkTp> otnLinkTps = new CopyOnWriteArrayList<>();
308         ForkJoinPool forkJoinPool = new ForkJoinPool();
309         ForkJoinTask forkJoinTask = forkJoinPool.submit(() -> nodes.parallelStream().forEach(node -> {
310             String nodeId = node.getNodeId();
311             LOG.info("Deleting service setup on node {}", nodeId);
312             if (node.getDestTp() == null) {
313                 LOG.error("Destination termination point must not be null.");
314                 return;
315             }
316             if (!this.deviceTransactionManager.isDeviceMounted(nodeId)) {
317                 String result = nodeId + IS_NOT_MOUNTED_ON_THE_CONTROLLER;
318                 results.add(result);
319                 success.set(false);
320                 LOG.warn(result);
321                 forkJoinPool.shutdown();
322                 return;
323                 //TODO should deletion end here?
324             }
325             // if the node is currently mounted then proceed.
326
327             String destTp = node.getDestTp();
328             String srcTp = "";
329             if (node.getSrcTp() == null) {
330                 otnLinkTps.add(new LinkTpBuilder()
331                         .setNodeId(nodeId)
332                         .setTpId(destTp)
333                         .build());
334             } else {
335                 srcTp = node.getSrcTp();
336             }
337             List<String> interfacesToDelete = new LinkedList<>();
338             interfacesToDelete.addAll(getInterfaces2delete(nodeId, srcTp, destTp,
339                     input.getLowerSpectralSlotNumber().intValue(),
340                     input.getHigherSpectralSlotNumber().intValue()));
341             for (String interfaceId : interfacesToDelete) {
342                 try {
343                     this.openRoadmInterfaces.deleteInterface(nodeId, interfaceId);
344                 } catch (OpenRoadmInterfaceException e) {
345                     String result = String.format("Failed to delete interface %s on node %s!", interfaceId, nodeId);
346                     success.set(false);
347                     LOG.error(result, e);
348                     results.add(result);
349                 }
350             }
351         }));
352         try {
353             forkJoinTask.get();
354         } catch (InterruptedException | ExecutionException e) {
355             LOG.error("Error while deleting service paths!", e);
356         }
357         forkJoinPool.shutdown();
358         if (!alarmSuppressionNodeRemoval(input.getServiceName())) {
359             LOG.error("Alarm suppresion node removal failed!!!!");
360         }
361         return new ServicePathOutputBuilder()
362                 .setSuccess(success.get())
363                 .setLinkTp(otnLinkTps)
364                 .setResult(
365                     results.isEmpty()
366                     ? "Request processed"
367                     : String.join("\n", results))
368                 .build();
369     }
370
371     private List<String> getInterfaces2delete(
372             String nodeId, String srcTp, String destTp, int lowerSpectralSlotNumber, int higherSpectralSlotNumber) {
373         String spectralSlotName = String.join(GridConstant.SPECTRAL_SLOT_SEPARATOR,
374                 String.valueOf(lowerSpectralSlotNumber),
375                 String.valueOf(higherSpectralSlotNumber));
376
377         if (destTp.contains(StringConstants.NETWORK_TOKEN)
378                 || srcTp.contains(StringConstants.CLIENT_TOKEN)
379                 || srcTp.contains(StringConstants.NETWORK_TOKEN)
380                 || destTp.contains(StringConstants.CLIENT_TOKEN)) {
381             return getInterfacesTodelete(nodeId, srcTp, destTp, spectralSlotName);
382         }
383
384         List<String> interfacesToDelete = new LinkedList<>();
385         String connectionNumber = String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, destTp, spectralSlotName);
386         List<String> intToDelete = this.crossConnect.deleteCrossConnect(nodeId, connectionNumber, false);
387         for (String interf : intToDelete == null ? new ArrayList<String>() : intToDelete) {
388             if (!this.openRoadmInterfaceFactory.isUsedByXc(
389                     nodeId, interf, connectionNumber, this.deviceTransactionManager)) {
390                 interfacesToDelete.add(interf);
391             }
392         }
393         return interfacesToDelete;
394     }
395
396     private List<String> getInterfacesTodelete(String nodeId, String srcTp, String destTp, String spectralSlotName) {
397
398         OpenroadmNodeVersion nodeOpenRoadmVersion =
399                 this.portMapping.getNode(nodeId).getNodeInfo().getOpenroadmVersion();
400
401         List<String> interfacesToDelete = new LinkedList<>();
402         Map<String, List<String>> suffixListMap =
403             nodeOpenRoadmVersion.equals(OpenroadmNodeVersion._71)
404                 ? Map.of(
405                     // We don't need ODUC2, ODUC3 here, since they are handled in OTN service-path
406                     // This has to be in an order of deletion
407                     "ODU",  List.of("ODU4", "ODUFLEX", "ODUC4"),
408                     // Add intermediate OTUCn rates (OTUC2, OTUC3)
409                     // OTU4 is used in 100G service on 7.1 model
410                     "other", List.of("OTU4", "OTUC2", "OTUC3", "OTUC4",
411                     "OTSIGROUP-400G", "OTSIGROUP-300G",  "OTSIGROUP-200G",
412                     spectralSlotName))
413                 : Map.of(
414                     "ODU", List.of("ODU", "ODU4"),
415                     "other", List.of("OTU", spectralSlotName));
416         // this last suffix used to be retrieved from openRoadmInterfaceFactory.createOpenRoadmOchInterfaceName
417         // i.e. String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, spectralSlotName) with
418         // common GridConstant that states NAME_PARAMETERS_SEPARATOR = "-"
419
420         if (destTp.contains(StringConstants.NETWORK_TOKEN)) {
421             try {
422                 for (String suffix : suffixListMap.get("ODU")) {
423                     if (this.openRoadmInterfaces.getInterface(
424                             nodeId, String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix)).isPresent()) {
425                         interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix));
426                     }
427                 }
428             }
429             catch (OpenRoadmInterfaceException e) {
430                 LOG.error("impossible to get one of the interfaces {}",
431                     destTp + GridConstant.NAME_PARAMETERS_SEPARATOR + String.join(
432                         " or " + destTp + GridConstant.NAME_PARAMETERS_SEPARATOR,
433                         suffixListMap.get("ODU")),
434                     e);
435             }
436             try {
437                 for (String suffix : suffixListMap.get("other")) {
438                     if (this.openRoadmInterfaces.getInterface(
439                         nodeId, String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix)).isPresent()) {
440                         LOG.info("Deleting the interface {}",
441                             String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix));
442                         interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix));
443                     }
444                 }
445             }
446             catch (OpenRoadmInterfaceException e) {
447                 LOG.error("impossible to get one of the interfaces {}",
448                     destTp + GridConstant.NAME_PARAMETERS_SEPARATOR + String.join(
449                         " or " + destTp + GridConstant.NAME_PARAMETERS_SEPARATOR,
450                         suffixListMap.get("ODU")),
451                     e);
452             }
453         }
454         if (srcTp.contains(StringConstants.NETWORK_TOKEN)) {
455             interfacesToDelete.add(
456                     String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, suffixListMap.get("ODU").get(0)));
457             for (String suffix : suffixListMap.get("other")) {
458                 interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, suffix));
459             }
460         }
461
462         if (srcTp.contains(StringConstants.CLIENT_TOKEN)) {
463             interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, "ETHERNET"));
464         }
465         if (destTp.contains(StringConstants.CLIENT_TOKEN)) {
466
467             interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, "ETHERNET"));
468         }
469         return interfacesToDelete;
470     }
471
472
473
474     @Override
475     public RendererRollbackOutput rendererRollback(RendererRollbackInput input) {
476         boolean success = true;
477         Map<FailedToRollbackKey,FailedToRollback> failedToRollbackList = new HashMap<>();
478         for (NodeInterface nodeInterfaces : input.nonnullNodeInterface().values()) {
479             List<String> failedInterfaces = new ArrayList<>();
480             String nodeId = nodeInterfaces.getNodeId();
481             for (String connectionId : nodeInterfaces.getConnectionId()) {
482                 List<String> listInter = this.crossConnect.deleteCrossConnect(nodeId, connectionId, false);
483                 if (listInter != null) {
484                     LOG.info("Cross connect {} on node {} successfully deleted.", connectionId, nodeId);
485                 } else {
486                     LOG.error("Failed to delete cross connect {} on node {}!", connectionId, nodeId);
487                     success = false;
488                     failedInterfaces.add(connectionId);
489                 }
490             }
491             // Interfaces needs to be in specific order to delete. Order is:
492             // 1. ODU interfaces
493             // 2. OTU interfaces
494             // 3. OCH interfaces
495             // 4. ETH interfaces
496             LinkedList<String> interfacesToDelete = new LinkedList<>();
497             if (nodeInterfaces.getOduInterfaceId() != null) {
498                 interfacesToDelete.addAll(nodeInterfaces.getOduInterfaceId());
499             }
500             if (nodeInterfaces.getOtuInterfaceId() != null) {
501                 interfacesToDelete.addAll(nodeInterfaces.getOtuInterfaceId());
502             }
503             if (nodeInterfaces.getOchInterfaceId() != null) {
504                 interfacesToDelete.addAll(nodeInterfaces.getOchInterfaceId());
505             }
506             if (nodeInterfaces.getEthInterfaceId() != null) {
507                 interfacesToDelete.addAll(nodeInterfaces.getEthInterfaceId());
508             }
509             LOG.info("Going to execute rollback on node {}. Interfaces to rollback: {}", nodeId,
510                     String.join(", ", interfacesToDelete));
511             for (String interfaceId : interfacesToDelete) {
512                 try {
513                     this.openRoadmInterfaces.deleteInterface(nodeId, interfaceId);
514                     LOG.info("Interface {} on node {} successfully deleted.", interfaceId, nodeId);
515                 } catch (OpenRoadmInterfaceException e) {
516                     LOG.error("Failed to delete interface {} on node {}!", interfaceId, nodeId);
517                     success = false;
518                     failedInterfaces.add(interfaceId);
519                 }
520             }
521             FailedToRollback failedToRollack = new FailedToRollbackBuilder().withKey(new FailedToRollbackKey(nodeId))
522                     .setNodeId(nodeId).setInterface(failedInterfaces).build();
523             failedToRollbackList.put(failedToRollack.key(),failedToRollack);
524         }
525         return new RendererRollbackOutputBuilder()
526                 .setSuccess(success)
527                 .setFailedToRollback(failedToRollbackList)
528                 .build();
529     }
530
531     private boolean alarmSuppressionNodeRegistration(ServicePathInput input) {
532         Map<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service
533                 .nodelist.nodelist.NodesKey,
534             org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service
535                 .nodelist.nodelist.Nodes> nodeList = new HashMap<>();
536         if (input.getNodes() != null) {
537             for (Nodes node : input.getNodes()) {
538                 org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
539                     .service.nodelist.nodelist.Nodes nodes =
540                         new org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
541                             .service.nodelist.nodelist.NodesBuilder().setNodeId(node.getNodeId()).build();
542                 nodeList.put(nodes.key(),nodes);
543             }
544         }
545         InstanceIdentifier<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
546             .service.nodelist.Nodelist> nodeListIID =
547                  InstanceIdentifier.create(ServiceNodelist.class)
548                      .child(org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
549                          .service.nodelist.Nodelist.class, new NodelistKey(input.getServiceName()));
550         final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
551         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION,
552                 nodeListIID,
553                 new NodelistBuilder()
554                     .withKey(new NodelistKey(input.getServiceName()))
555                     .setServiceName(input.getServiceName())
556                     .setNodes(nodeList)
557                     .build());
558         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
559         try {
560             commit.get(Timeouts.DATASTORE_WRITE, TimeUnit.MILLISECONDS);
561             LOG.info("Nodes are register for alarm suppression for service: {}", input.getServiceName());
562             return true;
563         } catch (ExecutionException | InterruptedException | TimeoutException e) {
564             LOG.warn("Failed to alarm suppresslist for service: {}", input.getServiceName(), e);
565             return false;
566         }
567     }
568
569     private boolean alarmSuppressionNodeRemoval(String serviceName) {
570         InstanceIdentifier<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
571             .service.nodelist.Nodelist> nodeListIID =
572                 InstanceIdentifier.create(ServiceNodelist.class)
573                     .child(org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
574                         .service.nodelist.Nodelist.class, new NodelistKey(serviceName));
575         final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
576         writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, nodeListIID);
577         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
578         try {
579             commit.get(Timeouts.DATASTORE_DELETE, TimeUnit.MILLISECONDS);
580             LOG.info("Nodes are unregister for alarm suppression for service: {}", serviceName);
581             return true;
582         } catch (InterruptedException | TimeoutException | ExecutionException e) {
583             LOG.warn("Failed to alarm suppresslist for service: {}", serviceName, e);
584             return false;
585         }
586     }
587
588     private void setTopologyForService(String name, Topology topo)
589             throws InterruptedException, ExecutionException, TimeoutException {
590         ServicesBuilder servicesBuilder;
591         // Get the service from the service list inventory
592         ServicesKey serviceKey = new ServicesKey(name);
593         InstanceIdentifier<Services> iid =
594                 InstanceIdentifier.create(ServiceList.class).child(Services.class, serviceKey);
595         Optional<Services> services;
596         try (ReadTransaction readTx = this.dataBroker.newReadOnlyTransaction()) {
597             Future<java.util.Optional<Services>> future =
598                     readTx.read(LogicalDatastoreType.OPERATIONAL, iid);
599             services = future.get(Timeouts.DATASTORE_READ, TimeUnit.MILLISECONDS);
600         } catch (InterruptedException | ExecutionException | TimeoutException e) {
601             throw e;
602         }
603         if (services.isPresent()) {
604             LOG.info("service {} already exists", name);
605             servicesBuilder = new ServicesBuilder(services.get()).setTopology(topo);
606             WriteTransaction writeTx = this.dataBroker.newWriteOnlyTransaction();
607             writeTx.merge(LogicalDatastoreType.OPERATIONAL, iid, servicesBuilder.build());
608             writeTx.commit().get(Timeouts.DATASTORE_WRITE, TimeUnit.MILLISECONDS);
609         } else {
610             LOG.warn("Service {} does not exist - topology can not be updated", name);
611         }
612     }
613
614     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
615         value = "SLF4J_FORMAT_SHOULD_BE_CONST",
616         justification = "Log messages content needs to be formatted before"
617             + "since they are used in the returned object")
618     @Override
619     public CreateOtsOmsOutput createOtsOms(CreateOtsOmsInput input) throws OpenRoadmInterfaceException {
620         if (!this.deviceTransactionManager.isDeviceMounted(input.getNodeId())) {
621             String result = input.getNodeId() + IS_NOT_MOUNTED_ON_THE_CONTROLLER;
622             LOG.warn(result);
623             return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
624         }
625         // if the node is currently mounted then proceed.
626         Mapping oldMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
627         if (oldMapping == null) {
628             return new CreateOtsOmsOutputBuilder()
629                     .setResult(String.format("Logical Connection point %s does not exist for %s",
630                             input.getLogicalConnectionPoint(), input.getNodeId()))
631                     .setSuccess(false)
632                     .build();
633         }
634
635         String otsInterface = this.openRoadmInterfaceFactory.createOpenRoadmOtsInterface(input.getNodeId(), oldMapping);
636         int count = 0;
637         Mapping newMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
638         while (!isSupportingOtsPresent(newMapping)) {
639             LOG.info("waiting for post interface operation on node '{}'...", input.getNodeId());
640             try {
641                 Thread.sleep(10000);
642                 this.portMapping.updateMapping(input.getNodeId(), oldMapping);
643             } catch (InterruptedException e) {
644                 LOG.error("Failed to wait for post interface operation");
645             }
646             count++;
647             if (count >= 6) {
648                 String result = String.format("Unable to get ots interface from mapping %s - %s",
649                         oldMapping.getLogicalConnectionPoint(), input.getNodeId());
650                 LOG.error(result);
651                 return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
652             }
653             newMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
654         }
655
656         String omsInterface = this.openRoadmInterfaceFactory.createOpenRoadmOmsInterface(input.getNodeId(), newMapping);
657         if (omsInterface == null) {
658             String result = String.format("Fail to create OpenRoadmOms Interface for node : %s", input.getNodeId());
659             LOG.error(result);
660             return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
661         }
662         return new CreateOtsOmsOutputBuilder()
663                 .setResult(String.format("Interfaces %s - %s successfully created on node %s",
664                     otsInterface, omsInterface, input.getNodeId()))
665                 .setSuccess(true)
666                 .build();
667     }
668
669     private Boolean isSupportingOtsPresent(Mapping mapping) {
670         if (mapping == null) {
671             return false;
672         }
673         if (mapping.getSupportingOts() == null) {
674             LOG.warn("SupportingOts info is not present in mapping {}", mapping);
675             return false;
676         }
677         LOG.info("SupportingOts info is present in mapping {}", mapping);
678         return true;
679     }
680 }