Generalize supporting interface (B100G) in port-mapping
[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.rev220114.OpenroadmNodeVersion;
67 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.portmapping.rev220114.mapping.Mapping;
68 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.service.types.rev190531.service.Topology;
69 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.ServiceList;
70 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.service.list.Services;
71 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.service.list.ServicesBuilder;
72 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev190531.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("Roadm-connection successfully created 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 suppresion node registraion 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         if (destTp.contains(StringConstants.NETWORK_TOKEN)
368                 || srcTp.contains(StringConstants.CLIENT_TOKEN)
369                 || srcTp.contains(StringConstants.NETWORK_TOKEN)
370                 || destTp.contains(StringConstants.CLIENT_TOKEN)) {
371             return getInterfacesTodelete(nodeId, srcTp, destTp, spectralSlotName);
372         }
373
374         List<String> interfacesToDelete = new LinkedList<>();
375         String connectionNumber = String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, destTp, spectralSlotName);
376         List<String> intToDelete = this.crossConnect.deleteCrossConnect(nodeId, connectionNumber, false);
377         for (String interf : intToDelete == null ? new ArrayList<String>() : intToDelete) {
378             if (!this.openRoadmInterfaceFactory.isUsedByXc(
379                     nodeId, interf, connectionNumber, this.deviceTransactionManager)) {
380                 interfacesToDelete.add(interf);
381             }
382         }
383         return interfacesToDelete;
384     }
385
386     private List<String> getInterfacesTodelete(String nodeId, String srcTp, String destTp, String spectralSlotName) {
387
388         OpenroadmNodeVersion nodeOpenRoadmVersion =
389                 this.portMapping.getNode(nodeId).getNodeInfo().getOpenroadmVersion();
390         List<String> interfacesToDelete = new LinkedList<>();
391         Map<String, List<String>> suffixListMap =
392             nodeOpenRoadmVersion.equals(OpenroadmNodeVersion._71)
393                 ? Map.of(
394                     "ODU",  List.of("ODUC4","ODUFLEX"),
395                     "other", List.of("OTUC4", "OTSI-GROUP", spectralSlotName))
396                 : Map.of(
397                     "ODU", List.of("ODU", "ODU4"),
398                     "other", List.of("OTU", spectralSlotName));
399         // this last suffix used to be retrieved from openRoadmInterfaceFactory.createOpenRoadmOchInterfaceName
400         // i.e. String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, spectralSlotName) with
401         // common GridConstant that states NAME_PARAMETERS_SEPARATOR = "-"
402
403         if (destTp.contains(StringConstants.NETWORK_TOKEN)) {
404             try {
405                 for (String suffix : suffixListMap.get("ODU")) {
406                     if (this.openRoadmInterfaces.getInterface(
407                             nodeId, String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix)).isPresent()) {
408                         interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix));
409                     }
410                 }
411             }
412             catch (OpenRoadmInterfaceException e) {
413                 LOG.error("impossible to get one of the interfaces {}",
414                     destTp + GridConstant.NAME_PARAMETERS_SEPARATOR + String.join(
415                         " or " + destTp + GridConstant.NAME_PARAMETERS_SEPARATOR,
416                         suffixListMap.get("ODU")),
417                     e);
418             }
419             for (String suffix : suffixListMap.get("other")) {
420                 interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, suffix));
421             }
422         }
423         if (srcTp.contains(StringConstants.NETWORK_TOKEN)) {
424             interfacesToDelete.add(
425                     String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, suffixListMap.get("ODU").get(0)));
426             for (String suffix : suffixListMap.get("other")) {
427                 interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, suffix));
428             }
429         }
430         if (srcTp.contains(StringConstants.CLIENT_TOKEN)) {
431             interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, srcTp, "ETHERNET"));
432         }
433         if (destTp.contains(StringConstants.CLIENT_TOKEN)) {
434             interfacesToDelete.add(String.join(GridConstant.NAME_PARAMETERS_SEPARATOR, destTp, "ETHERNET"));
435         }
436         return interfacesToDelete;
437     }
438
439
440
441     @Override
442     public RendererRollbackOutput rendererRollback(RendererRollbackInput input) {
443         boolean success = true;
444         Map<FailedToRollbackKey,FailedToRollback> failedToRollbackList = new HashMap<>();
445         for (NodeInterface nodeInterfaces : input.nonnullNodeInterface().values()) {
446             List<String> failedInterfaces = new ArrayList<>();
447             String nodeId = nodeInterfaces.getNodeId();
448             for (String connectionId : nodeInterfaces.getConnectionId()) {
449                 List<String> listInter = this.crossConnect.deleteCrossConnect(nodeId, connectionId, false);
450                 if (listInter != null) {
451                     LOG.info("Cross connect {} on node {} successfully deleted.", connectionId, nodeId);
452                 } else {
453                     LOG.error("Failed to delete cross connect {} on node {}!", connectionId, nodeId);
454                     success = false;
455                     failedInterfaces.add(connectionId);
456                 }
457             }
458             // Interfaces needs to be in specific order to delete. Order is:
459             // 1. ODU interfaces
460             // 2. OTU interfaces
461             // 3. OCH interfaces
462             // 4. ETH interfaces
463             LinkedList<String> interfacesToDelete = new LinkedList<>();
464             if (nodeInterfaces.getOduInterfaceId() != null) {
465                 interfacesToDelete.addAll(nodeInterfaces.getOduInterfaceId());
466             }
467             if (nodeInterfaces.getOtuInterfaceId() != null) {
468                 interfacesToDelete.addAll(nodeInterfaces.getOtuInterfaceId());
469             }
470             if (nodeInterfaces.getOchInterfaceId() != null) {
471                 interfacesToDelete.addAll(nodeInterfaces.getOchInterfaceId());
472             }
473             if (nodeInterfaces.getEthInterfaceId() != null) {
474                 interfacesToDelete.addAll(nodeInterfaces.getEthInterfaceId());
475             }
476             LOG.info("Going to execute rollback on node {}. Interfaces to rollback: {}", nodeId,
477                     String.join(", ", interfacesToDelete));
478             for (String interfaceId : interfacesToDelete) {
479                 try {
480                     this.openRoadmInterfaces.deleteInterface(nodeId, interfaceId);
481                     LOG.info("Interface {} on node {} successfully deleted.", interfaceId, nodeId);
482                 } catch (OpenRoadmInterfaceException e) {
483                     LOG.error("Failed to delete interface {} on node {}!", interfaceId, nodeId);
484                     success = false;
485                     failedInterfaces.add(interfaceId);
486                 }
487             }
488             FailedToRollback failedToRollack = new FailedToRollbackBuilder().withKey(new FailedToRollbackKey(nodeId))
489                     .setNodeId(nodeId).setInterface(failedInterfaces).build();
490             failedToRollbackList.put(failedToRollack.key(),failedToRollack);
491         }
492         return new RendererRollbackOutputBuilder()
493                 .setSuccess(success)
494                 .setFailedToRollback(failedToRollbackList)
495                 .build();
496     }
497
498     private boolean alarmSuppressionNodeRegistration(ServicePathInput input) {
499         Map<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service
500                 .nodelist.nodelist.NodesKey,
501             org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102.service
502                 .nodelist.nodelist.Nodes> nodeList = new HashMap<>();
503         if (input.getNodes() != null) {
504             for (Nodes node : input.getNodes()) {
505                 org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
506                     .service.nodelist.nodelist.Nodes nodes =
507                         new org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
508                             .service.nodelist.nodelist.NodesBuilder().setNodeId(node.getNodeId()).build();
509                 nodeList.put(nodes.key(),nodes);
510             }
511         }
512         InstanceIdentifier<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
513             .service.nodelist.Nodelist> nodeListIID =
514                  InstanceIdentifier.create(ServiceNodelist.class)
515                      .child(org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
516                          .service.nodelist.Nodelist.class, new NodelistKey(input.getServiceName()));
517         final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
518         writeTransaction.merge(LogicalDatastoreType.CONFIGURATION,
519                 nodeListIID,
520                 new NodelistBuilder()
521                     .withKey(new NodelistKey(input.getServiceName()))
522                     .setServiceName(input.getServiceName())
523                     .setNodes(nodeList)
524                     .build());
525         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
526         try {
527             commit.get(Timeouts.DATASTORE_WRITE, TimeUnit.MILLISECONDS);
528             LOG.info("Nodes are register for alarm suppression for service: {}", input.getServiceName());
529             return true;
530         } catch (ExecutionException | InterruptedException | TimeoutException e) {
531             LOG.warn("Failed to alarm suppresslist for service: {}", input.getServiceName(), e);
532             return false;
533         }
534     }
535
536     private boolean alarmSuppressionNodeRemoval(String serviceName) {
537         InstanceIdentifier<org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
538             .service.nodelist.Nodelist> nodeListIID =
539                 InstanceIdentifier.create(ServiceNodelist.class)
540                     .child(org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.alarmsuppression.rev171102
541                         .service.nodelist.Nodelist.class, new NodelistKey(serviceName));
542         final WriteTransaction writeTransaction = this.dataBroker.newWriteOnlyTransaction();
543         writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, nodeListIID);
544         FluentFuture<? extends @NonNull CommitInfo> commit = writeTransaction.commit();
545         try {
546             commit.get(Timeouts.DATASTORE_DELETE, TimeUnit.MILLISECONDS);
547             LOG.info("Nodes are unregister for alarm suppression for service: {}", serviceName);
548             return true;
549         } catch (InterruptedException | TimeoutException | ExecutionException e) {
550             LOG.warn("Failed to alarm suppresslist for service: {}", serviceName, e);
551             return false;
552         }
553     }
554
555     private void setTopologyForService(String name, Topology topo)
556             throws InterruptedException, ExecutionException, TimeoutException {
557         ServicesBuilder servicesBuilder;
558         // Get the service from the service list inventory
559         ServicesKey serviceKey = new ServicesKey(name);
560         InstanceIdentifier<Services> iid =
561                 InstanceIdentifier.create(ServiceList.class).child(Services.class, serviceKey);
562         Optional<Services> services;
563         try (ReadTransaction readTx = this.dataBroker.newReadOnlyTransaction()) {
564             Future<java.util.Optional<Services>> future =
565                     readTx.read(LogicalDatastoreType.OPERATIONAL, iid);
566             services = future.get(Timeouts.DATASTORE_READ, TimeUnit.MILLISECONDS);
567         } catch (InterruptedException | ExecutionException | TimeoutException e) {
568             throw e;
569         }
570         if (services.isPresent()) {
571             LOG.info("service {} already exists", name);
572             servicesBuilder = new ServicesBuilder(services.get()).setTopology(topo);
573             WriteTransaction writeTx = this.dataBroker.newWriteOnlyTransaction();
574             writeTx.merge(LogicalDatastoreType.OPERATIONAL, iid, servicesBuilder.build());
575             writeTx.commit().get(Timeouts.DATASTORE_WRITE, TimeUnit.MILLISECONDS);
576         } else {
577             LOG.warn("Service {} does not exist - topology can not be updated", name);
578         }
579     }
580
581     @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
582         value = "SLF4J_FORMAT_SHOULD_BE_CONST",
583         justification = "Log messages content needs to be formatted before"
584             + "since they are used in the returned object")
585     @Override
586     public CreateOtsOmsOutput createOtsOms(CreateOtsOmsInput input) throws OpenRoadmInterfaceException {
587         if (!this.deviceTransactionManager.isDeviceMounted(input.getNodeId())) {
588             String result = input.getNodeId() + IS_NOT_MOUNTED_ON_THE_CONTROLLER;
589             LOG.warn(result);
590             return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
591         }
592         // if the node is currently mounted then proceed.
593         Mapping oldMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
594         if (oldMapping == null) {
595             return new CreateOtsOmsOutputBuilder()
596                     .setResult(String.format("Logical Connection point %s does not exist for %s",
597                             input.getLogicalConnectionPoint(), input.getNodeId()))
598                     .setSuccess(false)
599                     .build();
600         }
601
602         String otsInterface = this.openRoadmInterfaceFactory.createOpenRoadmOtsInterface(input.getNodeId(), oldMapping);
603         int count = 0;
604         Mapping newMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
605         while (!isSupportingOtsPresent(newMapping)) {
606             LOG.info("waiting for post interface operation on node '{}'...", input.getNodeId());
607             try {
608                 Thread.sleep(10000);
609                 this.portMapping.updateMapping(input.getNodeId(), oldMapping);
610             } catch (InterruptedException e) {
611                 LOG.error("Failed to wait for post interface operation");
612             }
613             count++;
614             if (count >= 6) {
615                 String result = String.format("Unable to get ots interface from mapping %s - %s",
616                         oldMapping.getLogicalConnectionPoint(), input.getNodeId());
617                 LOG.error(result);
618                 return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
619             }
620             newMapping = this.portMapping.getMapping(input.getNodeId(), input.getLogicalConnectionPoint());
621         }
622
623         String omsInterface = this.openRoadmInterfaceFactory.createOpenRoadmOmsInterface(input.getNodeId(), newMapping);
624         if (omsInterface == null) {
625             String result = String.format("Fail to create OpenRoadmOms Interface for node : %s", input.getNodeId());
626             LOG.error(result);
627             return new CreateOtsOmsOutputBuilder().setResult(result).setSuccess(false).build();
628         }
629         return new CreateOtsOmsOutputBuilder()
630                 .setResult(String.format("Interfaces %s - %s successfully created on node %s",
631                     otsInterface, omsInterface, input.getNodeId()))
632                 .setSuccess(true)
633                 .build();
634     }
635
636     private Boolean isSupportingOtsPresent(Mapping mapping) {
637         if (mapping == null) {
638             return false;
639         }
640         if (mapping.getSupportingOts() == null) {
641             LOG.warn("SupportingOts info is not present in mapping {}", mapping);
642             return false;
643         }
644         LOG.info("SupportingOts info is present in mapping {}", mapping);
645         return true;
646     }
647 }