366050fa8f4b78b2cdae02c407cc6a76cd016946
[transportpce.git] / tapi / src / main / java / org / opendaylight / transportpce / tapi / utils / TapiContext.java
1 /*
2  * Copyright © 2021 Nokia, Inc. 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.tapi.utils;
9
10 import java.nio.charset.Charset;
11 import java.util.HashMap;
12 import java.util.Map;
13 import java.util.Optional;
14 import java.util.UUID;
15 import java.util.concurrent.ExecutionException;
16 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
17 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
18 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.Context;
19 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.ContextBuilder;
20 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.LayerProtocolName;
21 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.Uuid;
22 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.global._class.Name;
23 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.global._class.NameBuilder;
24 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.tapi.context.ServiceInterfacePoint;
25 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev221121.tapi.context.ServiceInterfacePointKey;
26 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.Context1;
27 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.Context1Builder;
28 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.OwnedNodeEdgePoint1;
29 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.OwnedNodeEdgePoint1Builder;
30 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.cep.list.ConnectionEndPoint;
31 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.cep.list.ConnectionEndPointKey;
32 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connection.LowerConnection;
33 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connection.LowerConnectionKey;
34 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.Connection;
35 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.ConnectionKey;
36 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.ConnectivityService;
37 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.ConnectivityServiceKey;
38 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContextBuilder;
39 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.context.topology.context.topology.node.owned.node.edge.point.CepList;
40 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.context.topology.context.topology.node.owned.node.edge.point.CepListBuilder;
41 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev221121.context.NotificationContextBuilder;
42 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext;
43 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContextBuilder;
44 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.node.OwnedNodeEdgePoint;
45 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.node.OwnedNodeEdgePointBuilder;
46 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.node.OwnedNodeEdgePointKey;
47 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Link;
48 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.LinkKey;
49 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Node;
50 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.NodeBuilder;
51 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.NodeKey;
52 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.context.NwTopologyServiceBuilder;
53 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.context.Topology;
54 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.context.TopologyKey;
55 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class TapiContext {
60
61     private static final Logger LOG = LoggerFactory.getLogger(TapiContext.class);
62     public static final String TAPI_CONTEXT = "T-API context";
63     public static final String NODE_NOT_PRESENT = "Node is not present in datastore";
64     private final NetworkTransactionService networkTransactionService;
65
66     public TapiContext(NetworkTransactionService networkTransactionService) {
67         this.networkTransactionService = networkTransactionService;
68         createTapiContext();
69     }
70
71     private void createTapiContext() {
72         try {
73             // Augmenting tapi context to include topology and connectivity contexts
74             Name contextName = new NameBuilder().setValue(TAPI_CONTEXT).setValueName("TAPI Context Name").build();
75
76             Context1 connectivityContext =
77                 new Context1Builder()
78                     .setConnectivityContext(
79                         new ConnectivityContextBuilder()
80                             .setConnection(new HashMap<>())
81                             .setConnectivityService(new HashMap<>())
82                             .build())
83                     .build();
84
85             Name nwTopoServiceName =
86                 new NameBuilder()
87                     .setValue("Network Topo Service")
88                     .setValueName("Network Topo Service Name")
89                     .build();
90
91             org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1 topologyContext
92                 = new org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1Builder()
93                     .setTopologyContext(new TopologyContextBuilder()
94                         .setNwTopologyService(new NwTopologyServiceBuilder()
95                             .setTopology(new HashMap<>())
96                             .setUuid(
97                                 new Uuid(
98                                     UUID.nameUUIDFromBytes("Network Topo Service".getBytes(Charset.forName("UTF-8")))
99                                         .toString()))
100                             .setName(Map.of(nwTopoServiceName.key(), nwTopoServiceName))
101                             .build())
102                         .setTopology(new HashMap<>())
103                         .build())
104                     .build();
105
106             org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev221121.Context1 notificationContext
107                 = new org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev221121.Context1Builder()
108                     .setNotificationContext(new NotificationContextBuilder()
109                         .setNotification(new HashMap<>())
110                         .setNotifSubscription(new HashMap<>())
111                         .build())
112                     .build();
113
114             ContextBuilder contextBuilder = new ContextBuilder()
115                     .setName(Map.of(contextName.key(), contextName))
116                     .setUuid(
117                         new Uuid(UUID.nameUUIDFromBytes(TAPI_CONTEXT.getBytes(Charset.forName("UTF-8"))).toString()))
118                     .setServiceInterfacePoint(new HashMap<>())
119                     .addAugmentation(connectivityContext)
120                     .addAugmentation(topologyContext)
121                     .addAugmentation(notificationContext);
122
123             // todo: add notification context
124             InstanceIdentifier<Context> contextIID = InstanceIdentifier.builder(Context.class).build();
125             // put in datastore
126             this.networkTransactionService.put(LogicalDatastoreType.OPERATIONAL, contextIID, contextBuilder.build());
127             this.networkTransactionService.commit().get();
128             LOG.info("TAPI context created successfully.");
129         } catch (InterruptedException | ExecutionException e) {
130             LOG.error("Failed to create TAPI context", e);
131         }
132     }
133
134     public Context getTapiContext() {
135         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
136         //  There is no Identifiable in Context model
137         InstanceIdentifier<Context> contextIID = InstanceIdentifier.builder(Context.class).build();
138         try {
139             Optional<Context> optionalContext = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL,
140                     contextIID).get();
141             if (!optionalContext.isPresent()) {
142                 LOG.error("Tapi context is not present in datastore");
143                 return null;
144             }
145             return optionalContext.orElseThrow();
146         } catch (InterruptedException | ExecutionException e) {
147             LOG.error("Couldnt read tapi context from datastore", e);
148             return null;
149         }
150     }
151
152     public void deleteTapiContext() {
153
154     }
155
156     public void updateTopologyContext(Map<TopologyKey, Topology> topologyMap) {
157         // TODO: solve error when merging: Topology is not a valid child of topology context?
158         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
159         try {
160             TopologyContext topologyContext = new TopologyContextBuilder()
161                     //.setNwTopologyService(new NwTopologyServiceBuilder().build())
162                     .setTopology(topologyMap)
163                     .build();
164             InstanceIdentifier<TopologyContext> topologycontextIID =
165                     InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
166                             .onf.otcc.yang.tapi.topology.rev221121.Context1.class)
167                             .child(TopologyContext.class)
168                             .build();
169             // merge in datastore
170             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, topologycontextIID,
171                     topologyContext);
172             this.networkTransactionService.commit().get();
173             LOG.info("TAPI topology merged successfully.");
174         } catch (InterruptedException | ExecutionException e) {
175             LOG.error("Failed to merge TAPI topology", e);
176         }
177     }
178
179     public void updateSIPContext(Map<ServiceInterfacePointKey, ServiceInterfacePoint> sipMap) {
180         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
181         try {
182             ContextBuilder contextBuilder = new ContextBuilder().setServiceInterfacePoint(sipMap);
183             InstanceIdentifier<Context> contextIID = InstanceIdentifier.builder(Context.class).build();
184             // merge in datastore
185             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, contextIID,
186                     contextBuilder.build());
187             this.networkTransactionService.commit().get();
188             LOG.info("TAPI SIPs merged successfully.");
189         } catch (InterruptedException | ExecutionException e) {
190             LOG.error("Failed to merge TAPI SIPs", e);
191         }
192     }
193
194     public void updateConnectivityContext(Map<ConnectivityServiceKey, ConnectivityService> connServMap,
195                                           Map<ConnectionKey, Connection> connectionFullMap) {
196         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
197         try {
198             org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext
199                 connectivityContext = new ConnectivityContextBuilder()
200                 .setConnectivityService(connServMap)
201                 .setConnection(connectionFullMap)
202                 .build();
203             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn
204                 .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext> connectivitycontextIID =
205                     InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
206                         .child(org.opendaylight.yang.gen.v1.urn
207                             .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
208                         .build();
209             // merge in datastore
210             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connectivitycontextIID,
211                 connectivityContext);
212             this.networkTransactionService.commit().get();
213             LOG.info("TAPI connectivity merged successfully.");
214         } catch (InterruptedException | ExecutionException e) {
215             LOG.error("Failed to merge TAPI connectivity", e);
216         }
217     }
218
219     public void updateTopologyWithCep(Uuid topoUuid, Uuid nodeUuid, Uuid nepUuid, ConnectionEndPoint cep) {
220         // TODO: verify this is correct. Should we identify the context IID with the context UUID??
221         InstanceIdentifier<OwnedNodeEdgePoint> onepIID = InstanceIdentifier.builder(Context.class)
222             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1.class)
223             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext.class)
224             .child(Topology.class, new TopologyKey(topoUuid))
225             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Node.class,
226                     new NodeKey(nodeUuid))
227             .child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(nepUuid))
228             .build();
229         try {
230             Optional<OwnedNodeEdgePoint> optionalOnep = this.networkTransactionService.read(
231                     LogicalDatastoreType.OPERATIONAL, onepIID).get();
232             if (!optionalOnep.isPresent()) {
233                 LOG.error("ONEP is not present in datastore");
234                 return;
235             }
236             OwnedNodeEdgePoint onep = optionalOnep.orElseThrow();
237             LOG.info("ONEP found = {}", onep);
238             // TODO -> If cep exists -> skip merging to datasore
239             OwnedNodeEdgePoint1 onep1 = onep.augmentation(OwnedNodeEdgePoint1.class);
240             if (onep1 != null && onep1.getCepList() != null && onep1.getCepList().getConnectionEndPoint() != null
241                     && onep1.getCepList().getConnectionEndPoint().containsKey(new ConnectionEndPointKey(cep.key()))) {
242                 LOG.info("CEP already in topology, skipping merge");
243                 return;
244             }
245             // Updated ONEP
246             CepList cepList = new CepListBuilder().setConnectionEndPoint(Map.of(cep.key(), cep)).build();
247             OwnedNodeEdgePoint1 onep1Bldr = new OwnedNodeEdgePoint1Builder().setCepList(cepList).build();
248             OwnedNodeEdgePoint newOnep = new OwnedNodeEdgePointBuilder(onep)
249                     .addAugmentation(onep1Bldr)
250                     .build();
251             LOG.info("New ONEP is {}", newOnep);
252             // merge in datastore
253             this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, onepIID,
254                     newOnep);
255             this.networkTransactionService.commit().get();
256             LOG.info("CEP added successfully.");
257         } catch (InterruptedException | ExecutionException e) {
258             LOG.error("Couldnt update cep in topology", e);
259         }
260     }
261
262     public Node getTapiNode(Uuid topoUuid, Uuid nodeUuid) {
263         InstanceIdentifier<Node> nodeIID = InstanceIdentifier.builder(Context.class)
264             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1.class)
265             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext.class)
266             .child(Topology.class, new TopologyKey(topoUuid))
267             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Node.class,
268                         new NodeKey(nodeUuid)).build();
269         try {
270             Optional<Node> optNode = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, nodeIID)
271                     .get();
272             if (!optNode.isPresent()) {
273                 LOG.error(NODE_NOT_PRESENT);
274                 return null;
275             }
276             // TODO -> Need to remove CEPs from NEPs. If not error from get Topology details output
277             Node node = optNode.orElseThrow();
278             LOG.debug("NEPs of node before creating map to be returned to the getTapiNode function = {}",
279                 node.getOwnedNodeEdgePoint().size());
280             Map<OwnedNodeEdgePointKey, OwnedNodeEdgePoint> onepMap = new HashMap<>();
281             for (OwnedNodeEdgePoint onep: node.getOwnedNodeEdgePoint().values()) {
282                 if (onep.augmentation(OwnedNodeEdgePoint1.class) == null) {
283                     onepMap.put(onep.key(), onep);
284                     continue;
285                 }
286                 OwnedNodeEdgePointBuilder newOnepBuilder = new OwnedNodeEdgePointBuilder()
287                     .setUuid(onep.getUuid())
288                     .setLayerProtocolName(onep.getLayerProtocolName())
289                     .setName(onep.getName())
290                     .setSupportedCepLayerProtocolQualifierInstances(
291                         onep.getSupportedCepLayerProtocolQualifierInstances())
292                     .setAdministrativeState(onep.getAdministrativeState())
293                     .setOperationalState(onep.getOperationalState())
294                     .setLifecycleState(onep.getLifecycleState())
295 //                    .setTerminationDirection(onep.getTerminationDirection())
296 //                    .setTerminationState(onep.getTerminationState())
297                     .setDirection(onep.getDirection())
298                     .setLinkPortRole(onep.getLinkPortRole());
299                 if (onep.getMappedServiceInterfacePoint() != null) {
300                     newOnepBuilder.setMappedServiceInterfacePoint(onep.getMappedServiceInterfacePoint());
301                 }
302                 OwnedNodeEdgePoint newOnep = newOnepBuilder.build();
303                 onepMap.put(newOnep.key(), newOnep);
304             }
305             LOG.debug("NEPs of node after creating map to be returned to the getTapiNode function = {}",
306                 onepMap.size());
307             return new NodeBuilder(node)
308                 .setOwnedNodeEdgePoint(onepMap)
309                 .build();
310         } catch (InterruptedException | ExecutionException e) {
311             LOG.error("Couldnt read node in topology", e);
312             return null;
313         }
314     }
315
316     public OwnedNodeEdgePoint getTapiNEP(Uuid topoUuid, Uuid nodeUuid, Uuid nepUuid) {
317         InstanceIdentifier<OwnedNodeEdgePoint> nepIID = InstanceIdentifier.builder(Context.class)
318             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1.class)
319             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext.class)
320             .child(Topology.class, new TopologyKey(topoUuid))
321             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Node.class,
322                 new NodeKey(nodeUuid)).child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(nepUuid)).build();
323         try {
324             Optional<OwnedNodeEdgePoint> optNode = this.networkTransactionService
325                     .read(LogicalDatastoreType.OPERATIONAL, nepIID)
326                     .get();
327             if (!optNode.isPresent()) {
328                 LOG.error(NODE_NOT_PRESENT);
329                 return null;
330             }
331             return optNode.orElseThrow();
332         } catch (InterruptedException | ExecutionException e) {
333             LOG.error("Couldnt read NEP in topology", e);
334             return null;
335         }
336     }
337
338     public Link getTapiLink(Uuid topoUuid, Uuid linkUuid) {
339         InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Context.class)
340             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1.class)
341             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext.class)
342             .child(Topology.class, new TopologyKey(topoUuid))
343             .child(Link.class, new LinkKey(linkUuid)).build();
344         try {
345             Optional<Link> optLink = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, linkIID)
346                     .get();
347             if (!optLink.isPresent()) {
348                 LOG.error(NODE_NOT_PRESENT);
349                 return null;
350             }
351             return optLink.orElseThrow();
352         } catch (InterruptedException | ExecutionException e) {
353             LOG.error("Couldnt read link in topology", e);
354             return null;
355         }
356     }
357
358     public Map<TopologyKey, Topology> getTopologyContext() {
359         InstanceIdentifier<TopologyContext> topologycontextIID =
360                 InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
361                         .onf.otcc.yang.tapi.topology.rev221121.Context1.class)
362                         .child(TopologyContext.class)
363                         .build();
364         try {
365             Optional<TopologyContext> optTopoContext = this.networkTransactionService.read(
366                     LogicalDatastoreType.OPERATIONAL, topologycontextIID).get();
367             if (!optTopoContext.isPresent()) {
368                 LOG.error("Topology context is not present in datastore");
369                 return null;
370             }
371             return optTopoContext.orElseThrow().getTopology();
372         } catch (InterruptedException | ExecutionException e) {
373             LOG.error("Couldnt read topology context", e);
374             return null;
375         }
376     }
377
378     public ConnectivityService getConnectivityService(Uuid serviceUuid) {
379         try {
380             // First read connectivity service with service uuid and update info
381             InstanceIdentifier<ConnectivityService> connectivityServIID =
382                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
383                     .child(org.opendaylight.yang.gen.v1.urn
384                         .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
385                     .child(ConnectivityService.class, new ConnectivityServiceKey(serviceUuid))
386                     .build();
387
388             Optional<ConnectivityService> optConnServ =
389                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityServIID).get();
390             if (!optConnServ.isPresent()) {
391                 LOG.error("Connectivity service not found in tapi context");
392                 return null;
393             }
394             return optConnServ.orElseThrow();
395         } catch (InterruptedException | ExecutionException e) {
396             LOG.error("Connectivity service not found in tapi context. Error:", e);
397             return null;
398         }
399     }
400
401     public void deleteConnectivityService(Uuid serviceUuid) {
402         // TODO: handle case where the infrastructure service is removed before the top level service?
403         ConnectivityService connectivityService = getConnectivityService(serviceUuid);
404         if (connectivityService == null) {
405             LOG.error("Service doesnt exist in tapi context");
406             return;
407         }
408         for (org.opendaylight.yang.gen.v1
409                 .urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.service.Connection connection:
410                     connectivityService.getConnection().values()) {
411             deleteConnection(connection.getConnectionUuid(), serviceUuid, connectivityService.getLayerProtocolName());
412         }
413         InstanceIdentifier<ConnectivityService> connectivityServIID =
414                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
415                         .child(org.opendaylight.yang.gen.v1.urn
416                                 .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
417                         .child(ConnectivityService.class, new ConnectivityServiceKey(serviceUuid))
418                         .build();
419         try {
420             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectivityServIID);
421             this.networkTransactionService.commit().get();
422             LOG.info("Connectivity service deleted");
423         } catch (InterruptedException | ExecutionException e) {
424             LOG.error("Failed to delete Connectivity service", e);
425         }
426     }
427
428     private void deleteConnection(Uuid connectionUuid, Uuid serviceUuid, LayerProtocolName serviceLayer) {
429         // First read connectivity service with service uuid and update info
430         InstanceIdentifier<org.opendaylight.yang.gen.v1
431             .urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.Connection> connectionIID =
432             InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
433                 .child(org.opendaylight.yang.gen.v1.urn
434                     .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
435                 .child(org.opendaylight.yang.gen.v1.urn
436                         .onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.Connection.class,
437                     new org.opendaylight.yang.gen.v1.urn
438                         .onf.otcc.yang.tapi.connectivity.rev221121.connectivity.context.ConnectionKey(
439                         connectionUuid))
440                 .build();
441         Connection connection = getConnection(connectionUuid);
442         if (connection != null && isNotUsedByOtherService(connection, serviceUuid)) {
443             Map<LowerConnectionKey, LowerConnection> lowerConnectionMap = connection.getLowerConnection();
444             if (lowerConnectionMap != null) {
445                 for (LowerConnection lowerConnection:lowerConnectionMap.values()) {
446                     // check layer of connection, for DSR service we only need to delete DSR layer
447                     // connection and XC at ODU. For ODU, only need to delete ODU connections and for
448                     // photonic media services all the photonic media. And when it is ETH we need to delete
449                     // everything and also without checking the lower connection layer
450                     Connection conn1 = getConnection(lowerConnection.getConnectionUuid());
451                     if (conn1 == null) {
452                         // connection not found in tapi context
453                         continue;
454                     }
455                     LayerProtocolName lowerConnLayer = conn1.getLayerProtocolName();
456                     switch (serviceLayer.getIntValue()) {
457                         case 0:
458                         case 3:
459                             // PHOTONIC & ODU
460                             if (lowerConnLayer.equals(serviceLayer)) {
461                                 deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
462                             }
463                             break;
464                         case 1:
465                             // ETH
466                             deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
467                             break;
468                         case 2:
469                             // DSR
470                             if (lowerConnLayer.equals(serviceLayer) || (lowerConnLayer.equals(LayerProtocolName.ODU)
471                                     && conn1.getName().values().stream().anyMatch(
472                                             name -> name.getValue().contains("XC")))) {
473                                 deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
474                             }
475                             break;
476                         default:
477                             LOG.info("Unknown service Layer: {}", serviceLayer.getName());
478                     }
479                 }
480             }
481         }
482         try {
483             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectionIID);
484             this.networkTransactionService.commit().get();
485         } catch (InterruptedException | ExecutionException e) {
486             LOG.error("Failed to delete TAPI Connection", e);
487         }
488     }
489
490     private boolean isNotUsedByOtherService(Connection connection, Uuid serviceUuid) {
491         Map<ConnectivityServiceKey, ConnectivityService> connServicesMap = getConnectivityServices();
492         if (connServicesMap == null) {
493             LOG.info("isNotUsedByOtherService: No service in tapi context!");
494             return true;
495         }
496         for (ConnectivityService connService: connServicesMap.values()) {
497             if (connService.getConnection() == null || connService.getUuid().equals(serviceUuid)) {
498                 LOG.info("isNotUsedByOtherService: There are no connections in service {} or service in loop is the "
499                         + "service to be deleted", connService.getUuid().getValue());
500                 continue;
501             }
502             if (connService.getConnection().containsKey(
503                     new org.opendaylight.yang.gen.v1
504                         .urn.onf.otcc.yang.tapi.connectivity.rev221121.connectivity.service.ConnectionKey(
505                             connection.getUuid()))) {
506                 LOG.info("isNotUsedByOtherService: Connection {} is in used by service {}. Cannot remove it from "
507                         + "context", connection.getUuid().getValue(), connService.getUuid().getValue());
508                 return false;
509             }
510             LOG.info("isNotUsedByOtherService: Going to check lower connections");
511             for (org.opendaylight.yang.gen.v1.urn
512                         .onf.otcc.yang.tapi.connectivity.rev221121.connectivity.service.Connection
513                     conn:connService.getConnection().values()) {
514                 Connection connection1 = getConnection(conn.getConnectionUuid());
515                 if (connection1 == null || connection1.getLowerConnection() == null) {
516                     continue;
517                 }
518                 if (connection1.getLowerConnection().containsKey(new LowerConnectionKey(connection.getUuid()))) {
519                     LOG.info("isNotUsedByOtherService: Lower Connection {} is in used by service {}. Cannot remove it "
520                             + "from context", connection.getUuid().getValue(), connService.getUuid().getValue());
521                     return false;
522                 }
523             }
524         }
525         LOG.info("isNotUsedByOtherService: No other service uses connection {}, therefore it can be safely deleted",
526                 connection.getUuid());
527         return true;
528     }
529
530     public Connection getConnection(Uuid connectionUuid) {
531         try {
532             // First read connectivity service with service uuid and update info
533             InstanceIdentifier<Connection> connIID =
534                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
535                     .child(org.opendaylight.yang.gen.v1.urn
536                         .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
537                     .child(Connection.class, new ConnectionKey(connectionUuid))
538                     .build();
539
540             Optional<Connection> optConn =
541                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connIID).get();
542             if (!optConn.isPresent()) {
543                 LOG.error("Connection not found in tapi context");
544                 return null;
545             }
546             return optConn.orElseThrow();
547         } catch (InterruptedException | ExecutionException e) {
548             LOG.error("Connection not found in tapi context. Error:", e);
549             return null;
550         }
551     }
552
553     public Map<ConnectivityServiceKey, ConnectivityService> getConnectivityServices() {
554         try {
555             // First read connectivity service with service uuid and update info
556             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn
557                 .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext> connectivityContextIID =
558                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
559                     .child(org.opendaylight.yang.gen.v1.urn
560                         .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext.class)
561                     .build();
562
563             Optional<org.opendaylight.yang.gen.v1.urn
564                 .onf.otcc.yang.tapi.connectivity.rev221121.context.ConnectivityContext> optConnContext =
565                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityContextIID)
566                         .get();
567             if (!optConnContext.isPresent()) {
568                 LOG.error("Connectivity context not found in tapi context");
569                 return null;
570             }
571             return optConnContext.orElseThrow().getConnectivityService();
572         } catch (InterruptedException | ExecutionException e) {
573             LOG.error("Connectivity context not found in tapi context. Error:", e);
574             return null;
575         }
576     }
577
578     public ConnectionEndPoint getTapiCEP(Uuid topoUuid, Uuid nodeUuid, Uuid nepUuid, Uuid cepUuid) {
579         InstanceIdentifier<OwnedNodeEdgePoint> nepIID = InstanceIdentifier.builder(Context.class)
580             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.Context1.class)
581             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.context.TopologyContext.class)
582             .child(Topology.class, new TopologyKey(topoUuid))
583             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev221121.topology.Node.class,
584                 new NodeKey(nodeUuid)).child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(nepUuid)).build();
585         try {
586             Optional<OwnedNodeEdgePoint> optNode = this.networkTransactionService
587                 .read(LogicalDatastoreType.OPERATIONAL, nepIID).get();
588             if (!optNode.isPresent()) {
589                 LOG.error(NODE_NOT_PRESENT);
590                 return null;
591             }
592             if (optNode.orElseThrow().augmentation(OwnedNodeEdgePoint1.class) == null) {
593                 LOG.error("Node doesnt have ceps");
594                 return null;
595             }
596             return optNode.orElseThrow().augmentation(OwnedNodeEdgePoint1.class).getCepList().getConnectionEndPoint()
597                 .get(new ConnectionEndPointKey(cepUuid));
598         } catch (InterruptedException | ExecutionException e) {
599             LOG.error("Couldnt read node in topology", e);
600             return null;
601         }
602     }
603 }