Adding missing tests
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / vnfm / LifecycleManager.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
17 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm;
18
19
20 import com.google.gson.Gson;
21 import com.google.gson.JsonElement;
22 import com.google.gson.JsonObject;
23 import com.nokia.cbam.catalog.v1.model.CatalogAdapterVnfpackage;
24 import com.nokia.cbam.lcm.v32.ApiException;
25 import com.nokia.cbam.lcm.v32.model.*;
26 import com.nokia.cbam.lcm.v32.model.ScaleDirection;
27 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.IGrantManager;
28 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.api.VimInfoProvider;
29 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.StoreLoader;
30 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.UserVisibleError;
31 import org.onap.vnfmdriver.model.ExtVirtualLinkInfo;
32 import org.onap.vnfmdriver.model.*;
33 import org.onap.vnfmdriver.model.VimInfo;
34 import org.onap.vnfmdriver.model.VnfInfo;
35 import org.slf4j.Logger;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Component;
38 import org.yaml.snakeyaml.Yaml;
39
40 import javax.servlet.http.HttpServletResponse;
41 import java.util.*;
42 import java.util.concurrent.ExecutorService;
43 import java.util.concurrent.Executors;
44
45 import static com.google.common.base.Splitter.on;
46 import static com.google.common.collect.Iterables.find;
47 import static com.google.common.collect.Lists.newArrayList;
48 import static com.google.common.collect.Sets.newHashSet;
49 import static com.nokia.cbam.lcm.v32.model.InstantiationState.INSTANTIATED;
50 import static com.nokia.cbam.lcm.v32.model.OperationStatus.FINISHED;
51 import static com.nokia.cbam.lcm.v32.model.OperationType.INSTANTIATE;
52 import static com.nokia.cbam.lcm.v32.model.VimInfo.VimInfoTypeEnum.*;
53 import static java.lang.Integer.parseInt;
54 import static java.nio.charset.StandardCharsets.UTF_8;
55 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.*;
56 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
57 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCM_API_VERSION;
58 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.notification.LifecycleChangeNotificationManager.NEWEST_OPERATIONS_FIRST;
59 import static org.slf4j.LoggerFactory.getLogger;
60 import static org.springframework.util.StringUtils.isEmpty;
61
62 /**
63  * Responsible for executing lifecycle operation on the VNF
64  */
65 @Component
66 public class LifecycleManager {
67     public static final String ONAP_CSAR_ID = "onapCsarId";
68     public static final long OPERATION_STATUS_POLLING_INTERVAL_IN_MS = 5000L;
69     /**
70      * The key of the CBAM VNF extension for the identifier of the VNFM in ONAP
71      */
72     public static final String EXTERNAL_VNFM_ID = "externalVnfmId";
73     public static final String SCALE_OPERATION_NAME = "scale";
74     private static Logger logger = getLogger(LifecycleManager.class);
75     private final CatalogManager catalogManager;
76     private final IGrantManager grantManager;
77     private final JobManager jobManager;
78     private final ILifecycleChangeNotificationManager notificationManager;
79     private final CbamRestApiProvider cbamRestApiProvider;
80     private final VimInfoProvider vimInfoProvider;
81
82     /**
83      * Runs asynchronous operations in the background
84      */
85     private ExecutorService executorService = Executors.newCachedThreadPool();
86
87     @Autowired
88     LifecycleManager(CatalogManager catalogManager, IGrantManager grantManager, CbamRestApiProvider restApiProvider, VimInfoProvider vimInfoProvider, JobManager jobManager, ILifecycleChangeNotificationManager notificationManager) {
89         this.vimInfoProvider = vimInfoProvider;
90         this.grantManager = grantManager;
91         this.cbamRestApiProvider = restApiProvider;
92         this.jobManager = jobManager;
93         this.notificationManager = notificationManager;
94         this.catalogManager = catalogManager;
95     }
96
97     /**
98      * @param vimId the VIM identifier
99      * @return the name of the region
100      */
101     public static String getRegionName(String vimId) {
102         return newArrayList(on(SEPARATOR).split(vimId)).get(1);
103     }
104
105     /**
106      * @param vimId the VIM identifier
107      * @return the owner of the cloud
108      */
109     public static String getCloudOwner(String vimId) {
110         return newArrayList(on(SEPARATOR).split(vimId)).get(0);
111     }
112
113     private static OperationExecution findLastInstantiation(List<OperationExecution> operationExecutions) {
114         return find(NEWEST_OPERATIONS_FIRST.sortedCopy(operationExecutions), op -> INSTANTIATE.equals(op.getOperationType()));
115     }
116
117     /**
118      * Create the VNF. It consists of the following steps
119      * <ul>
120      * <li>upload the VNF package to CBAM package (if not already there)</li>
121      * <li>create the VNF on CBAM</li>
122      * <li>modify attributes of the VNF (add onapCsarId field)</li>
123      * </ul>
124      * The rollback of the failed operation is not implemented
125      * <ul>
126      * <li>delete the VNF if error occurs before instantiation</li>
127      * <li>terminate & delete VNF if error occurs after instantiation</li>
128      * </ul>
129      *
130      * @param vnfmId          the identifier of the VNFM
131      * @param csarId          the identifier of the VNF package
132      * @param vnfName         the name of the VNF
133      * @param description     the description of the VNF
134      * @param addtionalParams additional parameters for the VNF instantiation request
135      * @return the VNF creation result
136      */
137     public VnfCreationResult create(String vnfmId, String csarId, String vnfName, String description, AdditionalParameters addtionalParams) {
138         logOperationInput("not yet specified", "creation", addtionalParams);
139         validateVimType(addtionalParams.getVimType());
140         try {
141             CatalogAdapterVnfpackage cbamPackage = catalogManager.preparePackageInCbam(vnfmId, csarId);
142             CreateVnfRequest vnfCreateRequest = new CreateVnfRequest();
143             vnfCreateRequest.setVnfdId(cbamPackage.getVnfdId());
144             vnfCreateRequest.setName(vnfName);
145             vnfCreateRequest.setDescription(description);
146             com.nokia.cbam.lcm.v32.model.VnfInfo vnfInfo = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsPost(vnfCreateRequest, NOKIA_LCM_API_VERSION);
147             addVnfdIdToVnfModifyableAttributeExtensions(vnfmId, vnfInfo.getId(), csarId);
148             return new VnfCreationResult(vnfInfo, cbamPackage.getVnfdId());
149         } catch (Exception e) {
150             throw buildFatalFailure(logger, "Unable to create the VNF", e);
151         }
152     }
153
154     private void logOperationInput(String vnfId, String operationName, Object payload) {
155         if (logger.isInfoEnabled()) {
156             logger.info("Starting {} operation on VNF with {} identifier with {} parameter", operationName, vnfId, new Gson().toJson(payload));
157         }
158     }
159
160     /**
161      * Instantiate the VNF
162      *
163      * @param vnfmId               the identifier of the VNFM
164      * @param request              the VNF instantiation request
165      * @param httpResponse         the HTTP response that corresponds to the VNF instantiation request
166      * @param additionalParameters additional parameters
167      * @param vnfId                thr identifier of the VNF
168      * @param vnfdId               the identifier of the VNF package in CBAM
169      * @return the instantiation response
170      */
171     public VnfInstantiateResponse instantiate(String vnfmId, VnfInstantiateRequest request, HttpServletResponse httpResponse, AdditionalParameters additionalParameters, String vnfId, String vnfdId) {
172         logOperationInput(vnfId, "instantiation", request);
173         validateVimType(additionalParameters.getVimType());
174         VnfInstantiateResponse response = new VnfInstantiateResponse();
175         response.setVnfInstanceId(vnfId);
176         String vimId = getVimId(request.getAdditionalParam());
177         JobInfo spawnJob = scheduleExecution(vnfId, httpResponse, "instantiate", jobInfo ->
178                 instantiateVnf(vnfmId, request, additionalParameters, vnfdId, vnfId, vimId, jobInfo)
179         );
180         response.setJobId(spawnJob.getJobId());
181         return response;
182     }
183
184     /**
185      * Instantiate (VF-C terminology) the VNF. It consists of the following steps
186      * <ul>
187      * <li>upload the VNF package to CBAM package (if not already there)</li>
188      * <li>create the VNF on CBAM</li>
189      * <li>modify attributes of the VNF (add onapCsarId field)</li>
190      * <li>asynchronously</li>
191      * <li>request grant from VF-C</li>
192      * <li>instantiate VNF on CBAM</li>
193      * <li>return VNF & job id (after create VNF on CBAM)</li>
194      * <li></li>
195      * </ul>
196      * The rollback of the failed operation is not implemented
197      * <ul>
198      * <li>delete the VNF if error occurs before instantiation</li>
199      * <li>terminate & delete VNf if error occurs after instantiation</li>
200      * </ul>
201      *
202      * @param vnfmId       the identifier of the VNFM
203      * @param request      the instantiation request
204      * @param httpResponse the HTTP response
205      * @return the instantiation response
206      */
207     public VnfInstantiateResponse createAndInstantiate(String vnfmId, VnfInstantiateRequest request, HttpServletResponse httpResponse) {
208         AdditionalParameters additionalParameters = convertInstantiationAdditionalParams(request.getVnfPackageId(), request.getAdditionalParam());
209         VnfCreationResult creationResult = create(vnfmId, request.getVnfDescriptorId(), request.getVnfInstanceName(), request.getVnfInstanceDescription(), additionalParameters);
210         return instantiate(vnfmId, request, httpResponse, additionalParameters, creationResult.vnfInfo.getId(), creationResult.vnfdId);
211     }
212
213     private void instantiateVnf(String vnfmId, VnfInstantiateRequest request, AdditionalParameters additionalParameters, String vnfdId, String vnfId, String vimId, JobInfo jobInfo) throws ApiException {
214         String vnfdContent = catalogManager.getCbamVnfdContent(vnfmId, vnfdId);
215         GrantVNFResponseVim vim = grantManager.requestGrantForInstantiate(vnfmId, vnfId, vimId, request.getVnfPackageId(), additionalParameters.getInstantiationLevel(), vnfdContent, jobInfo.getJobId());
216         if (vim.getVimId() == null) {
217             throw buildFatalFailure(logger, "VF-C did not send VIM identifier in grant response");
218         }
219         VimInfo vimInfo = vimInfoProvider.getVimInfo(vim.getVimId());
220         InstantiateVnfRequest instantiationRequest = new InstantiateVnfRequest();
221         addExternalLinksToRequest(request.getExtVirtualLink(), additionalParameters, instantiationRequest, vimId);
222         instantiationRequest.getVims().add(addVim(additionalParameters, vimId, vim, vimInfo));
223         instantiationRequest.setFlavourId(getFlavorId(vnfdContent));
224         instantiationRequest.setComputeResourceFlavours(additionalParameters.getComputeResourceFlavours());
225         instantiationRequest.setGrantlessMode(true);
226         instantiationRequest.setInstantiationLevelId(additionalParameters.getInstantiationLevel());
227         instantiationRequest.setSoftwareImages(additionalParameters.getSoftwareImages());
228         instantiationRequest.setZones(additionalParameters.getZones());
229         instantiationRequest.setExtManagedVirtualLinks(additionalParameters.getExtManagedVirtualLinks());
230         for (ExtVirtualLinkData extVirtualLinkData : additionalParameters.getExtVirtualLinks()) {
231             instantiationRequest.addExtVirtualLinksItem(extVirtualLinkData);
232         }
233         JsonObject root = new Gson().toJsonTree(jobInfo).getAsJsonObject();
234         if (additionalParameters.getAdditionalParams() != null) {
235             for (Map.Entry<String, JsonElement> item : new Gson().toJsonTree(additionalParameters.getAdditionalParams()).getAsJsonObject().entrySet()) {
236                 root.add(item.getKey(), item.getValue());
237             }
238         } else {
239             logger.warn("No additional parameters were specified for the operation");
240         }
241         instantiationRequest.setAdditionalParams(root);
242         OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdInstantiatePost(vnfId, instantiationRequest, NOKIA_LCM_API_VERSION);
243         waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
244     }
245
246     private com.nokia.cbam.lcm.v32.model.VimInfo addVim(AdditionalParameters additionalParameters, String vimId, GrantVNFResponseVim vim, VimInfo vimInfo) {
247         if (additionalParameters.getVimType() == OPENSTACK_V2_INFO) {
248             return buildOpenStackV2INFO(vimId, vim, vimInfo);
249
250         } else if (additionalParameters.getVimType() == OPENSTACK_V3_INFO) {
251             return buildOpenStackV3INFO(vimId, additionalParameters, vim, vimInfo);
252
253         } else {
254             //OTHER VIM TYPE is not possible
255             return buildVcloudInfo(vimId, vimInfo);
256         }
257     }
258
259     private void validateVimType(com.nokia.cbam.lcm.v32.model.VimInfo.VimInfoTypeEnum vimType) {
260         if (com.nokia.cbam.lcm.v32.model.VimInfo.VimInfoTypeEnum.OTHER_VIM_INFO.equals(vimType)) {
261             throw buildFatalFailure(logger, "Only " + OPENSTACK_V2_INFO + ", " + OPENSTACK_V3_INFO + " and " + VMWARE_VCLOUD_INFO + " is the supported VIM types");
262         }
263     }
264
265     private String getVimId(Object additionalParams) {
266         return childElement(new Gson().toJsonTree(additionalParams).getAsJsonObject(), "vimId").getAsString();
267     }
268
269     private AdditionalParameters convertInstantiationAdditionalParams(String csarId, Object additionalParams) {
270         JsonObject vnfParameters = child(child(new Gson().toJsonTree(additionalParams).getAsJsonObject(), "inputs"), "vnfs");
271         if (!vnfParameters.has(csarId)) {
272             throw buildFatalFailure(logger, "The additional parameter section does not contain setting for VNF with " + csarId + " CSAR id");
273         }
274         JsonElement additionalParamsForVnf = vnfParameters.get(csarId);
275         return new Gson().fromJson(additionalParamsForVnf, AdditionalParameters.class);
276     }
277
278     private String getFlavorId(String vnfdContent) {
279         JsonObject root = new Gson().toJsonTree(new Yaml().load(vnfdContent)).getAsJsonObject();
280         JsonObject capabilities = child(child(child(root, "topology_template"), "substitution_mappings"), "capabilities");
281         JsonObject deploymentFlavorProperties = child(child(capabilities, "deployment_flavour"), "properties");
282         return childElement(deploymentFlavorProperties, "flavour_id").getAsString();
283     }
284
285     private Set<String> getAcceptableOperationParameters(String vnfdContent, String categroryOfOperation, String operationName) {
286         JsonObject root = new Gson().toJsonTree(new Yaml().load(vnfdContent)).getAsJsonObject();
287         JsonObject interfaces = child(child(child(root, "topology_template"), "substitution_mappings"), "interfaces");
288         JsonObject additionalParameters = child(child(child(child(interfaces, categroryOfOperation), operationName), "inputs"), "additional_parameters");
289         return additionalParameters.keySet();
290     }
291
292     private void addExternalLinksToRequest(List<ExtVirtualLinkInfo> extVirtualLinks, AdditionalParameters additionalParameters, InstantiateVnfRequest instantiationRequest, String vimId) {
293         for (ExtVirtualLinkInfo extVirtualLink : extVirtualLinks) {
294             ExtVirtualLinkData cbamExternalVirtualLink = new ExtVirtualLinkData();
295             cbamExternalVirtualLink.setVimId(vimId);
296             cbamExternalVirtualLink.setResourceId(extVirtualLink.getResourceId());
297             VnfExtCpData ecp = new VnfExtCpData();
298             cbamExternalVirtualLink.setExtVirtualLinkId(extVirtualLink.getVlInstanceId());
299             cbamExternalVirtualLink.getExtCps().add(ecp);
300             ecp.setCpdId(extVirtualLink.getCpdId());
301             List<NetworkAddress> addresses = additionalParameters.getExternalConnectionPointAddresses().get(extVirtualLink.getCpdId());
302             ecp.setAddresses(addresses);
303             instantiationRequest.addExtVirtualLinksItem(cbamExternalVirtualLink);
304         }
305     }
306
307     private void addVnfdIdToVnfModifyableAttributeExtensions(String vnfmId, String vnfId, String onapCsarId) {
308         ModifyVnfInfoRequest request = new ModifyVnfInfoRequest();
309         VnfProperty onapCsarIdProperty = new VnfProperty();
310         onapCsarIdProperty.setName(ONAP_CSAR_ID);
311         onapCsarIdProperty.setValue(onapCsarId);
312         request.setExtensions(new ArrayList<>());
313         request.getExtensions().add(onapCsarIdProperty);
314         VnfProperty externalVnfmIdProperty = new VnfProperty();
315         externalVnfmIdProperty.setName(EXTERNAL_VNFM_ID);
316         externalVnfmIdProperty.setValue(vnfmId);
317         request.getExtensions().add(externalVnfmIdProperty);
318         request.setVnfConfigurableProperties(null);
319         try {
320             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdPatch(vnfId, request, NOKIA_LCM_API_VERSION);
321             waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
322         } catch (ApiException e) {
323             throw buildFatalFailure(logger, "Unable to set the " + ONAP_CSAR_ID + " property on the VNF", e);
324         }
325     }
326
327     private OPENSTACKV3INFO buildOpenStackV3INFO(String vimId, AdditionalParameters additionalParameters, GrantVNFResponseVim vim, org.onap.vnfmdriver.model.VimInfo vimInfo) {
328         OPENSTACKV3INFO openstackv3INFO = new OPENSTACKV3INFO();
329         openstackv3INFO.setVimInfoType(OPENSTACK_V3_INFO);
330         OpenStackAccessInfoV3 accessInfov3 = new OpenStackAccessInfoV3();
331         openstackv3INFO.accessInfo(accessInfov3);
332         accessInfov3.setPassword(vimInfo.getPassword());
333         accessInfov3.setDomain(additionalParameters.getDomain());
334         accessInfov3.setProject(vim.getAccessInfo().getTenant());
335         accessInfov3.setRegion(getRegionName(vimId));
336         accessInfov3.setUsername(vimInfo.getUserName());
337         EndpointInfo interfaceInfoV3 = new EndpointInfo();
338         interfaceInfoV3.setEndpoint(vimInfo.getUrl());
339         if (!isEmpty(vimInfo.getSslInsecure())) {
340             interfaceInfoV3.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
341             interfaceInfoV3.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
342         } else {
343             interfaceInfoV3.setSkipCertificateHostnameCheck(true);
344             interfaceInfoV3.setSkipCertificateVerification(true);
345         }
346         if (!interfaceInfoV3.isSkipCertificateVerification()) {
347             interfaceInfoV3.setTrustedCertificates(new ArrayList<>());
348             for (String trustedCertificate : StoreLoader.getCertifacates(vimInfo.getSslCacert())) {
349                 interfaceInfoV3.getTrustedCertificates().add(trustedCertificate.getBytes(UTF_8));
350             }
351         }
352         openstackv3INFO.setInterfaceInfo(interfaceInfoV3);
353         openstackv3INFO.setId(vimId);
354         return openstackv3INFO;
355     }
356
357     private OPENSTACKV2INFO buildOpenStackV2INFO(String vimId, GrantVNFResponseVim vim, org.onap.vnfmdriver.model.VimInfo vimInfo) {
358         OPENSTACKV2INFO openstackv2INFO = new OPENSTACKV2INFO();
359         openstackv2INFO.setVimInfoType(OPENSTACK_V2_INFO);
360         OpenStackAccessInfoV2 accessInfo = new OpenStackAccessInfoV2();
361         openstackv2INFO.setAccessInfo(accessInfo);
362         accessInfo.setPassword(vimInfo.getPassword());
363         accessInfo.setTenant(vim.getAccessInfo().getTenant());
364         accessInfo.setUsername(vimInfo.getUserName());
365         accessInfo.setRegion(getRegionName(vimId));
366         EndpointInfo interfaceEndpoint = new EndpointInfo();
367         if (!isEmpty(vimInfo.getSslInsecure())) {
368             interfaceEndpoint.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
369             interfaceEndpoint.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
370         } else {
371             interfaceEndpoint.setSkipCertificateHostnameCheck(true);
372             interfaceEndpoint.setSkipCertificateVerification(true);
373         }
374         interfaceEndpoint.setEndpoint(vimInfo.getUrl());
375         if (!interfaceEndpoint.isSkipCertificateVerification()) {
376             interfaceEndpoint.setTrustedCertificates(new ArrayList<>());
377             for (String trustedCertificate : StoreLoader.getCertifacates(vimInfo.getSslCacert())) {
378                 interfaceEndpoint.getTrustedCertificates().add(trustedCertificate.getBytes(UTF_8));
379             }
380         }
381         openstackv2INFO.setInterfaceInfo(interfaceEndpoint);
382         openstackv2INFO.setId(vimId);
383         return openstackv2INFO;
384     }
385
386     private VMWAREVCLOUDINFO buildVcloudInfo(String vimId, org.onap.vnfmdriver.model.VimInfo vimInfo) {
387         VMWAREVCLOUDINFO vcloudInfo = new VMWAREVCLOUDINFO();
388         vcloudInfo.setVimInfoType(VMWARE_VCLOUD_INFO);
389         VCloudAccessInfo accessInfo = new VCloudAccessInfo();
390         vcloudInfo.setAccessInfo(accessInfo);
391         accessInfo.setPassword(vimInfo.getPassword());
392         accessInfo.setUsername(vimInfo.getUserName());
393         accessInfo.setOrganization(getRegionName(vimId));
394         EndpointInfo interfaceEndpoint = new EndpointInfo();
395         if (!isEmpty(vimInfo.getSslInsecure())) {
396             interfaceEndpoint.setSkipCertificateHostnameCheck(Boolean.parseBoolean(vimInfo.getSslInsecure()));
397             interfaceEndpoint.setSkipCertificateVerification(Boolean.parseBoolean(vimInfo.getSslInsecure()));
398         } else {
399             interfaceEndpoint.setSkipCertificateHostnameCheck(true);
400             interfaceEndpoint.setSkipCertificateVerification(true);
401         }
402         interfaceEndpoint.setEndpoint(vimInfo.getUrl());
403         if (!interfaceEndpoint.isSkipCertificateVerification()) {
404             interfaceEndpoint.setTrustedCertificates(new ArrayList<>());
405             for (String trustedCertificate : StoreLoader.getCertifacates(vimInfo.getSslCacert())) {
406                 interfaceEndpoint.getTrustedCertificates().add(trustedCertificate.getBytes(UTF_8));
407             }
408         }
409         vcloudInfo.setInterfaceInfo(interfaceEndpoint);
410         vcloudInfo.setId(vimId);
411         return vcloudInfo;
412     }
413
414     /**
415      * Terminates and deletes the VNF
416      * <ul>
417      * <li>fails if the VNF does not exist</li>
418      * <li>terminates if instantiated</li>
419      * <li>deletes the VNF</li>
420      * </ul>
421      *
422      * @param vnfmId       the identifier of the VNFM
423      * @param vnfId        the identifier of the VNF
424      * @param request      the termination request
425      * @param httpResponse the HTTP response
426      * @return the job for polling the progress of the termination
427      */
428     public JobInfo terminateVnf(String vnfmId, String vnfId, VnfTerminateRequest request, HttpServletResponse httpResponse) {
429         logOperationInput(vnfId, "termination", request);
430         return scheduleExecution(vnfId, httpResponse, "terminate", jobInfo -> {
431             TerminateVnfRequest cbamRequest = new TerminateVnfRequest();
432             cbamRequest.setAdditionalParams(jobInfo);
433             if (request.getTerminationType() == null) {
434                 cbamRequest.setTerminationType(TerminationType.FORCEFUL);
435             } else {
436                 if (request.getTerminationType().equals(VnfTerminationType.GRACEFUL)) {
437                     cbamRequest.setTerminationType(TerminationType.GRACEFUL);
438                     cbamRequest.setGracefulTerminationTimeout(parseInt(request.getGracefulTerminationTimeout()));
439                 } else {
440                     cbamRequest.setTerminationType(TerminationType.FORCEFUL);
441                 }
442             }
443             com.nokia.cbam.lcm.v32.model.VnfInfo vnf = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
444             if (vnf.getInstantiationState() == INSTANTIATED) {
445                 terminateVnf(vnfmId, vnfId, jobInfo, cbamRequest, vnf);
446             } else {
447                 cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
448             }
449         });
450     }
451
452     private void terminateVnf(String vnfmId, String vnfId, JobInfo jobInfo, TerminateVnfRequest cbamRequest, com.nokia.cbam.lcm.v32.model.VnfInfo vnf) throws ApiException {
453         String vimId = getVimIdFromInstantiationRequest(vnfmId, vnf);
454         grantManager.requestGrantForTerminate(vnfmId, vnfId, vimId, getVnfdIdFromModifyableAttributes(vnf), vnf, jobInfo.getJobId());
455         OperationExecution terminationOperation = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdTerminatePost(vnfId, cbamRequest, NOKIA_LCM_API_VERSION);
456         OperationExecution finishedOperation = waitForOperationToFinish(vnfmId, vnfId, terminationOperation.getId());
457         if (finishedOperation.getStatus() == FINISHED) {
458             notificationManager.waitForTerminationToBeProcessed(finishedOperation.getId());
459             logger.info("Deleting VNF with {}", vnfId);
460             cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdDelete(vnfId, NOKIA_LCM_API_VERSION);
461             logger.info("VNF with {} has been deleted", vnfId);
462
463         } else {
464             logger.error("Unable to terminate VNF the operation did not finish with success");
465         }
466     }
467
468     private String getVimIdFromInstantiationRequest(String vnfmId, com.nokia.cbam.lcm.v32.model.VnfInfo vnf) throws ApiException {
469         OperationExecution lastInstantiation = findLastInstantiation(vnf.getOperationExecutions());
470         Object operationParameters = cbamRestApiProvider.getCbamOperationExecutionApi(vnfmId).operationExecutionsOperationExecutionIdOperationParamsGet(lastInstantiation.getId(), NOKIA_LCM_API_VERSION);
471         JsonObject root = new Gson().toJsonTree(operationParameters).getAsJsonObject();
472         return childElement(childElement(root, "vims").getAsJsonArray().get(0).getAsJsonObject(), "id").getAsString();
473     }
474
475     private String getVnfdIdFromModifyableAttributes(com.nokia.cbam.lcm.v32.model.VnfInfo vnf) {
476         return find(vnf.getExtensions(), p -> p.getName().equals(ONAP_CSAR_ID)).getValue().toString();
477     }
478
479     /**
480      * @param vnfmId the identifier of the VNFM
481      * @param vnfId  the identifier of the VNF
482      * @return the current state of the VNF
483      */
484     public VnfInfo queryVnf(String vnfmId, String vnfId) {
485         try {
486             com.nokia.cbam.lcm.v32.model.VnfInfo cbamVnfInfo = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
487             VnfInfo vnfInfo = new VnfInfo();
488             vnfInfo.setVersion(cbamVnfInfo.getVnfSoftwareVersion());
489             vnfInfo.setVnfInstanceId(vnfId);
490             String onapCsarId = getVnfdIdFromModifyableAttributes(cbamVnfInfo);
491             vnfInfo.setVnfdId(onapCsarId);
492             vnfInfo.setVnfPackageId(onapCsarId);
493             vnfInfo.setVnfInstanceDescription(cbamVnfInfo.getDescription());
494             vnfInfo.setVnfInstanceName(cbamVnfInfo.getName());
495             vnfInfo.setVnfProvider(cbamVnfInfo.getVnfProvider());
496             vnfInfo.setVnfStatus("ACTIVE");
497             vnfInfo.setVnfType("Kuku");
498             return vnfInfo;
499         } catch (ApiException e) {
500             throw buildFatalFailure(logger, "Unable to query VNF (" + vnfId + ")", e);
501         }
502     }
503
504     private ScaleDirection convert(org.onap.vnfmdriver.model.ScaleDirection direction) {
505         if (org.onap.vnfmdriver.model.ScaleDirection.IN.equals(direction)) {
506             return ScaleDirection.IN;
507         } else {
508             return ScaleDirection.OUT;
509         }
510     }
511
512     /**
513      * Scale the VNF
514      *
515      * @param vnfmId       the identifier of the VNFM
516      * @param vnfId        the identifier of the VNF
517      * @param request      the scale request
518      * @param httpResponse the HTTP response
519      * @return the job for tracking the scale
520      */
521     public JobInfo scaleVnf(String vnfmId, String vnfId, VnfScaleRequest request, HttpServletResponse httpResponse) {
522         logOperationInput(vnfId, SCALE_OPERATION_NAME, request);
523         return scheduleExecution(vnfId, httpResponse, SCALE_OPERATION_NAME, jobInfo -> {
524             ScaleVnfRequest cbamRequest = new ScaleVnfRequest();
525             cbamRequest.setAspectId(request.getAspectId());
526             cbamRequest.setNumberOfSteps(Integer.valueOf(request.getNumberOfSteps()));
527             cbamRequest.setType(convert(request.getType()));
528             com.nokia.cbam.lcm.v32.model.VnfInfo vnf = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
529             JsonObject root = new Gson().toJsonTree(jobInfo).getAsJsonObject();
530             com.nokia.cbam.lcm.v32.model.VnfInfo cbamVnfInfo = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
531             String vnfdContent = catalogManager.getCbamVnfdContent(vnfmId, cbamVnfInfo.getVnfdId());
532             Set<String> acceptableOperationParameters = getAcceptableOperationParameters(vnfdContent, "Basic", SCALE_OPERATION_NAME);
533             buildAdditionalParameters(request, root, acceptableOperationParameters);
534             cbamRequest.setAdditionalParams(root);
535             grantManager.requestGrantForScale(vnfmId, vnfId, getVimIdFromInstantiationRequest(vnfmId, vnf), getVnfdIdFromModifyableAttributes(vnf), request, jobInfo.getJobId());
536             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdScalePost(vnfId, cbamRequest, NOKIA_LCM_API_VERSION);
537             waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
538         });
539     }
540
541     private void buildAdditionalParameters(VnfScaleRequest request, JsonObject root, Set<String> acceptableOperationParameters) {
542         if (request.getAdditionalParam() != null) {
543             for (Map.Entry<String, JsonElement> item : new Gson().toJsonTree(request.getAdditionalParam()).getAsJsonObject().entrySet()) {
544                 if (acceptableOperationParameters.contains(item.getKey())) {
545                     root.add(item.getKey(), item.getValue());
546                 }
547             }
548         } else {
549             logger.warn("No additional parameters were passed for scaling");
550         }
551     }
552
553     /**
554      * Heal the VNF
555      *
556      * @param vnfmId       the identifier of the VNFM
557      * @param vnfId        the identifier of the VNF
558      * @param request      the heal request
559      * @param httpResponse the HTTP response
560      * @return the job for tracking the heal
561      */
562     public JobInfo healVnf(String vnfmId, String vnfId, VnfHealRequest request, HttpServletResponse httpResponse) {
563         logOperationInput(vnfId, "heal", request);
564         return scheduleExecution(vnfId, httpResponse, "heal", job -> {
565             HealVnfRequest cbamHealRequest = new HealVnfRequest();
566             Map<String, String> additionalParams = new HashMap<>();
567             additionalParams.put("vmName", request.getAffectedvm().getVmname());
568             additionalParams.put("action", request.getAction());
569             additionalParams.put("jobId", job.getJobId());
570             cbamHealRequest.setAdditionalParams(additionalParams);
571             com.nokia.cbam.lcm.v32.model.VnfInfo vnf = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdGet(vnfId, NOKIA_LCM_API_VERSION);
572             String vimId = getVimIdFromInstantiationRequest(vnfmId, vnf);
573             grantManager.requestGrantForHeal(vnfmId, vnfId, vimId, getVnfdIdFromModifyableAttributes(vnf), request, job.getJobId());
574             OperationExecution operationExecution = cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdHealPost(vnfId, cbamHealRequest, NOKIA_LCM_API_VERSION);
575             waitForOperationToFinish(vnfmId, vnfId, operationExecution.getId());
576         });
577     }
578
579     private JobInfo scheduleExecution(String vnfId, HttpServletResponse httpResponse, String operation, AsynchronousExecution asynchronExecution) {
580         JobInfo jobInfo = new JobInfo();
581         jobInfo.setJobId(jobManager.spawnJob(vnfId, httpResponse));
582         executorService.submit(() -> {
583             try {
584                 asynchronExecution.execute(jobInfo);
585             } catch (RuntimeException e) {
586                 logger.error("Unable to " + operation + " VNF with " + vnfId + " identifier", e);
587                 jobManager.jobFinished(jobInfo.getJobId());
588                 throw e;
589             } catch (Exception e) {
590                 String msg = "Unable to " + operation + " VNF with " + vnfId + " identifier";
591                 logger.error(msg, e);
592                 //the job can only be signaled to be finished after the error is logged
593                 jobManager.jobFinished(jobInfo.getJobId());
594                 throw new UserVisibleError(msg, e);
595             }
596             jobManager.jobFinished(jobInfo.getJobId());
597         });
598         return jobInfo;
599     }
600
601     private OperationExecution waitForOperationToFinish(String vnfmId, String vnfId, String operationExecutionId) {
602         while (true) {
603             try {
604                 OperationExecution operationExecution = find(cbamRestApiProvider.getCbamLcmApi(vnfmId).vnfsVnfInstanceIdOperationExecutionsGet(vnfId, NOKIA_LCM_API_VERSION), opEx -> operationExecutionId.equals(opEx.getId()));
605                 if (hasOperationFinished(operationExecution)) {
606                     logger.debug("Operation finished with " + operationExecution.getId());
607                     return operationExecution;
608                 }
609             } catch (Exception e) {
610                 //swallow exception and retry
611                 logger.warn("Unable to retrieve operations details", e);
612             }
613             systemFunctions().sleep(OPERATION_STATUS_POLLING_INTERVAL_IN_MS);
614         }
615     }
616
617     private boolean hasOperationFinished(OperationExecution operationExecution) {
618         return newHashSet(FINISHED, OperationStatus.FAILED).contains(operationExecution.getStatus());
619     }
620
621     @FunctionalInterface
622     private interface AsynchronousExecution {
623         void execute(JobInfo job) throws ApiException;
624     }
625
626     private static class VnfCreationResult {
627         private com.nokia.cbam.lcm.v32.model.VnfInfo vnfInfo;
628         private String vnfdId;
629
630         VnfCreationResult(com.nokia.cbam.lcm.v32.model.VnfInfo vnfInfo, String vnfdId) {
631             this.vnfInfo = vnfInfo;
632             this.vnfdId = vnfdId;
633         }
634     }
635 }