12ee2b61cef827e5722862bc71fc81265d86dd8a
[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.rev181210.Context;
19 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.ContextBuilder;
20 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LayerProtocolName;
21 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Uuid;
22 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.Name;
23 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.NameBuilder;
24 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.tapi.context.ServiceInterfacePoint;
25 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.tapi.context.ServiceInterfacePointKey;
26 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1;
27 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1Builder;
28 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.OwnedNodeEdgePoint1;
29 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.OwnedNodeEdgePoint1Builder;
30 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.cep.list.ConnectionEndPoint;
31 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.cep.list.ConnectionEndPointKey;
32 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connection.LowerConnection;
33 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connection.LowerConnectionKey;
34 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection;
35 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey;
36 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityService;
37 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceKey;
38 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContextBuilder;
39 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.context.topology.context.topology.node.owned.node.edge.point.CepList;
40 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.context.topology.context.topology.node.owned.node.edge.point.CepListBuilder;
41 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.context.NotificationContextBuilder;
42 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext;
43 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContextBuilder;
44 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePoint;
45 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePointBuilder;
46 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePointKey;
47 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Link;
48 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.LinkKey;
49 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Node;
50 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.NodeBuilder;
51 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.NodeKey;
52 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.NwTopologyServiceBuilder;
53 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.Topology;
54 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.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.rev181210.Context1 topologyContext
92                 = new org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.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.rev181210.Context1 notificationContext
107                 = new org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.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.rev181210.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.rev181210.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.rev181210.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.rev181210.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.rev181210.Context1.class)
223             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext.class)
224             .child(Topology.class, new TopologyKey(topoUuid))
225             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.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.rev181210.Context1.class)
265             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext.class)
266             .child(Topology.class, new TopologyKey(topoUuid))
267             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.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                     .setSupportedCepLayerProtocolQualifier(onep.getSupportedCepLayerProtocolQualifier())
291                     .setAdministrativeState(onep.getAdministrativeState())
292                     .setOperationalState(onep.getOperationalState())
293                     .setLifecycleState(onep.getLifecycleState())
294                     .setTerminationDirection(onep.getTerminationDirection())
295                     .setTerminationState(onep.getTerminationState())
296                     .setLinkPortDirection(onep.getLinkPortDirection())
297                     .setLinkPortRole(onep.getLinkPortRole());
298                 if (onep.getMappedServiceInterfacePoint() != null) {
299                     newOnepBuilder.setMappedServiceInterfacePoint(onep.getMappedServiceInterfacePoint());
300                 }
301                 OwnedNodeEdgePoint newOnep = newOnepBuilder.build();
302                 onepMap.put(newOnep.key(), newOnep);
303             }
304             LOG.debug("NEPs of node after creating map to be returned to the getTapiNode function = {}",
305                 onepMap.size());
306             return new NodeBuilder(node)
307                 .setOwnedNodeEdgePoint(onepMap)
308                 .build();
309         } catch (InterruptedException | ExecutionException e) {
310             LOG.error("Couldnt read node in topology", e);
311             return null;
312         }
313     }
314
315     public OwnedNodeEdgePoint getTapiNEP(Uuid topoUuid, Uuid nodeUuid, Uuid nepUuid) {
316         InstanceIdentifier<OwnedNodeEdgePoint> nepIID = InstanceIdentifier.builder(Context.class)
317             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.Context1.class)
318             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext.class)
319             .child(Topology.class, new TopologyKey(topoUuid))
320             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Node.class,
321                 new NodeKey(nodeUuid)).child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(nepUuid)).build();
322         try {
323             Optional<OwnedNodeEdgePoint> optNode = this.networkTransactionService
324                     .read(LogicalDatastoreType.OPERATIONAL, nepIID)
325                     .get();
326             if (!optNode.isPresent()) {
327                 LOG.error(NODE_NOT_PRESENT);
328                 return null;
329             }
330             return optNode.orElseThrow();
331         } catch (InterruptedException | ExecutionException e) {
332             LOG.error("Couldnt read NEP in topology", e);
333             return null;
334         }
335     }
336
337     public Link getTapiLink(Uuid topoUuid, Uuid linkUuid) {
338         InstanceIdentifier<Link> linkIID = InstanceIdentifier.builder(Context.class)
339             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.Context1.class)
340             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext.class)
341             .child(Topology.class, new TopologyKey(topoUuid))
342             .child(Link.class, new LinkKey(linkUuid)).build();
343         try {
344             Optional<Link> optLink = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, linkIID)
345                     .get();
346             if (!optLink.isPresent()) {
347                 LOG.error(NODE_NOT_PRESENT);
348                 return null;
349             }
350             return optLink.orElseThrow();
351         } catch (InterruptedException | ExecutionException e) {
352             LOG.error("Couldnt read link in topology", e);
353             return null;
354         }
355     }
356
357     public Map<TopologyKey, Topology> getTopologyContext() {
358         InstanceIdentifier<TopologyContext> topologycontextIID =
359                 InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
360                         .onf.otcc.yang.tapi.topology.rev181210.Context1.class)
361                         .child(TopologyContext.class)
362                         .build();
363         try {
364             Optional<TopologyContext> optTopoContext = this.networkTransactionService.read(
365                     LogicalDatastoreType.OPERATIONAL, topologycontextIID).get();
366             if (!optTopoContext.isPresent()) {
367                 LOG.error("Topology context is not present in datastore");
368                 return null;
369             }
370             return optTopoContext.orElseThrow().getTopology();
371         } catch (InterruptedException | ExecutionException e) {
372             LOG.error("Couldnt read topology context", e);
373             return null;
374         }
375     }
376
377     public ConnectivityService getConnectivityService(Uuid serviceUuid) {
378         try {
379             // First read connectivity service with service uuid and update info
380             InstanceIdentifier<ConnectivityService> connectivityServIID =
381                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
382                     .child(org.opendaylight.yang.gen.v1.urn
383                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
384                     .child(ConnectivityService.class, new ConnectivityServiceKey(serviceUuid))
385                     .build();
386
387             Optional<ConnectivityService> optConnServ =
388                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityServIID).get();
389             if (!optConnServ.isPresent()) {
390                 LOG.error("Connectivity service not found in tapi context");
391                 return null;
392             }
393             return optConnServ.orElseThrow();
394         } catch (InterruptedException | ExecutionException e) {
395             LOG.error("Connectivity service not found in tapi context. Error:", e);
396             return null;
397         }
398     }
399
400     public void deleteConnectivityService(Uuid serviceUuid) {
401         // TODO: handle case where the infrastructure service is removed before the top level service?
402         ConnectivityService connectivityService = getConnectivityService(serviceUuid);
403         if (connectivityService == null) {
404             LOG.error("Service doesnt exist in tapi context");
405             return;
406         }
407         for (org.opendaylight.yang.gen.v1
408                 .urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.Connection connection:
409                     connectivityService.getConnection().values()) {
410             deleteConnection(connection.getConnectionUuid(), serviceUuid, connectivityService.getServiceLayer());
411         }
412         InstanceIdentifier<ConnectivityService> connectivityServIID =
413                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
414                         .child(org.opendaylight.yang.gen.v1.urn
415                                 .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
416                         .child(ConnectivityService.class, new ConnectivityServiceKey(serviceUuid))
417                         .build();
418         try {
419             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectivityServIID);
420             this.networkTransactionService.commit().get();
421             LOG.info("Connectivity service deleted");
422         } catch (InterruptedException | ExecutionException e) {
423             LOG.error("Failed to delete Connectivity service", e);
424         }
425     }
426
427     private void deleteConnection(Uuid connectionUuid, Uuid serviceUuid, LayerProtocolName serviceLayer) {
428         // First read connectivity service with service uuid and update info
429         InstanceIdentifier<org.opendaylight.yang.gen.v1
430             .urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection> connectionIID =
431             InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
432                 .child(org.opendaylight.yang.gen.v1.urn
433                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
434                 .child(org.opendaylight.yang.gen.v1.urn
435                         .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection.class,
436                     new org.opendaylight.yang.gen.v1.urn
437                         .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey(
438                         connectionUuid))
439                 .build();
440         Connection connection = getConnection(connectionUuid);
441         if (connection != null && isNotUsedByOtherService(connection, serviceUuid)) {
442             Map<LowerConnectionKey, LowerConnection> lowerConnectionMap = connection.getLowerConnection();
443             if (lowerConnectionMap != null) {
444                 for (LowerConnection lowerConnection:lowerConnectionMap.values()) {
445                     // check layer of connection, for DSR service we only need to delete DSR layer
446                     // connection and XC at ODU. For ODU, only need to delete ODU connections and for
447                     // photonic media services all the photonic media. And when it is ETH we need to delete
448                     // everything and also without checking the lower connection layer
449                     Connection conn1 = getConnection(lowerConnection.getConnectionUuid());
450                     if (conn1 == null) {
451                         // connection not found in tapi context
452                         continue;
453                     }
454                     LayerProtocolName lowerConnLayer = conn1.getLayerProtocolName();
455                     switch (serviceLayer.getIntValue()) {
456                         case 0:
457                         case 3:
458                             // PHOTONIC & ODU
459                             if (lowerConnLayer.equals(serviceLayer)) {
460                                 deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
461                             }
462                             break;
463                         case 1:
464                             // ETH
465                             deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
466                             break;
467                         case 2:
468                             // DSR
469                             if (lowerConnLayer.equals(serviceLayer) || (lowerConnLayer.equals(LayerProtocolName.ODU)
470                                     && conn1.getName().values().stream().anyMatch(
471                                             name -> name.getValue().contains("XC")))) {
472                                 deleteConnection(lowerConnection.getConnectionUuid(), serviceUuid, serviceLayer);
473                             }
474                             break;
475                         default:
476                             LOG.info("Unknown service Layer: {}", serviceLayer.getName());
477                     }
478                 }
479             }
480         }
481         try {
482             this.networkTransactionService.delete(LogicalDatastoreType.OPERATIONAL, connectionIID);
483             this.networkTransactionService.commit().get();
484         } catch (InterruptedException | ExecutionException e) {
485             LOG.error("Failed to delete TAPI Connection", e);
486         }
487     }
488
489     private boolean isNotUsedByOtherService(Connection connection, Uuid serviceUuid) {
490         Map<ConnectivityServiceKey, ConnectivityService> connServicesMap = getConnectivityServices();
491         if (connServicesMap == null) {
492             LOG.info("isNotUsedByOtherService: No service in tapi context!");
493             return true;
494         }
495         for (ConnectivityService connService: connServicesMap.values()) {
496             if (connService.getConnection() == null || connService.getUuid().equals(serviceUuid)) {
497                 LOG.info("isNotUsedByOtherService: There are no connections in service {} or service in loop is the "
498                         + "service to be deleted", connService.getUuid().getValue());
499                 continue;
500             }
501             if (connService.getConnection().containsKey(
502                     new org.opendaylight.yang.gen.v1
503                         .urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.ConnectionKey(
504                             connection.getUuid()))) {
505                 LOG.info("isNotUsedByOtherService: Connection {} is in used by service {}. Cannot remove it from "
506                         + "context", connection.getUuid().getValue(), connService.getUuid().getValue());
507                 return false;
508             }
509             LOG.info("isNotUsedByOtherService: Going to check lower connections");
510             for (org.opendaylight.yang.gen.v1.urn
511                         .onf.otcc.yang.tapi.connectivity.rev181210.connectivity.service.Connection
512                     conn:connService.getConnection().values()) {
513                 Connection connection1 = getConnection(conn.getConnectionUuid());
514                 if (connection1 == null || connection1.getLowerConnection() == null) {
515                     continue;
516                 }
517                 if (connection1.getLowerConnection().containsKey(new LowerConnectionKey(connection.getUuid()))) {
518                     LOG.info("isNotUsedByOtherService: Lower Connection {} is in used by service {}. Cannot remove it "
519                             + "from context", connection.getUuid().getValue(), connService.getUuid().getValue());
520                     return false;
521                 }
522             }
523         }
524         LOG.info("isNotUsedByOtherService: No other service uses connection {}, therefore it can be safely deleted",
525                 connection.getUuid());
526         return true;
527     }
528
529     public Connection getConnection(Uuid connectionUuid) {
530         try {
531             // First read connectivity service with service uuid and update info
532             InstanceIdentifier<Connection> connIID =
533                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
534                     .child(org.opendaylight.yang.gen.v1.urn
535                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
536                     .child(Connection.class, new ConnectionKey(connectionUuid))
537                     .build();
538
539             Optional<Connection> optConn =
540                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connIID).get();
541             if (!optConn.isPresent()) {
542                 LOG.error("Connection not found in tapi context");
543                 return null;
544             }
545             return optConn.orElseThrow();
546         } catch (InterruptedException | ExecutionException e) {
547             LOG.error("Connection not found in tapi context. Error:", e);
548             return null;
549         }
550     }
551
552     public Map<ConnectivityServiceKey, ConnectivityService> getConnectivityServices() {
553         try {
554             // First read connectivity service with service uuid and update info
555             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn
556                 .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext> connectivityContextIID =
557                 InstanceIdentifier.builder(Context.class).augmentation(Context1.class)
558                     .child(org.opendaylight.yang.gen.v1.urn
559                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
560                     .build();
561
562             Optional<org.opendaylight.yang.gen.v1.urn
563                 .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext> optConnContext =
564                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityContextIID)
565                         .get();
566             if (!optConnContext.isPresent()) {
567                 LOG.error("Connectivity context not found in tapi context");
568                 return null;
569             }
570             return optConnContext.orElseThrow().getConnectivityService();
571         } catch (InterruptedException | ExecutionException e) {
572             LOG.error("Connectivity context not found in tapi context. Error:", e);
573             return null;
574         }
575     }
576
577     public ConnectionEndPoint getTapiCEP(Uuid topoUuid, Uuid nodeUuid, Uuid nepUuid, Uuid cepUuid) {
578         InstanceIdentifier<OwnedNodeEdgePoint> nepIID = InstanceIdentifier.builder(Context.class)
579             .augmentation(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.Context1.class)
580             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext.class)
581             .child(Topology.class, new TopologyKey(topoUuid))
582             .child(org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Node.class,
583                 new NodeKey(nodeUuid)).child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(nepUuid)).build();
584         try {
585             Optional<OwnedNodeEdgePoint> optNode = this.networkTransactionService
586                 .read(LogicalDatastoreType.OPERATIONAL, nepIID).get();
587             if (!optNode.isPresent()) {
588                 LOG.error(NODE_NOT_PRESENT);
589                 return null;
590             }
591             if (optNode.orElseThrow().augmentation(OwnedNodeEdgePoint1.class) == null) {
592                 LOG.error("Node doesnt have ceps");
593                 return null;
594             }
595             return optNode.orElseThrow().augmentation(OwnedNodeEdgePoint1.class).getCepList().getConnectionEndPoint()
596                 .get(new ConnectionEndPointKey(cepUuid));
597         } catch (InterruptedException | ExecutionException e) {
598             LOG.error("Couldnt read node in topology", e);
599             return null;
600         }
601     }
602 }