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