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