c4cd434203504853702b5dd6ab0a3729fc36d918
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / vnfm / notification / LifecycleChangeNotificationManager.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification;
17
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.collect.Ordering;
20 import com.google.gson.Gson;
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonObject;
23 import com.nokia.cbam.lcm.v32.api.OperationExecutionsApi;
24 import com.nokia.cbam.lcm.v32.api.VnfsApi;
25 import com.nokia.cbam.lcm.v32.model.*;
26 import java.util.List;
27 import java.util.Optional;
28 import java.util.Set;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.INotificationSender;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.core.SelfRegistrationManager;
31 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.OperationMustBeAborted;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
33 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
34 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager;
35 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.LifecycleManager;
36 import org.slf4j.Logger;
37
38 import static java.util.Optional.empty;
39 import static java.util.Optional.of;
40
41 import static com.google.common.collect.Iterables.find;
42 import static com.google.common.collect.Iterables.tryFind;
43 import static com.google.common.collect.Sets.newConcurrentHashSet;
44 import static com.google.common.collect.Sets.newHashSet;
45 import static com.nokia.cbam.lcm.v32.model.OperationType.INSTANTIATE;
46 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
47 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.childElement;
48 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
49 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCN_API_VERSION;
50 import static org.slf4j.LoggerFactory.getLogger;
51
52 /**
53  * Responsible for handling lifecycle change notifications from CBAM.
54  * The received LCNs are transformed into ONAP LCNs.
55  * The following CBAM LCNs are processed:
56  * - HEAL
57  * - INSTANTIATE
58  * - SCALE
59  * - TERMINATE
60  * The current limitations
61  * - if a LCN can not be be processed due to VNF having been deleted the problem is logged and CBAM is notified that
62  * the LCN has been processed (even if not in reality) because the signaling of failed LCN delivery blocks the delivery
63  * on all LCN deliveries. The consequence of this is that the information known by VF-C / A&AI may be inconsistent with
64  * reality (VNF having been deleted)
65  */
66 public class LifecycleChangeNotificationManager implements ILifecycleChangeNotificationManager {
67
68     public static final String PROBLEM = "All operations must return the { \"operationResult\" : { \"cbam_pre\" : [<fillMeOut>], \"cbam_post\" : [<fillMeOut>] } } structure";
69     /**
70      * Order the operations by start time (latest first)
71      */
72     public static final Ordering<OperationExecution> NEWEST_OPERATIONS_FIRST = new Ordering<OperationExecution>() {
73         @Override
74         public int compare(OperationExecution left, OperationExecution right) {
75             return right.getStartTime().toLocalDate().compareTo(left.getStartTime().toLocalDate());
76         }
77     };
78     /**
79      * < Separates the VNF id and the resource id within a VNF
80      */
81     private static final Set<OperationStatus> terminalStatus = newHashSet(OperationStatus.FINISHED, OperationStatus.FAILED);
82     private static Logger logger = getLogger(LifecycleChangeNotificationManager.class);
83
84     private final CbamRestApiProvider restApiProvider;
85     private final INotificationSender notificationSender;
86     private final SelfRegistrationManager selfRegistrationManager;
87     private Set<ProcessedNotification> processedNotifications = newConcurrentHashSet();
88
89     LifecycleChangeNotificationManager(CbamRestApiProvider restApiProvider, SelfRegistrationManager selfRegistrationManager, INotificationSender notificationSender) {
90         this.notificationSender = notificationSender;
91         this.restApiProvider = restApiProvider;
92         this.selfRegistrationManager = selfRegistrationManager;
93     }
94
95     /**
96      * @param status the status of the operation
97      * @return has the operation finished
98      */
99     public static boolean isTerminal(OperationStatus status) {
100         return terminalStatus.contains(status);
101     }
102
103     @VisibleForTesting
104     static OperationExecution findLastInstantiationBefore(List<OperationExecution> operationExecutions, OperationExecution currentOperation) {
105         return find(NEWEST_OPERATIONS_FIRST.sortedCopy(operationExecutions), (OperationExecution opex2) ->
106                 !opex2.getStartTime().isAfter(currentOperation.getStartTime())
107                         && INSTANTIATE.equals(opex2.getOperationType()));
108     }
109
110     @Override
111     public void handleLcn(VnfLifecycleChangeNotification receivedNotification) {
112         if (logger.isInfoEnabled()) {
113             logger.info("Received LCN: {}", new Gson().toJson(receivedNotification));
114         }
115         String vnfmId = selfRegistrationManager.getVnfmId(receivedNotification.getSubscriptionId());
116         VnfsApi cbamLcmApi = restApiProvider.getCbamLcmApi(vnfmId);
117         try {
118             List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION).blockingFirst();
119             com.google.common.base.Optional<VnfInfo> currentVnf = tryFind(vnfs, vnf -> vnf.getId().equals(receivedNotification.getVnfInstanceId()));
120             String vnfHeader = "The VNF with " + receivedNotification.getVnfInstanceId() + " identifier";
121             if (!currentVnf.isPresent()) {
122                 logger.warn(vnfHeader + " disappeared before being able to process the LCN");
123                 //swallow LCN
124                 return;
125             } else {
126                 VnfInfo vnf = cbamLcmApi.vnfsVnfInstanceIdGet(receivedNotification.getVnfInstanceId(), NOKIA_LCN_API_VERSION).blockingFirst();
127                 com.google.common.base.Optional<VnfProperty> externalVnfmId = tryFind(vnf.getExtensions(), prop -> prop.getName().equals(LifecycleManager.EXTERNAL_VNFM_ID));
128                 if (!externalVnfmId.isPresent()) {
129                     logger.warn(vnfHeader + " is not a managed VNF");
130                     return;
131                 }
132                 if (!externalVnfmId.get().getValue().equals(vnfmId)) {
133                     logger.warn(vnfHeader + " is not a managed by the VNFM with id " + externalVnfmId.get().getValue());
134                     return;
135                 }
136             }
137         } catch (Exception e) {
138             throw buildFatalFailure(logger, "Unable to list VNFs / query VNF", e);
139         }
140         OperationExecutionsApi cbamOperationExecutionApi = restApiProvider.getCbamOperationExecutionApi(vnfmId);
141         List<OperationExecution> operationExecutions;
142         try {
143             operationExecutions = cbamLcmApi.vnfsVnfInstanceIdOperationExecutionsGet(receivedNotification.getVnfInstanceId(), NOKIA_LCM_API_VERSION).blockingFirst();
144         } catch (Exception e) {
145             throw buildFatalFailure(logger, "Unable to retrieve the operation executions for the VNF " + receivedNotification.getVnfInstanceId(), e);
146         }
147         OperationExecution operationExecution;
148         try {
149             operationExecution = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdGet(receivedNotification.getLifecycleOperationOccurrenceId(), NOKIA_LCM_API_VERSION).blockingFirst();
150         } catch (Exception e) {
151             throw buildFatalFailure(logger, "Unable to retrieve the operation execution with " + receivedNotification.getLifecycleOperationOccurrenceId() + " identifier", e);
152         }
153         OperationExecution closestInstantiationToOperation = findLastInstantiationBefore(operationExecutions, operationExecution);
154         String vimId = getVimId(cbamOperationExecutionApi, closestInstantiationToOperation);
155         notificationSender.processNotification(receivedNotification, operationExecution, buildAffectedCps(operationExecution), vimId, vnfmId);
156         if (isTerminationFinished(receivedNotification)) {
157             //signal LifecycleManager to continue the deletion of the VNF
158             processedNotifications.add(new ProcessedNotification(receivedNotification.getLifecycleOperationOccurrenceId(), receivedNotification.getStatus()));
159         }
160     }
161
162     private boolean isTerminationFinished(VnfLifecycleChangeNotification receivedNotification) {
163         return OperationType.TERMINATE.equals(receivedNotification.getOperation()) && terminalStatus.contains(receivedNotification.getStatus());
164     }
165
166     private String getVimId(OperationExecutionsApi cbamOperationExecutionApi, OperationExecution closestInstantiationToOperation) {
167         try {
168             Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(closestInstantiationToOperation.getId(), NOKIA_LCM_API_VERSION).blockingFirst();
169             return getVimId(operationParams);
170         } catch (Exception e) {
171             throw buildFatalFailure(logger, "Unable to detect last instantiation operation", e);
172         }
173     }
174
175     @Override
176     public void waitForTerminationToBeProcessed(String operationExecutionId) {
177         while (true) {
178             com.google.common.base.Optional<ProcessedNotification> notification = tryFind(processedNotifications, processedNotification -> processedNotification.getOperationExecutionId().equals(operationExecutionId));
179             if (notification.isPresent()) {
180                 processedNotifications.remove(notification.get());
181                 return;
182             }
183             SystemFunctions.systemFunctions().sleep(500);
184         }
185     }
186
187     private String getVimId(Object instantiationParameters) {
188         InstantiateVnfRequest request = new Gson().fromJson(new Gson().toJson(instantiationParameters), InstantiateVnfRequest.class);
189         return request.getVims().get(0).getId();
190     }
191
192     private Optional<ReportedAffectedConnectionPoints> buildAffectedCps(OperationExecution operationExecution) {
193         if (!isTerminal(operationExecution.getStatus())) {
194             //connection points can only be calculated after the operation has finished
195             return Optional.empty();
196         }
197         if (operationExecution.getOperationType() == OperationType.TERMINATE) {
198             String terminationType = childElement(new Gson().toJsonTree(operationExecution.getOperationParams()).getAsJsonObject(), "terminationType").getAsString();
199             if (TerminationType.FORCEFUL.name().equals(terminationType)) {
200                 //in case of force full termination the Ansible is not executed, so the connection points can not be
201                 //calculated from operation execution result
202                 logger.warn("Unable to send information related to affected connection points during forceful termination");
203                 return empty();
204             } else {
205                 //graceful termination should be handled as any other operation
206             }
207         }
208         try {
209             JsonElement root = new Gson().toJsonTree(operationExecution.getAdditionalData());
210             if (root.getAsJsonObject().has("operationResult")) {
211                 JsonObject operationResult = root.getAsJsonObject().get("operationResult").getAsJsonObject();
212                 if (isAbsent(operationResult, "cbam_pre") ||
213                         isAbsent(operationResult, "cbam_post")) {
214                     return handleFailure(operationExecution);
215                 } else {
216                     return of(new Gson().fromJson(operationResult, ReportedAffectedConnectionPoints.class));
217                 }
218             } else {
219                 return handleFailure(operationExecution);
220             }
221         }
222         catch(OperationMustBeAborted handledFailuire){
223             throw handledFailuire;
224         }
225         catch (Exception e) {
226             logger.warn("Unable to build affected connection points", e);
227             return toleratedFailure();
228         }
229     }
230
231     private boolean isAbsent(JsonObject operationResult, String key) {
232         return !operationResult.has(key) || !operationResult.get(key).isJsonArray();
233     }
234
235     private Optional<ReportedAffectedConnectionPoints> handleFailure(OperationExecution operationExecution) {
236         if (operationExecution.getStatus() == OperationStatus.FAILED) {
237             return toleratedFailure();
238         } else {
239             throw buildFatalFailure(logger, PROBLEM);
240         }
241     }
242
243     private Optional<ReportedAffectedConnectionPoints> toleratedFailure() {
244         logger.warn("The operation failed and the affected connection points were not reported");
245         return empty();
246     }
247 }