Add service-resiliency handling in service-create
[transportpce.git] / servicehandler / src / main / java / org / opendaylight / transportpce / servicehandler / listeners / NetworkModelListenerImpl.java
1 /*
2  * Copyright © 2020 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.servicehandler.listeners;
9
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Optional;
15 import java.util.stream.Collectors;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.mdsal.binding.api.NotificationPublishService;
18 import org.opendaylight.transportpce.common.OperationResult;
19 import org.opendaylight.transportpce.servicehandler.service.ServiceDataStoreOperations;
20 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkmodel.rev201116.TopologyUpdateResult;
21 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkmodel.rev201116.TopologyUpdateResultBuilder;
22 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkmodel.rev201116.TransportpceNetworkmodelListener;
23 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkmodel.rev201116.topology.update.result.TopologyChanges;
24 import org.opendaylight.yang.gen.v1.http.org.opendaylight.transportpce.networkmodel.rev201116.topology.update.result.TopologyChangesKey;
25 import org.opendaylight.yang.gen.v1.http.org.openroadm.common.state.types.rev191129.State;
26 import org.opendaylight.yang.gen.v1.http.org.openroadm.service.rev211210.service.list.Services;
27 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.AToZDirection;
28 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.AToZDirectionBuilder;
29 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ZToADirection;
30 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ZToADirectionBuilder;
31 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.atoz.direction.AToZ;
32 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.atoz.direction.AToZBuilder;
33 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.atoz.direction.AToZKey;
34 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ztoa.direction.ZToA;
35 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ztoa.direction.ZToABuilder;
36 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.path.description.ztoa.direction.ZToAKey;
37 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.pce.resource.Resource;
38 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.pce.resource.ResourceBuilder;
39 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.pathdescription.rev210705.pce.resource.resource.resource.TerminationPoint;
40 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev220118.service.path.PathDescription;
41 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.service.types.rev220118.service.path.PathDescriptionBuilder;
42 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.ServicePathList;
43 import org.opendaylight.yang.gen.v1.http.org.transportpce.b.c._interface.servicepath.rev171017.service.path.list.ServicePaths;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class NetworkModelListenerImpl implements TransportpceNetworkmodelListener {
48
49     private static final Logger LOG = LoggerFactory.getLogger(NetworkModelListenerImpl.class);
50     private final NotificationPublishService notificationPublishService; // to be used for T-API notification
51     private ServiceDataStoreOperations serviceDataStoreOperations;
52     private TopologyUpdateResult topologyUpdateResult;
53
54     public NetworkModelListenerImpl(NotificationPublishService notificationPublishService,
55                                     ServiceDataStoreOperations serviceDataStoreOperations) {
56         this.notificationPublishService = notificationPublishService;
57         this.serviceDataStoreOperations = serviceDataStoreOperations;
58     }
59
60     @Override
61     public void onTopologyUpdateResult(TopologyUpdateResult notification) {
62         LOG.debug("Topology update notification: {}", notification);
63         if (compareTopologyUpdateResult(notification)) {
64             LOG.warn("TopologyUpdateResult already wired !");
65             return;
66         }
67         topologyUpdateResult = new TopologyUpdateResultBuilder().setTopologyChanges(
68                 new HashMap<>(notification.getTopologyChanges())).build();
69         // Update service datastore and service path description
70         updateServicePaths(notification);
71     }
72
73     /**
74      * Process topology update result.
75      * @param notification the result notification.
76      */
77     protected void updateServicePaths(TopologyUpdateResult notification) {
78         @Nullable
79         Map<TopologyChangesKey, TopologyChanges> topologyChanges = notification.getTopologyChanges();
80         Optional<ServicePathList> servicePathListOptional = this.serviceDataStoreOperations.getServicePaths();
81         if (servicePathListOptional.isEmpty()) {
82             LOG.warn("Enable to retrieve service path list");
83             return;
84         }
85         ServicePathList servicePathList = servicePathListOptional.get();
86         for (ServicePaths servicePaths : servicePathList.getServicePaths().values()) {
87             String serviceName = servicePaths.getServicePathName();
88             PathDescription pathDescription = servicePaths.getPathDescription();
89             // update path descriptions in the datastore
90             Map<AToZKey, AToZ> updatedAtoZ = changePathElementStateAZ(topologyChanges, pathDescription);
91             Map<ZToAKey, ZToA> updatedZtoA = changePathElementStateZA(topologyChanges, pathDescription);
92             OperationResult operationResult = this.serviceDataStoreOperations
93                     .modifyServicePath(buildNewPathDescription(pathDescription, updatedAtoZ, updatedZtoA), serviceName);
94             if (!operationResult.isSuccess()) {
95                 LOG.warn("Service Path not updated in datastore!");
96                 continue;
97             }
98             // update service in the datastore. Only path description with all elements in service can have a service
99             // in service. Therefore we check if all the states of the path description resources are inService
100             Optional<Services> serviceOptional = this.serviceDataStoreOperations.getService(serviceName);
101             if (serviceOptional.isEmpty()) {
102                 LOG.error("Couldn't retrieve service");
103                 continue;
104             }
105             Services services = serviceOptional.get();
106             OperationResult operationResult1 = null;
107             switch (services.getOperationalState()) {
108                 case InService:
109                     if (!allElementsinPathinService(updatedAtoZ, updatedZtoA)) {
110                         LOG.debug("Service={} needs to be updated to outOfService", serviceName);
111                         //if (operationResult1 != null && operationResult1.isSuccess()) {
112                         //null check probably no more needed
113                         if (this.serviceDataStoreOperations
114                                 .modifyService(serviceName, State.OutOfService, services.getAdministrativeState())
115                                 .isSuccess()) {
116                             LOG.info("Service state of {} correctly updated to outOfService in datastore", serviceName);
117                             continue;
118                         } else {
119                             LOG.error("Service state of {} cannot be updated to outOfService in datastore",
120                                 serviceName);
121                         }
122                     }
123                     break;
124                 case OutOfService:
125                     if (allElementsinPathinService(updatedAtoZ, updatedZtoA)) {
126                         LOG.debug("Service={} needs to be updated to inService", serviceName);
127                         //if (operationResult1 != null && operationResult1.isSuccess()) {
128                         //null check probably no more needed
129                         if (this.serviceDataStoreOperations
130                                 .modifyService(serviceName, State.InService, services.getAdministrativeState())
131                                 .isSuccess()) {
132                             LOG.info("Service state of {} correctly updated to inService in datastore", serviceName);
133                             continue;
134                         } else {
135                             LOG.error("Service state of {} cannot be updated to inService in datastore", serviceName);
136                         }
137                     }
138                     break;
139                 default:
140                     LOG.warn("Service {} state not managed", serviceName);
141                     continue;
142             }
143             LOG.debug("Service {} state does not need to be modified", serviceName);
144         }
145     }
146
147     protected Map<ZToAKey, ZToA> changePathElementStateZA(Map<TopologyChangesKey, TopologyChanges> topologyChanges,
148         PathDescription pathDescription) {
149         Map<ZToAKey, ZToA> newztoaMap = new HashMap<>(pathDescription.getZToADirection().getZToA());
150         List<ZToA> tpResources = pathDescription.getZToADirection().getZToA().values().stream()
151                 .filter(ele -> ele.getResource().getResource() instanceof TerminationPoint)
152                 .collect(Collectors.toList());
153         for (ZToA ztoA : tpResources) {
154             String ztoAid = ztoA.getId();
155             State ztoAState = ztoA.getResource().getState();
156             TerminationPoint tp = (TerminationPoint) ztoA.getResource().getResource();
157             if (topologyChanges.containsKey(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId()))
158                 && !topologyChanges.get(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId())).getState()
159                 .equals(ztoAState)) {
160                 LOG.debug("updating ztoa tp {}", ztoA);
161                 State updatedState = topologyChanges.get(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId()))
162                     .getState();
163                 Resource updatedResource = new ResourceBuilder()
164                     .setResource(tp)
165                     .setState(updatedState)
166                     .build();
167                 ZToA updatedZToA = new ZToABuilder(ztoA)
168                     .setId(ztoAid)
169                     .setResource(updatedResource)
170                     .build();
171                 newztoaMap.put(updatedZToA.key(), updatedZToA);
172             }
173         }
174         return newztoaMap;
175     }
176
177     protected Map<AToZKey, AToZ> changePathElementStateAZ(Map<TopologyChangesKey,
178             TopologyChanges> topologyChanges, PathDescription pathDescription) {
179
180         Map<AToZKey, AToZ> newatozMap = new HashMap<>(pathDescription.getAToZDirection().getAToZ());
181         List<AToZ> tpResources = pathDescription.getAToZDirection().getAToZ().values().stream()
182             .filter(ele -> ele.getResource().getResource() instanceof TerminationPoint)
183             .collect(Collectors.toList());
184         for (AToZ atoZ : tpResources) {
185             String atoZid = atoZ.getId();
186             State atoZState = atoZ.getResource().getState();
187             TerminationPoint tp = (TerminationPoint) atoZ.getResource().getResource();
188             if (topologyChanges.containsKey(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId()))
189                 && !topologyChanges.get(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId())).getState()
190                 .equals(atoZState)) {
191                 LOG.debug("updating atoz tp {}", atoZ);
192                 State updatedState = topologyChanges.get(new TopologyChangesKey(tp.getTpNodeId(), tp.getTpId()))
193                     .getState();
194                 Resource updatedResource = new ResourceBuilder()
195                     .setResource(tp)
196                     .setState(updatedState)
197                     .build();
198                 AToZ updatedAToZ = new AToZBuilder(atoZ)
199                     .setId(atoZid)
200                     .setResource(updatedResource)
201                     .build();
202                 newatozMap.put(updatedAToZ.key(), updatedAToZ);
203             }
204         }
205         return newatozMap;
206     }
207
208     private PathDescription buildNewPathDescription(PathDescription pathDescription, Map<AToZKey, AToZ> updatedAtoZ,
209                                                     Map<ZToAKey, ZToA> updatedZtoA) {
210         AToZDirection atozDir = new AToZDirectionBuilder(pathDescription.getAToZDirection())
211                 .setAToZ(updatedAtoZ)
212                 .build();
213         ZToADirection ztoaDir = new ZToADirectionBuilder(pathDescription.getZToADirection())
214                 .setZToA(updatedZtoA)
215                 .build();
216         return new PathDescriptionBuilder()
217             .setAToZDirection(atozDir)
218             .setZToADirection(ztoaDir)
219             .build();
220     }
221
222     protected boolean allElementsinPathinService(Map<AToZKey, AToZ> updatedAtoZ, Map<ZToAKey, ZToA> updatedZtoA) {
223         boolean allEleminService = true;
224         Iterator<AToZ> i1 = updatedAtoZ.values().iterator();
225         Iterator<ZToA> i2 = updatedZtoA.values().iterator();
226         // TODO: both directions have same length?
227         while (i1.hasNext() && i2.hasNext()) {
228             if (State.OutOfService.getIntValue() == i1.next().getResource().getState().getIntValue()
229                     || State.OutOfService.getIntValue() == i2.next().getResource().getState().getIntValue()) {
230                 allEleminService = false;
231                 break;
232             }
233         }
234
235         return allEleminService;
236     }
237
238     private boolean compareTopologyUpdateResult(TopologyUpdateResult notification) {
239         return topologyUpdateResult != null && topologyUpdateResult.getTopologyChanges()
240                 .equals(notification.getTopologyChanges());
241     }
242
243     public void setserviceDataStoreOperations(ServiceDataStoreOperations serviceData) {
244         this.serviceDataStoreOperations = serviceData;
245     }
246 }