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