Removing jackson to mitigate cve-2017-4995
[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.util.SystemFunctions;
31 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties;
33 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager;
34 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.LifecycleManager;
35 import org.slf4j.Logger;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Component;
38
39 import static java.util.Optional.empty;
40 import static java.util.Optional.of;
41
42 import static com.google.common.collect.Iterables.find;
43 import static com.google.common.collect.Iterables.tryFind;
44 import static com.google.common.collect.Sets.newConcurrentHashSet;
45 import static com.google.common.collect.Sets.newHashSet;
46 import static com.nokia.cbam.lcm.v32.model.OperationType.INSTANTIATE;
47 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
48 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.childElement;
49 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
50 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCN_API_VERSION;
51 import static org.slf4j.LoggerFactory.getLogger;
52
53 /**
54  * Responsible for handling lifecycle change notifications from CBAM.
55  * The received LCNs are transformed into ONAP LCNs.
56  * The following CBAM LCNs are processed:
57  * - HEAL
58  * - INSTANTIATE
59  * - SCALE
60  * - TERMINATE
61  * The current limitations
62  * - if a LCN can not be be processed due to VNF having been deleted the problem is logged and CBAM is notified that
63  * the LCN has been processed (even if not in reality) because the signaling of failed LCN delivery blocks the delivery
64  * on all LCN deliveries. The consequence of this is that the information known by VF-C / A&AI may be inconsistent with
65  * reality (VNF having been deleted)
66  */
67 @Component
68 public class LifecycleChangeNotificationManager implements ILifecycleChangeNotificationManager {
69
70     public static final String PROBLEM = "All operations must return the { \"operationResult\" : { \"cbam_pre\" : [<fillMeOut>], \"cbam_post\" : [<fillMeOut>] } } structure";
71     /**
72      * Order the operations by start time (latest first)
73      */
74     public static final Ordering<OperationExecution> NEWEST_OPERATIONS_FIRST = new Ordering<OperationExecution>() {
75         @Override
76         public int compare(OperationExecution left, OperationExecution right) {
77             return right.getStartTime().toLocalDate().compareTo(left.getStartTime().toLocalDate());
78         }
79     };
80     /**
81      * < Separates the VNF id and the resource id within a VNF
82      */
83     private static final Set<OperationStatus> terminalStatus = newHashSet(OperationStatus.FINISHED, OperationStatus.FAILED);
84     private static Logger logger = getLogger(LifecycleChangeNotificationManager.class);
85
86     private final CbamRestApiProvider restApiProvider;
87     private final DriverProperties driverProperties;
88     private final INotificationSender notificationSender;
89     private Set<ProcessedNotification> processedNotifications = newConcurrentHashSet();
90
91     @Autowired
92     LifecycleChangeNotificationManager(CbamRestApiProvider restApiProvider, DriverProperties driverProperties, INotificationSender notificationSender) {
93         this.notificationSender = notificationSender;
94         this.driverProperties = driverProperties;
95         this.restApiProvider = restApiProvider;
96     }
97
98     /**
99      * @param status the status of the operation
100      * @return has the operation finished
101      */
102     public static boolean isTerminal(OperationStatus status) {
103         return terminalStatus.contains(status);
104     }
105
106     @VisibleForTesting
107     static OperationExecution findLastInstantiationBefore(List<OperationExecution> operationExecutions, OperationExecution currentOperation) {
108         return find(NEWEST_OPERATIONS_FIRST.sortedCopy(operationExecutions), (OperationExecution opex2) ->
109                 !opex2.getStartTime().isAfter(currentOperation.getStartTime())
110                         && INSTANTIATE.equals(opex2.getOperationType()));
111     }
112
113     @Override
114     public void handleLcn(VnfLifecycleChangeNotification receivedNotification) {
115         if (logger.isInfoEnabled()) {
116             logger.info("Received LCN: {}", new Gson().toJson(receivedNotification));
117         }
118         VnfsApi cbamLcmApi = restApiProvider.getCbamLcmApi(driverProperties.getVnfmId());
119         try {
120             List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION).blockingFirst();
121             com.google.common.base.Optional<VnfInfo> currentVnf = tryFind(vnfs, vnf -> vnf.getId().equals(receivedNotification.getVnfInstanceId()));
122             String vnfHeader = "The VNF with " + receivedNotification.getVnfInstanceId() + " identifier";
123             if (!currentVnf.isPresent()) {
124                 logger.warn(vnfHeader + " disappeared before being able to process the LCN");
125                 //swallow LCN
126                 return;
127             } else {
128                 VnfInfo vnf = cbamLcmApi.vnfsVnfInstanceIdGet(receivedNotification.getVnfInstanceId(), NOKIA_LCN_API_VERSION).blockingFirst();
129                 com.google.common.base.Optional<VnfProperty> externalVnfmId = tryFind(vnf.getExtensions(), prop -> prop.getName().equals(LifecycleManager.EXTERNAL_VNFM_ID));
130                 if (!externalVnfmId.isPresent()) {
131                     logger.warn(vnfHeader + " is not a managed VNF");
132                     return;
133                 }
134                 if (!externalVnfmId.get().getValue().equals(driverProperties.getVnfmId())) {
135                     logger.warn(vnfHeader + " is not a managed by the VNFM with id " + externalVnfmId.get().getValue());
136                     return;
137                 }
138             }
139         } catch (Exception e) {
140             throw buildFatalFailure(logger, "Unable to list VNFs / query VNF", e);
141         }
142         OperationExecutionsApi cbamOperationExecutionApi = restApiProvider.getCbamOperationExecutionApi(driverProperties.getVnfmId());
143         List<OperationExecution> operationExecutions;
144         try {
145             operationExecutions = cbamLcmApi.vnfsVnfInstanceIdOperationExecutionsGet(receivedNotification.getVnfInstanceId(), NOKIA_LCM_API_VERSION).blockingFirst();
146         } catch (Exception e) {
147             throw buildFatalFailure(logger, "Unable to retrieve the operation executions for the VNF " + receivedNotification.getVnfInstanceId(), e);
148         }
149         OperationExecution operationExecution;
150         try {
151             operationExecution = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdGet(receivedNotification.getLifecycleOperationOccurrenceId(), NOKIA_LCM_API_VERSION).blockingFirst();
152         } catch (Exception e) {
153             throw buildFatalFailure(logger, "Unable to retrieve the operation execution with " + receivedNotification.getLifecycleOperationOccurrenceId() + " identifier", e);
154         }
155         OperationExecution closestInstantiationToOperation = findLastInstantiationBefore(operationExecutions, operationExecution);
156         String vimId = getVimId(cbamOperationExecutionApi, closestInstantiationToOperation);
157         notificationSender.processNotification(receivedNotification, operationExecution, buildAffectedCps(operationExecution), vimId);
158         if (isTerminationFinished(receivedNotification)) {
159             //signal LifecycleManager to continue the deletion of the VNF
160             processedNotifications.add(new ProcessedNotification(receivedNotification.getLifecycleOperationOccurrenceId(), receivedNotification.getStatus()));
161         }
162     }
163
164     private boolean isTerminationFinished(VnfLifecycleChangeNotification receivedNotification) {
165         return OperationType.TERMINATE.equals(receivedNotification.getOperation()) && terminalStatus.contains(receivedNotification.getStatus());
166     }
167
168     private String getVimId(OperationExecutionsApi cbamOperationExecutionApi, OperationExecution closestInstantiationToOperation) {
169         try {
170             Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(closestInstantiationToOperation.getId(), NOKIA_LCM_API_VERSION).blockingFirst();
171             return getVimId(operationParams);
172         } catch (Exception e) {
173             throw buildFatalFailure(logger, "Unable to detect last instantiation operation", e);
174         }
175     }
176
177     @Override
178     public void waitForTerminationToBeProcessed(String operationExecutionId) {
179         while (true) {
180             com.google.common.base.Optional<ProcessedNotification> notification = tryFind(processedNotifications, processedNotification -> processedNotification.getOperationExecutionId().equals(operationExecutionId));
181             if (notification.isPresent()) {
182                 processedNotifications.remove(notification.get());
183                 return;
184             }
185             SystemFunctions.systemFunctions().sleep(500);
186         }
187     }
188
189     private String getVimId(Object instantiationParameters) {
190         InstantiateVnfRequest request = new Gson().fromJson(new Gson().toJson(instantiationParameters), InstantiateVnfRequest.class);
191         return request.getVims().get(0).getId();
192     }
193
194     private Optional<ReportedAffectedConnectionPoints> buildAffectedCps(OperationExecution operationExecution) {
195         if (!isTerminal(operationExecution.getStatus())) {
196             //connection points can only be calculated after the operation has finished
197             return Optional.empty();
198         }
199         if (operationExecution.getOperationType() == OperationType.TERMINATE) {
200             String terminationType = childElement(new Gson().toJsonTree(operationExecution.getOperationParams()).getAsJsonObject(), "terminationType").getAsString();
201             if (TerminationType.FORCEFUL.name().equals(terminationType)) {
202                 //in case of force full termination the Ansible is not executed, so the connection points can not be
203                 //calculated from operation execution result
204                 logger.warn("Unable to send information related to affected connection points during forceful termination");
205                 return empty();
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, null);
215                 } else {
216                     return of(new Gson().fromJson(operationResult, ReportedAffectedConnectionPoints.class));
217                 }
218             } else {
219                 return handleFailure(operationExecution, null);
220             }
221         } catch (Exception e) {
222             return handleFailure(operationExecution, e);
223         }
224     }
225
226     private boolean isAbsent(JsonObject operationResult, String key) {
227         return !operationResult.has(key) || !operationResult.get(key).isJsonArray();
228     }
229
230     private Optional<ReportedAffectedConnectionPoints> handleFailure(OperationExecution operationExecution, Exception e) {
231         if (operationExecution.getStatus() == OperationStatus.FAILED) {
232             logger.warn("The operation failed and the affected connection points were not reported");
233             return empty();
234         } else {
235             if (e != null) {
236                 throw buildFatalFailure(logger, PROBLEM, e);
237             }
238             throw buildFatalFailure(logger, PROBLEM);
239         }
240     }
241 }