Initial tapi notification implementation
[transportpce.git] / tapi / src / main / java / org / opendaylight / transportpce / tapi / listeners / TapiNetworkModelListenerImpl.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.listeners;
9
10 import java.nio.charset.StandardCharsets;
11 import java.time.OffsetDateTime;
12 import java.time.ZoneOffset;
13 import java.time.format.DateTimeFormatter;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Objects;
21 import java.util.Optional;
22 import java.util.UUID;
23 import java.util.concurrent.ExecutionException;
24 import java.util.stream.Collectors;
25 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.transportpce.common.network.NetworkTransactionService;
28 import org.opendaylight.transportpce.tapi.TapiStringConstants;
29 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
30 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.PublishTapiNotificationService;
31 import org.opendaylight.yang.gen.v1.nbi.notifications.rev211013.PublishTapiNotificationServiceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.AdministrativeState;
33 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Context;
34 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.DateAndTime;
35 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.LayerProtocolName;
36 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.OperationalState;
37 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.Uuid;
38 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.Name;
39 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.common.rev181210.global._class.NameKey;
40 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.OwnedNodeEdgePoint1;
41 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connection.LowerConnection;
42 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.Connection;
43 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionBuilder;
44 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectionKey;
45 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityService;
46 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceBuilder;
47 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.connectivity.context.ConnectivityServiceKey;
48 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext;
49 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.NameAndValueChange;
50 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.Notification;
51 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.NotificationType;
52 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.ObjectType;
53 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.TapiNotificationListener;
54 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.ChangedAttributes;
55 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.ChangedAttributesBuilder;
56 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.ChangedAttributesKey;
57 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.TargetObjectName;
58 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.TargetObjectNameBuilder;
59 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.notification.rev181210.notification.TargetObjectNameKey;
60 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.Context1;
61 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.NodeEdgePointRef;
62 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.context.TopologyContext;
63 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePoint;
64 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.node.OwnedNodeEdgePointKey;
65 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.Node;
66 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.NodeKey;
67 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.Topology;
68 import org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.topology.rev181210.topology.context.TopologyKey;
69 import org.opendaylight.yangtools.yang.binding.Enumeration;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 public class TapiNetworkModelListenerImpl implements TapiNotificationListener {
75
76     private static final Logger LOG = LoggerFactory.getLogger(TapiNetworkModelListenerImpl.class);
77     private final NetworkTransactionService networkTransactionService;
78     private final List<ConnectivityService> connectivityServiceChanges = new ArrayList<>();
79     private final Uuid tapiTopoUuid = new Uuid(UUID.nameUUIDFromBytes(TapiStringConstants.T0_FULL_MULTILAYER
80             .getBytes(StandardCharsets.UTF_8)).toString());
81     private final List<LayerProtocolName> orderedServiceLayerList;
82     private final NotificationPublishService notificationPublishService;
83
84     public TapiNetworkModelListenerImpl(NetworkTransactionService networkTransactionService,
85                                         NotificationPublishService notificationPublishService) {
86         this.networkTransactionService = networkTransactionService;
87         this.orderedServiceLayerList = List.of(LayerProtocolName.PHOTONICMEDIA, LayerProtocolName.ODU,
88             LayerProtocolName.DSR, LayerProtocolName.ETH);
89         this.notificationPublishService = notificationPublishService;
90     }
91
92     @Override
93     public void onNotification(Notification notification) {
94         LOG.info("Received network model notification {}", notification);
95         if (notification.getNotificationType() == NotificationType.ATTRIBUTEVALUECHANGE
96                 && notification.getTargetObjectType() == ObjectType.NODEEDGEPOINT) {
97             if (notification.getChangedAttributes() == null) {
98                 return;
99             }
100             // TODO: need to re-think this to update first the connections from roadm to roadm and then the others
101             updateConnections(notification.getChangedAttributes().keySet().stream()
102                     .map(changedAttributesKey -> new Uuid(changedAttributesKey.getValueName()))
103                     .collect(Collectors.toList()),
104                 notification.getChangedAttributes().values().stream()
105                     .map(NameAndValueChange::getNewValue)
106                     .collect(Collectors.toList()));
107             updateConnectivityServices();
108             // todo set attributes
109             for (ConnectivityService connService : this.connectivityServiceChanges) {
110                 sendNbiNotification(createNbiNotification(connService));
111             }
112         }
113     }
114
115     private PublishTapiNotificationService createNbiNotification(ConnectivityService connService) {
116         if (connService == null) {
117             LOG.error("ConnService is null");
118             return null;
119         }
120         Map<ChangedAttributesKey, ChangedAttributes> changedStates = new HashMap<>();
121         changedStates.put(new ChangedAttributesKey("administrativeState"),
122             new ChangedAttributesBuilder()
123                 .setNewValue(connService.getAdministrativeState().getName())
124                 .setOldValue(connService.getAdministrativeState().equals(AdministrativeState.UNLOCKED)
125                     ? AdministrativeState.LOCKED.getName() : AdministrativeState.UNLOCKED.getName())
126                 .setValueName("administrativeState").build());
127         changedStates.put(new ChangedAttributesKey("operationalState"),
128             new ChangedAttributesBuilder()
129                 .setNewValue(connService.getOperationalState().getName())
130                 .setOldValue(connService.getOperationalState().equals(OperationalState.ENABLED)
131                     ? OperationalState.DISABLED.getName() : OperationalState.ENABLED.getName())
132                 .setValueName("operationalState").build());
133         DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx");
134         OffsetDateTime offsetDateTime = OffsetDateTime.now(ZoneOffset.UTC);
135         DateAndTime datetime = new DateAndTime(dtf.format(offsetDateTime));
136         Map<TargetObjectNameKey, TargetObjectName> targetObjectNames = new HashMap<>();
137         if (connService.getName() != null) {
138             for (Map.Entry<NameKey, Name> entry : connService.getName().entrySet()) {
139                 targetObjectNames.put(new TargetObjectNameKey(entry.getKey().getValueName()),
140                     new TargetObjectNameBuilder()
141                         .setValueName(entry.getValue().getValueName())
142                         .setValue(entry.getValue().getValue())
143                         .build());
144             }
145         }
146
147         return new PublishTapiNotificationServiceBuilder()
148             .setUuid(new Uuid(UUID.randomUUID().toString()))
149             .setTopic(connService.getUuid().getValue())
150             .setTargetObjectIdentifier(connService.getUuid())
151             .setNotificationType(NotificationType.ATTRIBUTEVALUECHANGE)
152             .setChangedAttributes(changedStates)
153             .setEventTimeStamp(datetime)
154             .setTargetObjectName(targetObjectNames)
155             .setTargetObjectType(ObjectType.CONNECTIVITYSERVICE)
156             .setLayerProtocolName(connService.getServiceLayer())
157             .build();
158     }
159
160     private void sendNbiNotification(PublishTapiNotificationService service) {
161         try {
162             this.notificationPublishService.putNotification(service);
163         } catch (InterruptedException e) {
164             LOG.warn("Cannot send notification to nbi", e);
165             Thread.currentThread().interrupt();
166         }
167     }
168
169     private void updateConnectivityServices() {
170         try {
171             this.connectivityServiceChanges.clear();
172             InstanceIdentifier<ConnectivityContext> connectivityContextIID =
173                 InstanceIdentifier.builder(Context.class).augmentation(
174                         org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
175                     .child(ConnectivityContext.class)
176                     .build();
177             Optional<ConnectivityContext> optConnContext =
178                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityContextIID).get();
179             if (optConnContext.isEmpty()) {
180                 LOG.error("Could not update TAPI connectivity services");
181                 return;
182             }
183             ConnectivityContext connContext = optConnContext.get();
184             Map<Uuid, Enumeration[]> states = new HashMap<>();
185             if (connContext.getConnectivityService() == null) {
186                 return;
187             }
188             for (ConnectivityService connService : connContext.getConnectivityService().values()) {
189                 LOG.info("Connectivity service = {}", connService);
190                 // TODO: maybe we need to check lower connections if my new code doesnt work
191                 states.put(connService.getUuid(), getStates(connService));
192                 AdministrativeState adminState = (AdministrativeState) states.get(connService.getUuid())[0];
193                 OperationalState operState = (OperationalState) states.get(connService.getUuid())[1];
194
195                 InstanceIdentifier<ConnectivityService> connServIID = InstanceIdentifier
196                     .builder(Context.class).augmentation(org.opendaylight.yang.gen.v1
197                                 .urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
198                     .child(ConnectivityContext.class)
199                     .child(ConnectivityService.class, new ConnectivityServiceKey(connService.getUuid()))
200                     .build();
201                 ConnectivityService changedConnServ = new ConnectivityServiceBuilder()
202                     .setUuid(connService.getUuid())
203                     .setAdministrativeState(adminState)
204                     .setOperationalState(operState)
205                     .build();
206                 this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connServIID,
207                     changedConnServ);
208                 this.networkTransactionService.commit().get();
209
210                 if (connService.getAdministrativeState() != adminState
211                     || connService.getOperationalState() != operState) {
212                     this.connectivityServiceChanges.add(changedConnServ);
213                 }
214             }
215             // TODO: this last function may need some refactoring... if the PHOT_MEDIA goes down,
216             //  then ODU goes down and then DSR should also go down
217             for (ConnectivityService connService : connContext.getConnectivityService().values()) {
218                 AdministrativeState adminState = (AdministrativeState) states.get(connService.getUuid())[0];
219                 OperationalState operState = (OperationalState) states.get(connService.getUuid())[1];
220                 this.connectivityServiceChanges.addAll(updateSupportedConnectivityServices(
221                     connContext.getConnectivityService().values(), connService.getUuid(), adminState, operState,
222                     LayerProtocolName.ODU));
223             }
224         } catch (InterruptedException | ExecutionException e) {
225             LOG.error("Could not update TAPI connectivity services");
226         }
227     }
228
229     private Enumeration[] getStates(ConnectivityService connService) throws InterruptedException, ExecutionException {
230         OperationalState operState = OperationalState.ENABLED;
231         AdministrativeState adminState = AdministrativeState.UNLOCKED;
232         if (connService.getConnection() == null) {
233             LOG.info("No connections on service = {}", connService);
234             return new Enumeration[]{null, null};
235         }
236         for (org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210
237                 .connectivity.service.Connection connection : connService.getConnection().values()) {
238             InstanceIdentifier<Connection> connIID =
239                 InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
240                         .onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
241                     .child(ConnectivityContext.class)
242                     .child(Connection.class, new ConnectionKey(connection.getConnectionUuid()))
243                     .build();
244             Optional<Connection> optConn = this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL,
245                 connIID).get();
246             if (optConn.isEmpty()) {
247                 LOG.error("Could not get state for a TAPI connection");
248                 continue;
249             }
250             LOG.info("State of connection {} of connectivity service {} = {}", optConn.get().getUuid().getValue(),
251                 connService.getUuid().getValue(), optConn.get().getOperationalState().getName());
252             if (optConn.get().getOperationalState() == OperationalState.DISABLED) {
253                 adminState = AdministrativeState.LOCKED;
254                 operState = OperationalState.DISABLED;
255             }
256         }
257         return new Enumeration[]{adminState, operState};
258     }
259
260     private void updateConnections(List<Uuid> changedOneps, List<String> onepStates) {
261         LOG.info("Updating TAPI connections");
262         LOG.info("Change in oneps = {}, new states = {}", changedOneps, onepStates);
263         try {
264             //should it return a list of connections?
265             InstanceIdentifier<org.opendaylight.yang.gen.v1.urn
266                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext> connectivityContextIID =
267                 InstanceIdentifier.builder(Context.class).augmentation(
268                             org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
269                         .child(org.opendaylight.yang.gen.v1.urn
270                                 .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
271                         .build();
272             Optional<org.opendaylight.yang.gen.v1.urn
273                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext> optConnContext =
274                 this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connectivityContextIID).get();
275             if (optConnContext.isEmpty()) {
276                 LOG.error(TapiStringConstants.TAPI_CONNECTION_UPDATE_ERROR);
277                 return;
278             }
279             if (optConnContext.get().getConnectivityService() == null) {
280                 LOG.info("No TAPI connectivity service to update");
281                 return;
282             }
283             // TODO: order services from lower layer to upper layer
284             Map<ConnectivityServiceKey, ConnectivityService> connServMap
285                     = optConnContext.get().getConnectivityService();
286             if (connServMap == null) {
287                 LOG.info("No connections to update");
288                 return;
289             }
290             connServMap = orderConnServiceMap(connServMap);
291             for (ConnectivityService connService : connServMap.values()) {
292                 LOG.info("Looping through connectivity service = {}", connService.getUuid().getValue());
293                 if (connService.getConnection() == null) {
294                     continue;
295                 }
296                 for (org.opendaylight.yang.gen.v1.urn.onf.otcc.yang.tapi.connectivity.rev181210
297                         .connectivity.service.Connection connection : connService.getConnection().values()) {
298                     InstanceIdentifier<Connection> connIID =
299                         InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
300                             .onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
301                                 .child(org.opendaylight.yang.gen.v1.urn
302                                         .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
303                                 .child(Connection.class, new ConnectionKey(connection.getConnectionUuid()))
304                                 .build();
305                     Optional<Connection> optConn =
306                         this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connIID).get();
307                     if (optConn.isEmpty()) {
308                         LOG.error(TapiStringConstants.TAPI_CONNECTION_READ_ERROR);
309                         continue;
310                     }
311                     Connection newConn = optConn.get();
312                     // Check LowerConnection states and if any of the lower connection is disabled then we can put
313                     // the connection out of service. And based on the connection previous state we decide
314                     // the update necessary
315                     OperationalState newConnState = newConn.getOperationalState();
316                     if (newConn.getLowerConnection() != null) {
317                         newConnState = updateLowerConnections(changedOneps, onepStates,
318                                 newConn.getLowerConnection().values(), newConn.getOperationalState());
319                     }
320                     if (newConnState.equals(newConn.getOperationalState())) {
321                         // To check if the oneps are from the original Top connection
322                         newConnState = getConnectionState(changedOneps, onepStates, newConn);
323                     }
324
325                     LOG.info("Previous connection state = {} & New connection state = {}",
326                             newConn.getOperationalState().getName(), newConnState.getName());
327                     Connection changedConn = new ConnectionBuilder(newConn).setOperationalState(newConnState).build();
328                     // TODO: the changed NEP is a DEG port which is not in any connection,
329                     //  therefore we also need to change the cross connections,
330                     //  the lower connections uuid and check the states.
331                     //  If any of the lower connections of a connection is DISABLED then the top connection is DISABLED
332                     this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connIID, changedConn);
333                     this.networkTransactionService.commit().get();
334                 }
335             }
336         } catch (InterruptedException | ExecutionException e) {
337             LOG.error(TapiStringConstants.TAPI_CONNECTION_UPDATE_ERROR);
338         }
339     }
340
341     private Map<ConnectivityServiceKey, ConnectivityService> orderConnServiceMap(
342             Map<ConnectivityServiceKey, ConnectivityService> connServMap) {
343         Map<ConnectivityServiceKey, ConnectivityService> orderedServiceMap = new HashMap<>();
344         for (LayerProtocolName lpn:this.orderedServiceLayerList) {
345             for (ConnectivityService connServ:connServMap.values()) {
346                 if (connServ.getServiceLayer().equals(lpn)) {
347                     LOG.info("Layer of service is equal to entry of lpn = {}", lpn);
348                     orderedServiceMap.put(connServ.key(), connServ);
349                 }
350             }
351         }
352         LOG.info("Ordered map of services = {}", orderedServiceMap);
353         return orderedServiceMap;
354     }
355
356     private OperationalState updateLowerConnections(List<Uuid> changedOneps, List<String> onepStates,
357                                                     Collection<LowerConnection> lowerConnections,
358                                                     OperationalState uppConnState) {
359         LOG.info("Updating lower connections");
360         OperationalState topConnectionState = uppConnState;
361         Boolean allLowerConnEna = true;
362         try {
363             for (LowerConnection lowerConn:lowerConnections) {
364                 InstanceIdentifier<Connection> connIID =
365                     InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
366                         .onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
367                             .child(org.opendaylight.yang.gen.v1.urn
368                                     .onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
369                             .child(Connection.class, new ConnectionKey(lowerConn.getConnectionUuid()))
370                             .build();
371                 Optional<Connection> optConn =
372                         this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connIID).get();
373                 if (optConn.isEmpty()) {
374                     LOG.error(TapiStringConstants.TAPI_CONNECTION_READ_ERROR);
375                     continue;
376                 }
377                 Connection newConn = optConn.get(); // Current state of connection
378                 if (newConn.getLowerConnection() != null) {
379                     // TODO: we can receive disable here because the lower connection haven been yet looped through and
380                     //  therefore it is disabled but it has to be changed to enable before returning disable.
381                     //  We need to recall the update Lower Connections with the lower connection we are checking now
382                     //  and all its lower connections, until no lower connections are found in the connection
383                     updateLowerConnections(changedOneps, onepStates, newConn.getLowerConnection().values(),
384                             newConn.getOperationalState());
385                 }
386                 OperationalState newConnState = getConnectionState(changedOneps, onepStates, newConn);
387                 // updated connection state if it contains a nep that has changed
388                 if (!newConn.getOperationalState().equals(newConnState)) {
389                     Connection changedConn = new ConnectionBuilder(newConn).setOperationalState(newConnState).build();
390                     this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, connIID, changedConn);
391                     this.networkTransactionService.commit().get();
392                 }
393                 if (newConnState.equals(OperationalState.DISABLED)) {
394                     LOG.info("LowerConnection state is disable");
395                     allLowerConnEna = false;
396                     topConnectionState = OperationalState.DISABLED;
397                 }
398             }
399             if (allLowerConnEna) {
400                 return OperationalState.ENABLED;
401             }
402             return OperationalState.DISABLED;
403         } catch (InterruptedException | ExecutionException e) {
404             LOG.error(TapiStringConstants.TAPI_CONNECTION_UPDATE_ERROR);
405             return topConnectionState;
406         }
407     }
408
409     private OperationalState getConnectionState(List<Uuid> changedOneps, List<String> operState, Connection conn)
410             throws InterruptedException, ExecutionException {
411         LOG.info("Getting TAPI connectionState");
412         List<Uuid> connectionNeps = Objects.requireNonNull(conn.getConnectionEndPoint()).values().stream()
413             .map(NodeEdgePointRef::getNodeEdgePointUuid).collect(Collectors.toList());
414         LOG.info("Changed neps = {}", changedOneps);
415         LOG.info("Connection NEPs = {}", connectionNeps);
416         if (!Collections.disjoint(changedOneps, connectionNeps)) {
417             LOG.info("Connection neps {} are included in changed oneps {}", connectionNeps, changedOneps);
418             if ((changedOneps.contains(connectionNeps.get(0)) ? transformOperState(operState.get(
419                     changedOneps.indexOf(connectionNeps.get(0)))) : null) == OperationalState.DISABLED
420                         || (changedOneps.contains(connectionNeps.get(1)) ? transformOperState(operState.get(
421                                 changedOneps.indexOf(connectionNeps.get(1)))) : null) == OperationalState.DISABLED) {
422                 return OperationalState.DISABLED;
423             }
424             LOG.info("Didnt transform correctly the states");
425             for (Uuid connectionNep : connectionNeps) {
426                 Optional<org.opendaylight.yang.gen.v1.urn
427                         .onf.otcc.yang.tapi.connectivity.rev181210.connection.ConnectionEndPoint> ocep
428                     = conn.getConnectionEndPoint().values().stream()
429                         .filter(connectionEndPoint -> connectionEndPoint.getNodeEdgePointUuid() == connectionNep)
430                         .findFirst();
431                 if (ocep.isEmpty()) {
432                     continue;
433                 }
434                 InstanceIdentifier<OwnedNodeEdgePoint> onepIID = InstanceIdentifier.builder(Context.class)
435                     .augmentation(Context1.class).child(TopologyContext.class)
436                     .child(Topology.class, new TopologyKey(tapiTopoUuid))
437                     .child(Node.class, new NodeKey(ocep.get().getNodeUuid()))
438                     .child(OwnedNodeEdgePoint.class, new OwnedNodeEdgePointKey(connectionNep))
439                     .build();
440                 Optional<OwnedNodeEdgePoint> onep =
441                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, onepIID).get();
442                 if (onep.isEmpty() || onep.get().augmentation(OwnedNodeEdgePoint1.class) == null
443                         || onep.get().augmentation(OwnedNodeEdgePoint1.class).getCepList() == null) {
444                     continue;
445                 }
446                 if (onep.get().getOperationalState() == OperationalState.DISABLED
447                         && !changedOneps.contains(onep.get().getUuid())) {
448                     return OperationalState.DISABLED;
449                 }
450             }
451             return OperationalState.ENABLED;
452         }
453         LOG.info("Connection state = {}. Going to check lower connections", conn.getOperationalState());
454         // TODO --> check all lower connections state and if all of them are enabled we return enable, otherwise disable
455         if (conn.getLowerConnection() != null && allLowerConEnabled(conn.getLowerConnection().values())) {
456             return OperationalState.ENABLED;
457         }
458         return conn.getOperationalState();
459     }
460
461     private boolean allLowerConEnabled(Collection<LowerConnection> lowerConnections) {
462         try {
463             for (LowerConnection lowerConn:lowerConnections) {
464                 InstanceIdentifier<Connection> connIID =
465                     InstanceIdentifier.builder(Context.class).augmentation(org.opendaylight.yang.gen.v1.urn
466                             .onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
467                         .child(org.opendaylight.yang.gen.v1.urn
468                             .onf.otcc.yang.tapi.connectivity.rev181210.context
469                             .ConnectivityContext.class)
470                         .child(Connection.class, new ConnectionKey(lowerConn.getConnectionUuid()))
471                         .build();
472                 Optional<Connection> optConn =
473                     this.networkTransactionService.read(LogicalDatastoreType.OPERATIONAL, connIID).get();
474                 if (optConn.isEmpty()) {
475                     LOG.error(TapiStringConstants.TAPI_CONNECTION_READ_ERROR);
476                     continue;
477                 }
478                 Connection newConn = optConn.get(); // Current state of connection
479                 // updated connection state if it contains a nep that has changed
480                 if (newConn.getOperationalState().equals(OperationalState.DISABLED)) {
481                     LOG.info("LowerConnection state is disable");
482                     return false;
483                 }
484             }
485             return true;
486         } catch (InterruptedException | ExecutionException e) {
487             LOG.error(TapiStringConstants.TAPI_CONNECTION_UPDATE_ERROR);
488             return false;
489         }
490     }
491
492     private List<ConnectivityService> updateSupportedConnectivityServices(Collection<ConnectivityService> connServices,
493                                                                           Uuid supportingConnService,
494                                                                           AdministrativeState adminState,
495                                                                           OperationalState operState,
496                                                                           LayerProtocolName layer) {
497         // TODO we need to check this function
498         List<ConnectivityService> changedServices = new ArrayList<>();
499         if (adminState != AdministrativeState.LOCKED && operState != OperationalState.DISABLED) {
500             return changedServices;
501         }
502         try {
503             for (ConnectivityService supportedConnService : connServices) {
504                 // TODO currently supporting service uuid is saved in service layer, replace with name as soon
505                 // as name is implemented
506                 if (supportedConnService.getServiceLayer() != layer) {
507                     continue;
508                 }
509                 InstanceIdentifier<ConnectivityService> supportedConnServIID = InstanceIdentifier
510                     .builder(Context.class).augmentation(org.opendaylight.yang.gen.v1
511                         .urn.onf.otcc.yang.tapi.connectivity.rev181210.Context1.class)
512                     .child(org.opendaylight.yang.gen.v1
513                         .urn.onf.otcc.yang.tapi.connectivity.rev181210.context.ConnectivityContext.class)
514                     .child(ConnectivityService.class, new ConnectivityServiceKey(supportedConnService.getUuid()))
515                     .build();
516                 Optional<ConnectivityService> optNewConnService = this.networkTransactionService.read(
517                     LogicalDatastoreType.OPERATIONAL, supportedConnServIID).get();
518                 if (optNewConnService.isEmpty()) {
519                     LOG.error("Could not update TAPI connectivity service");
520                     continue;
521                 }
522                 ConnectivityService newConnService = optNewConnService.get();
523                 if (supportedConnService.getServiceLevel() != null
524                         && supportedConnService.getServiceLevel().equals(supportingConnService.getValue())
525                         && newConnService.getAdministrativeState() != AdministrativeState.LOCKED
526                         && newConnService.getOperationalState() != OperationalState.DISABLED) {
527
528                     ConnectivityService changedSupportedConnServ = new ConnectivityServiceBuilder()
529                         .setUuid(supportedConnService.getUuid())
530                         .setAdministrativeState(adminState)
531                         .setOperationalState(operState)
532                         .build();
533                     // TODO: may need to update connections...
534                     this.networkTransactionService.merge(LogicalDatastoreType.OPERATIONAL, supportedConnServIID,
535                         changedSupportedConnServ);
536                     this.networkTransactionService.commit().get();
537                     changedServices.add(changedSupportedConnServ);
538                     if (layer == LayerProtocolName.ODU) {
539                         changedServices.addAll(updateSupportedConnectivityServices(connServices,
540                             supportedConnService.getUuid(), adminState, operState, LayerProtocolName.DSR));
541                     }
542                 }
543             }
544         } catch (InterruptedException | ExecutionException e) {
545             LOG.error("Could not update TAPI connectivity service");
546         }
547         return changedServices;
548     }
549
550     private OperationalState transformOperState(String operString) {
551         LOG.debug("Operstring to be converted = {}", operString);
552         State operState = org.opendaylight.transportpce.networkmodel.util.TopologyUtils.setNetworkOperState(operString);
553         LOG.debug("State received from topologyutils = {}", operState);
554         return operState.equals(State.InService) ? OperationalState.ENABLED : OperationalState.DISABLED;
555     }
556
557 }