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