Merge "Updating Nokia driver"
[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.Iterables;
20 import com.google.common.collect.Sets;
21 import com.google.gson.Gson;
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonObject;
24 import com.nokia.cbam.lcm.v32.ApiException;
25 import com.nokia.cbam.lcm.v32.api.OperationExecutionsApi;
26 import com.nokia.cbam.lcm.v32.api.VnfsApi;
27 import com.nokia.cbam.lcm.v32.model.*;
28 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.INotificationSender;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
31 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties;
32 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.ILifecycleChangeNotificationManager;
33 import org.slf4j.Logger;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.stereotype.Component;
36
37 import java.util.List;
38 import java.util.NoSuchElementException;
39 import java.util.Set;
40
41 import static com.google.common.collect.Iterables.filter;
42 import static com.google.common.collect.Iterables.tryFind;
43 import static com.google.common.collect.Sets.newConcurrentHashSet;
44 import static com.nokia.cbam.lcm.v32.model.OperationType.INSTANTIATE;
45 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.childElement;
46 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.fatalFailure;
47 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
48 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCN_API_VERSION;
49 import static org.slf4j.LoggerFactory.getLogger;
50
51 /**
52  * Responsible for handling lifecycle change notifications from CBAM.
53  * The received LCNs are transformed into ONAP LCNs.
54  * The following CBAM LCNs are processed:
55  * - HEAL
56  * - INSTANTIATE
57  * - SCALE
58  * - TERMINATE
59  * The current limitations
60  * - if a LCN can not be be processed due to VNF having been deleted the problem is logged and CBAM is notified that
61  * the LCN has been processed (even if not in reality) because the signaling of failed LCN delivery blocks the delivery
62  * on all LCN deliveries. The consequence of this is that the information known by VF-C / A&AI may be inconsistent with
63  * reality (VNF having been deleted)
64  */
65 @Component
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      * < Separates the VNF id and the resource id within a VNF
71      */
72     private static final Set<OperationStatus> terminalStatus = Sets.newHashSet(OperationStatus.FINISHED, OperationStatus.FAILED);
73     private static Logger logger = getLogger(LifecycleChangeNotificationManager.class);
74
75     private final CbamRestApiProvider restApiProvider;
76     private final DriverProperties driverProperties;
77     private final INotificationSender notificationSender;
78     private Set<ProcessedNotification> processedNotifications = newConcurrentHashSet();
79
80     @Autowired
81     LifecycleChangeNotificationManager(CbamRestApiProvider restApiProvider, DriverProperties driverProperties, INotificationSender notificationSender) {
82         this.notificationSender = notificationSender;
83         this.driverProperties = driverProperties;
84         this.restApiProvider = restApiProvider;
85     }
86
87     @VisibleForTesting
88     static OperationExecution findLastInstantiationBefore(List<OperationExecution> operationExecutions, OperationExecution currentOperation) {
89         for (OperationExecution opExs : filter(NEWEST_OPERATIONS_FIRST.sortedCopy(operationExecutions), (OperationExecution opex2) -> !opex2.getStartTime().isAfter(currentOperation.getStartTime()))) {
90             if (INSTANTIATE.equals(opExs.getOperationType()) &&
91                     (opExs.getStartTime().toLocalDate().isBefore(currentOperation.getStartTime().toLocalDate()) ||
92                             opExs.getStartTime().toLocalDate().isEqual(currentOperation.getStartTime().toLocalDate())
93                     )) {
94                 return opExs;
95             }
96         }
97         throw new NoSuchElementException();
98     }
99
100     @Override
101     public void handleLcn(VnfLifecycleChangeNotification recievedNotification) {
102         logger.info("Received LCN: " + new Gson().toJson(recievedNotification));
103         VnfsApi cbamLcmApi = restApiProvider.getCbamLcmApi(driverProperties.getVnfmId());
104         try {
105             List<VnfInfo> vnfs = cbamLcmApi.vnfsGet(NOKIA_LCM_API_VERSION);
106             com.google.common.base.Optional<VnfInfo> currentVnf = tryFind(vnfs, vnf -> vnf.getId().equals(recievedNotification.getVnfInstanceId()));
107             if (!currentVnf.isPresent()) {
108                 logger.warn("The VNF with " + recievedNotification.getVnfInstanceId() + " disappeared before being able to process the LCN");
109                 //swallow LCN
110                 return;
111             } else {
112                 VnfInfo vnf = cbamLcmApi.vnfsVnfInstanceIdGet(recievedNotification.getVnfInstanceId(), NOKIA_LCN_API_VERSION);
113                 com.google.common.base.Optional<VnfProperty> externalVnfmId = tryFind(vnf.getExtensions(), prop -> prop.getName().equals(EXTERNAL_VNFM_ID));
114                 if (!externalVnfmId.isPresent()) {
115                     logger.warn("The VNF with " + vnf.getId() + " identifier is not a managed VNF");
116                     return;
117                 }
118                 if (!externalVnfmId.get().getValue().equals(driverProperties.getVnfmId())) {
119                     logger.warn("The VNF with " + vnf.getId() + " identifier is not a managed by the VNFM with id " + externalVnfmId.get().getValue());
120                     return;
121                 }
122             }
123         } catch (Exception e) {
124             logger.error("Unable to list VNFs / query VNF", e);
125             throw new RuntimeException("Unable to list VNFs / query VNF", e);
126         }
127         OperationExecutionsApi cbamOperationExecutionApi = restApiProvider.getCbamOperationExecutionApi(driverProperties.getVnfmId());
128         try {
129             List<OperationExecution> operationExecutions = cbamLcmApi.vnfsVnfInstanceIdOperationExecutionsGet(recievedNotification.getVnfInstanceId(), NOKIA_LCM_API_VERSION);
130             OperationExecution operationExecution = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdGet(recievedNotification.getLifecycleOperationOccurrenceId(), NOKIA_LCM_API_VERSION);
131             OperationExecution closestInstantiationToOperation = findLastInstantiationBefore(operationExecutions, operationExecution);
132             String vimId;
133             try {
134                 Object operationParams = cbamOperationExecutionApi.operationExecutionsOperationExecutionIdOperationParamsGet(closestInstantiationToOperation.getId(), NOKIA_LCM_API_VERSION);
135                 vimId = getVimId(operationParams);
136             } catch (Exception e) {
137                 logger.error("Unable to detect last instantiation operation", e);
138                 throw new RuntimeException("Unable to detect last instantiation operation", e);
139             }
140             notificationSender.processNotification(recievedNotification, operationExecution, buildAffectedCps(operationExecution), vimId);
141             if (OperationType.TERMINATE.equals(recievedNotification.getOperation()) && terminalStatus.contains(recievedNotification.getStatus())) {
142                 processedNotifications.add(new ProcessedNotification(recievedNotification.getLifecycleOperationOccurrenceId(), recievedNotification.getStatus()));
143             }
144         } catch (ApiException e) {
145             logger.error("Unable to retrieve the current VNF " + recievedNotification.getVnfInstanceId(), e);
146             throw new RuntimeException("Unable to retrieve the current VNF " + recievedNotification.getVnfInstanceId(), e);
147         }
148     }
149
150     @Override
151     public void waitForTerminationToBeProcessed(String operationExecutionId) {
152         while (true) {
153             com.google.common.base.Optional<ProcessedNotification> notification = Iterables.tryFind(processedNotifications, processedNotification -> processedNotification.getOperationExecutionId().equals(operationExecutionId));
154             if (notification.isPresent()) {
155                 processedNotifications.remove(notification.get());
156                 return;
157             }
158             SystemFunctions.systemFunctions().sleep(500);
159         }
160     }
161
162     private String getVimId(Object instantiationParameters) {
163         InstantiateVnfRequest request = new Gson().fromJson(new Gson().toJson(instantiationParameters), InstantiateVnfRequest.class);
164         return request.getVims().get(0).getId();
165     }
166
167     private ReportedAffectedConnectionPoints buildAffectedCps(OperationExecution operationExecution) {
168         switch (operationExecution.getOperationType()) {
169             case TERMINATE:
170                 String terminationType = childElement(new Gson().toJsonTree(operationExecution.getOperationParams()).getAsJsonObject(), "terminationType").getAsString();
171                 if (TerminationType.FORCEFUL.name().equals(terminationType)) {
172                     //in case of force full termination the Ansible is not executed, so the connection points can not be
173                     //calculated from operation execution result
174                     logger.warn("Unable to send information related to affected connection points during forceful termination");
175                     return null;
176                 }
177         }
178         try {
179             JsonElement root = new Gson().toJsonTree(operationExecution.getAdditionalData());
180             if (root.getAsJsonObject().has("operationResult")) {
181                 JsonObject operationResult = root.getAsJsonObject().get("operationResult").getAsJsonObject();
182                 if (!isPresent(operationResult, "cbam_pre") || !isPresent(operationResult, "cbam_post")) {
183                     handleFailure(operationExecution, null);
184                 }
185                 return new Gson().fromJson(operationResult, ReportedAffectedConnectionPoints.class);
186             }
187         } catch (Exception e) {
188             handleFailure(operationExecution, e);
189         }
190         return new ReportedAffectedConnectionPoints();
191     }
192
193     private boolean isPresent(JsonObject operationResult, String key) {
194         return operationResult.has(key) && operationResult.get(key).isJsonArray();
195     }
196
197     private void handleFailure(OperationExecution operationExecution, Exception e) {
198         switch (operationExecution.getStatus()) {
199             case FAILED:
200             case OTHER:
201                 logger.warn("The operation failed and the affected connection points were not reported");
202                 break;
203             case STARTED: //can not happen (the changed resources are only executed for terminal state
204             case FINISHED:
205                 if (e != null) {
206                     fatalFailure(logger, PROBLEM, e);
207                 }
208                 fatalFailure(logger, PROBLEM);
209         }
210     }
211 }