Fixed Sonar blocker issues
[so.git] / adapters / mso-adapter-utils / src / main / java / org / onap / so / openstack / utils / MsoMulticloudUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Intel Corp. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.openstack.utils;
24
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.woorea.openstack.heat.model.CreateStackParam;
28 import java.net.MalformedURLException;
29 import java.net.URL;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Scanner;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.UriBuilder;
37 import javax.ws.rs.core.UriBuilderException;
38 import org.onap.so.adapters.vdu.CloudInfo;
39 import org.onap.so.adapters.vdu.PluginAction;
40 import org.onap.so.adapters.vdu.VduArtifact;
41 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
42 import org.onap.so.adapters.vdu.VduException;
43 import org.onap.so.adapters.vdu.VduInstance;
44 import org.onap.so.adapters.vdu.VduModelInfo;
45 import org.onap.so.adapters.vdu.VduPlugin;
46 import org.onap.so.adapters.vdu.VduStateType;
47 import org.onap.so.adapters.vdu.VduStatus;
48 import org.onap.so.client.HttpClientFactory;
49 import org.onap.so.client.RestClient;
50 import org.onap.so.logger.ErrorCode;
51 import org.onap.so.logger.MessageEnum;
52 import org.onap.so.openstack.beans.HeatStatus;
53 import org.onap.so.openstack.beans.StackInfo;
54 import org.onap.so.openstack.exceptions.MsoAdapterException;
55 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
56 import org.onap.so.openstack.exceptions.MsoException;
57 import org.onap.so.openstack.exceptions.MsoOpenstackException;
58 import org.onap.so.utils.TargetEntity;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.core.env.Environment;
63 import org.springframework.stereotype.Component;
64
65 @Component
66 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
67
68     public static final String OOF_DIRECTIVES = "oof_directives";
69     public static final String SDNC_DIRECTIVES = "sdnc_directives";
70     public static final String USER_DIRECTIVES = "user_directives";
71     public static final String VNF_ID = "vnf_id";
72     public static final String VF_MODULE_ID = "vf_module_id";
73     public static final String TEMPLATE_TYPE = "template_type";
74     public static final String MULTICLOUD_QUERY_BODY_NULL = "multicloudQueryBody is null";
75     public static final List<String> MULTICLOUD_INPUTS =
76             Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, USER_DIRECTIVES, TEMPLATE_TYPE);
77
78     private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
79
80     private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
81     private static final Integer DEFAULT_MSB_PORT = 80;
82     private static final String DEFAULT_MSB_IP = "127.0.0.1";
83     private static final String ONAP_IP = "ONAP_IP";
84     private final HttpClientFactory httpClientFactory = new HttpClientFactory();
85
86     @Autowired
87     private Environment environment;
88
89     /******************************************************************************
90      *
91      * Methods (and associated utilities) to implement the VduPlugin interface
92      *
93      *******************************************************************************/
94
95     /**
96      * Create a new Stack in the specified cloud location and tenant. The Heat template
97      * and parameter map are passed in as arguments, along with the cloud access credentials.
98      * It is expected that parameters have been validated and contain at minimum the required
99      * parameters for the given template with no extra (undefined) parameters..
100      *
101      * The Stack name supplied by the caller must be unique in the scope of this tenant.
102      * However, it should also be globally unique, as it will be the identifier for the
103      * resource going forward in Inventory. This latter is managed by the higher levels
104      * invoking this function.
105      *
106      * The caller may choose to let this function poll Openstack for completion of the
107      * stack creation, or may handle polling itself via separate calls to query the status.
108      * In either case, a StackInfo object will be returned containing the current status.
109      * When polling is enabled, a status of CREATED is expected. When not polling, a
110      * status of BUILDING is expected.
111      *
112      * An error will be thrown if the requested Stack already exists in the specified
113      * Tenant and Cloud.
114      *
115      * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
116      * parameters for createStack. If environment is non-null, it will be added to the stack.
117      * The nested templates and get_file entries both end up being added to the "files" on the
118      * stack. We must combine them before we add them to the stack if they're both non-null.
119      *
120      * @param cloudSiteId The cloud (may be a region) in which to create the stack
121      * @param cloudOwner the cloud owner of the cloud site in which to create the stack
122      * @param tenantId The Openstack ID of the tenant in which to create the Stack
123      * @param stackName The name of the stack to create
124      * @param heatTemplate The Heat template
125      * @param stackInputs A map of key/value inputs
126      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
127      * @param environment An optional yaml-format string to specify environmental parameters
128      * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
129      *        Template id)
130      * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
131      * @param backout Do not delete stack on create Failure - defaulted to True
132      * @return A StackInfo object
133      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
134      */
135
136     @SuppressWarnings("unchecked")
137     @Override
138     public StackInfo createStack (String cloudSiteId,
139                                   String cloudOwner,
140                                   String tenantId,
141                                   String stackName,
142                                   VduModelInfo vduModel,
143                                   String heatTemplate,
144                                   Map <String, ?> stackInputs,
145                                   boolean pollForCompletion,
146                                   int timeoutMinutes,
147                                   String environment,
148                                   Map <String, Object> files,
149                                   Map <String, Object> heatFiles,
150                                   boolean backout) throws MsoException {
151
152         logger.trace("Started MsoMulticloudUtils.createStack");
153
154         // Get the directives, if present.
155         String oofDirectives = "{}";
156         String sdncDirectives = "{}";
157         String userDirectives = "{}";
158         String genericVnfId = "";
159         String vfModuleId = "";
160         String templateType = "";
161
162         for (String key: MULTICLOUD_INPUTS) {
163             if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
164                 if (key == OOF_DIRECTIVES) {
165                     oofDirectives = (String) stackInputs.get(key);
166                 }
167                 if (key == SDNC_DIRECTIVES) {
168                     sdncDirectives = (String) stackInputs.get(key);
169                 }
170                 if (key == USER_DIRECTIVES) {
171                     sdncDirectives = (String) stackInputs.get(key);
172                 }
173                 if (key == TEMPLATE_TYPE) {
174                     templateType = (String) stackInputs.get(key);
175                 }
176                 if (logger.isDebugEnabled()) {
177                     logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
178                 }
179                 stackInputs.remove(key);
180             }
181         }
182
183         if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
184             vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
185         }
186         if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
187             genericVnfId = (String) stackInputs.get(VNF_ID);
188         }
189
190         // create the multicloud payload
191         CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
192
193         MulticloudRequest multicloudRequest= new MulticloudRequest();
194
195         multicloudRequest.setGenericVnfId(genericVnfId);
196         multicloudRequest.setVfModuleId(vfModuleId);
197         multicloudRequest.setVfModuleModelInvariantId(vduModel.getModelInvariantUUID());
198         multicloudRequest.setVfModuleModelVersionId(vduModel.getModelUUID());
199         multicloudRequest.setVfModuleModelCustomizationId(vduModel.getModelCustomizationUUID());
200         multicloudRequest.setTemplateType(templateType);
201         multicloudRequest.setTemplateData(stack);
202         multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives));
203         multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives));
204         multicloudRequest.setUserDirectives(getDirectiveNode(userDirectives));
205         if (logger.isDebugEnabled()) {
206             logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
207         }
208
209         String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, null);
210         RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
211
212         if (multicloudClient == null) {
213             MsoOpenstackException me = new MsoOpenstackException(0, "", "Multicloud client could not be initialized");
214             me.addContext(CREATE_STACK);
215             throw me;
216         }
217
218         Response response = multicloudClient.post(multicloudRequest);
219
220         MulticloudCreateResponse multicloudResponseBody = null;
221         if (response.hasEntity()) {
222             multicloudResponseBody = getCreateBody((java.io.InputStream) response.getEntity());
223         }
224         if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
225             String canonicalName = stackName + "/";
226             if (multicloudResponseBody != null) {
227                 canonicalName = canonicalName + multicloudResponseBody.getWorkloadId();
228             }
229             if (logger.isDebugEnabled()) {
230                 logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
231             }
232             return getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion, timeoutMinutes, backout);
233         }
234         StringBuilder stackErrorStatusReason = new StringBuilder(response.getStatusInfo().getReasonPhrase());
235         if (null != multicloudResponseBody) {
236             stackErrorStatusReason.append(multicloudResponseBody.toString());
237         }
238         MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
239         me.addContext(CREATE_STACK);
240         throw me;
241     }
242
243     @Override
244     public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
245                                                            String tenantId, String stackName) throws MsoException {
246         logger.debug("MsoHeatUtils.queryStackForOutputs)");
247         StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
248         if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
249             return null;
250         }
251         return heatStack.getOutputs();
252     }
253
254     /**
255      * Query for a single stack (by ID) in a tenant. This call will always return a
256      * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
257      * returned - containing only the stack name and a status of NOTFOUND.
258      *
259      * @param tenantId The Openstack ID of the tenant in which to query
260      * @param cloudSiteId The cloud identifier (may be a region) in which to query
261      * @param cloudOwner cloud owner of the cloud site in which to query
262      * @param stackId The ID of the stack to query
263      * @return A StackInfo object
264      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
265      */
266     @Override
267     public StackInfo queryStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
268         if (logger.isDebugEnabled()) {
269             logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
270         }
271         String stackName = null;
272         String stackId = null;
273         int offset = instanceId.indexOf('/');
274         if (offset > 0 && offset < (instanceId.length() - 1)) {
275             stackName = instanceId.substring(0, offset);
276             stackId = instanceId.substring(offset + 1);
277         } else {
278             stackName = instanceId;
279             stackId = instanceId;
280         }
281
282         StackInfo returnInfo = new StackInfo();
283         returnInfo.setName(stackName);
284
285         String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
286         RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
287
288         if (multicloudClient != null) {
289             Response response = multicloudClient.get();
290             if (logger.isDebugEnabled()) {
291                 logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
292             }
293
294             MulticloudQueryResponse multicloudQueryBody = null;
295             if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
296                 returnInfo.setStatus(HeatStatus.NOTFOUND);
297                 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
298             } else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
299                 multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
300                 if (multicloudQueryBody != null) {
301                     returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
302                     returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
303                     returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
304                     if (logger.isDebugEnabled()) {
305                         logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
306                     }
307                 } else {
308                     returnInfo.setStatus(HeatStatus.FAILED);
309                     returnInfo.setStatusMessage(MULTICLOUD_QUERY_BODY_NULL);
310                 }
311             } else {
312                 returnInfo.setStatus(HeatStatus.FAILED);
313                 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
314             }
315         }
316
317         return returnInfo;
318     }
319
320     public StackInfo deleteStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
321         if (logger.isDebugEnabled()) {
322             logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
323         }
324         String stackName = null;
325         String stackId = null;
326         int offset = instanceId.indexOf('/');
327         if (offset > 0 && offset < (instanceId.length() - 1)) {
328             stackName = instanceId.substring(0, offset);
329             stackId = instanceId.substring(offset + 1);
330         } else {
331             stackName = instanceId;
332             stackId = instanceId;
333         }
334
335         StackInfo returnInfo = new StackInfo();
336         returnInfo.setName(stackName);
337         Response response = null;
338
339         String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
340         RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
341
342         if (multicloudClient != null) {
343             response = multicloudClient.delete();
344             if (logger.isDebugEnabled()) {
345                 logger.debug(String.format("Multicloud Delete response is: %s", response.getEntity().toString()));
346             }
347
348             if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
349                 returnInfo.setStatus(HeatStatus.NOTFOUND);
350                 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
351             } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
352                 return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId);
353             } else {
354                 returnInfo.setStatus(HeatStatus.FAILED);
355                 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
356             }
357
358         }
359         returnInfo.setStatus(mapResponseToHeatStatus(response));
360         return returnInfo;
361     }
362
363     // ---------------------------------------------------------------
364     // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
365
366     private HeatStatus getHeatStatus(String workloadStatus) {
367         if (workloadStatus.length() == 0) return HeatStatus.INIT;
368         if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
369         if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
370         if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
371         if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
372         if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
373         if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
374         if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
375         if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
376         if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
377         return HeatStatus.UNKNOWN;
378     }
379
380     private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
381         return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId, false, 0, false);
382     }
383
384     private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
385         StackInfo stackInfo = new StackInfo();
386
387         // If client has requested a final response, poll for stack completion
388         if (pollForCompletion) {
389             // Set a time limit on overall polling.
390             // Use the resource (template) timeout for Openstack (expressed in minutes)
391             // and add one poll interval to give Openstack a chance to fail on its own.s
392
393             int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
394             int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
395             // New 1610 - poll on delete if we rollback - use same values for now
396             int deletePollInterval = createPollInterval;
397             int deletePollTimeout = pollTimeout;
398             boolean createTimedOut = false;
399             StringBuilder stackErrorStatusReason = new StringBuilder("");
400             logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
401
402             while (true) {
403                 try {
404                     stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
405                     logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
406
407                     if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
408                         // Stack creation is still running.
409                         // Sleep and try again unless timeout has been reached
410                         if (pollTimeout <= 0) {
411                             // Note that this should not occur, since there is a timeout specified
412                             // in the Openstack (multicloud?) call.
413                             logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(), "Create stack timeout"));
414                             createTimedOut = true;
415                             break;
416                         }
417
418                         sleep(createPollInterval * 1000L);
419
420                         pollTimeout -= createPollInterval;
421                         logger.debug("pollTimeout remaining: " + pollTimeout);
422                     } else {
423                         //save off the status & reason msg before we attempt delete
424                         stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
425                         break;
426                     }
427                 } catch (MsoException me) {
428                     // Cannot query the stack status. Something is wrong.
429                     // Try to roll back the stack
430                     if (!backout) {
431                         logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack, stack deletion suppressed"));
432                     } else {
433                         try {
434                             logger.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + instanceId + " - This will likely fail and/or we won't be able to query to see if delete worked");
435                             StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
436                             // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
437                             // get another one, n'est-ce pas?
438                             boolean deleted = false;
439                             while (!deleted) {
440                                 try {
441                                     StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
442                                     logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
443                                     if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
444                                         if (deletePollTimeout <= 0) {
445                                             logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
446                                                     queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
447                                                     "Rollback: DELETE stack timeout"));
448                                             break;
449                                         } else {
450                                             sleep(deletePollInterval * 1000L);
451                                             deletePollTimeout -= deletePollInterval;
452                                         }
453                                     } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
454                                         logger.debug("DELETE_COMPLETE for " + instanceId);
455                                         deleted = true;
456                                         continue;
457                                     } else {
458                                         //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
459                                         break;
460                                     }
461                                 } catch (Exception e3) {
462                                     // Just log this one. We will report the original exception.
463                                     logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e3, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack on error on query"));
464                                 }
465                             }
466                         } catch (Exception e2) {
467                             // Just log this one. We will report the original exception.
468                             logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack"));
469                         }
470                     }
471
472                     // Propagate the original exception from Stack Query.
473                     me.addContext (CREATE_STACK);
474                     throw me;
475                 }
476             }
477
478             if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
479                 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error:  Polling complete with non-success status: "
480                               + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
481
482                 // Rollback the stack creation, since it is in an indeterminate state.
483                 if (!backout) {
484                     logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion suppressed"));
485                 }
486                 else
487                 {
488                     try {
489                         logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
490                         logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
491                         StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
492                         boolean deleted = false;
493                         while (!deleted) {
494                             try {
495                                 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
496                                 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
497                                 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
498                                     if (deletePollTimeout <= 0) {
499                                         logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
500                                                 queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
501                                                 "Rollback: DELETE stack timeout"));
502                                         break;
503                                     } else {
504                                         sleep(deletePollInterval * 1000L);
505                                         deletePollTimeout -= deletePollInterval;
506                                     }
507                                 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
508                                     logger.debug("DELETE_COMPLETE for " + instanceId);
509                                     deleted = true;
510                                     continue;
511                                 } else {
512                                     //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
513                                     logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion FAILED", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion FAILED"));
514                                     logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
515                                     break;
516                                 }
517                             } catch (MsoException me2) {
518                                 // Just log this one. We will report the original exception.
519                                 logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
520                                 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
521                             }
522                         }
523                         StringBuilder errorContextMessage;
524                         if (createTimedOut) {
525                             errorContextMessage = new StringBuilder("Stack Creation Timeout");
526                         } else {
527                             errorContextMessage  = stackErrorStatusReason;
528                         }
529                         if (deleted) {
530                             errorContextMessage.append(" - stack successfully deleted");
531                         } else {
532                             errorContextMessage.append(" - encountered an error trying to delete the stack");
533                         }
534                     } catch (MsoException e2) {
535                         // shouldn't happen - but handle
536                         logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack: rolling back stack"));
537                     }
538                 }
539                 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
540                 me.addContext(CREATE_STACK);
541                 throw me;
542             }
543         } else {
544             // Get initial status, since it will have been null after the create.
545             stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
546             logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
547         }
548         return stackInfo;
549     }
550
551     private HeatStatus mapResponseToHeatStatus(Response response) {
552         if (response == null) {
553             return HeatStatus.FAILED;
554         } else if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
555             return HeatStatus.CREATED;
556         } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
557             return HeatStatus.CREATED;
558         } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
559             return HeatStatus.CREATED;
560         } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
561             return HeatStatus.FAILED;
562         } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
563             return HeatStatus.FAILED;
564         } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
565             return HeatStatus.NOTFOUND;
566         } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
567             return HeatStatus.FAILED;
568         } else {
569             return HeatStatus.UNKNOWN;
570         }
571     }
572
573     private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
574         Scanner scanner = new Scanner(in);
575         scanner.useDelimiter("\\Z");
576         String body = "";
577         if (scanner.hasNext()) {
578             body = scanner.next();
579         }
580         scanner.close();
581
582         try {
583             return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
584         } catch (Exception e) {
585             logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
586         }
587         return null;
588     }
589
590     private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
591         Scanner scanner = new Scanner(in);
592         scanner.useDelimiter("\\Z");
593         String body = "";
594         if (scanner.hasNext()) {
595             body = scanner.next();
596         }
597         scanner.close();
598
599         try {
600             return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
601         } catch (Exception e) {
602             logger.debug("Exception retrieving multicloud workload query response body " + e);
603         }
604         return null;
605     }
606
607     private String getMulticloudEndpoint(String cloudSiteId, String cloudOwner, String workloadId) throws MsoCloudSiteNotFound {
608         String msbIp = System.getenv().get(ONAP_IP);
609         if (null == msbIp || msbIp.isEmpty()) {
610             msbIp = environment.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
611         }
612         Integer msbPort = environment.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
613
614         String path = "/api/multicloud/v1/" + cloudOwner + "/" + cloudSiteId + "/infra_workload";
615
616         String endpoint = UriBuilder.fromPath(path).host(msbIp).port(msbPort).scheme("http").build().toString();
617         if (workloadId != null) {
618             if (logger.isDebugEnabled()) {
619                 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
620             }
621             return String.format("%s/%s", endpoint, workloadId);
622         } else {
623             if (logger.isDebugEnabled()) {
624                 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
625             }
626             return endpoint;
627         }
628     }
629
630     private RestClient getMulticloudClient(String endpoint) {
631         RestClient client = null;
632         try {
633             client = httpClientFactory.newJsonClient(
634                 new URL(endpoint),
635                 TargetEntity.MULTICLOUD);
636         } catch (MalformedURLException e) {
637             logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
638         } catch (IllegalArgumentException e) {
639             logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
640         } catch (UriBuilderException e) {
641             logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
642         }
643         return client;
644     }
645
646     private JsonNode getDirectiveNode(String directives) throws MsoException {
647         try {
648             return JSON_MAPPER.readTree(directives);
649         } catch (Exception e) {
650             logger.error(String.format("%s %s %s %s %d %s",
651                     MessageEnum.RA_CREATE_STACK_ERR.toString(),
652                     "Create Stack: " + e, "", "",
653                     ErrorCode.BusinessProcesssError.getValue(),
654                     "Exception in Create Stack: Invalid JSON format of directives" + directives));
655             MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
656             me.addContext(CREATE_STACK);
657             throw me;
658         }
659     }
660
661     /**
662      * VduPlugin interface for instantiate function.
663      *
664      * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
665      * and then invoke the existing function.
666      */
667     @Override
668     public VduInstance instantiateVdu (
669             CloudInfo cloudInfo,
670             String instanceName,
671             Map<String,Object> inputs,
672             VduModelInfo vduModel,
673             boolean rollbackOnFailure)
674         throws VduException
675     {
676         String cloudSiteId = cloudInfo.getCloudSiteId();
677         String cloudOwner = cloudInfo.getCloudOwner();
678         String tenantId = cloudInfo.getTenantId();
679
680         // Translate the VDU ModelInformation structure to that which is needed for
681         // creating the Heat stack.  Loop through the artifacts, looking specifically
682         // for MAIN_TEMPLATE and ENVIRONMENT.  Any other artifact will
683         // be attached as a FILE.
684         String heatTemplate = null;
685         Map<String,Object> nestedTemplates = new HashMap<>();
686         Map<String,Object> files = new HashMap<>();
687         String heatEnvironment = null;
688
689         for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
690             if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
691                 heatTemplate = new String(vduArtifact.getContent());
692             }
693             else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
694                 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
695             }
696             else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
697                 heatEnvironment = new String(vduArtifact.getContent());
698             }
699         }
700
701         try {
702             StackInfo stackInfo = createStack (cloudSiteId,
703                     cloudOwner,
704                     tenantId,
705                     instanceName,
706                     vduModel,
707                     heatTemplate,
708                     inputs,
709                     true,    // poll for completion
710                     vduModel.getTimeoutMinutes(),
711                     heatEnvironment,
712                     nestedTemplates,
713                     files,
714                     rollbackOnFailure);
715             // Populate a vduInstance from the StackInfo
716             return stackInfoToVduInstance(stackInfo);
717         }
718         catch (Exception e) {
719             throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
720         }
721     }
722
723
724     /**
725      * VduPlugin interface for query function.
726      */
727     @Override
728     public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
729         throws VduException
730     {
731         String cloudSiteId = cloudInfo.getCloudSiteId();
732         String cloudOwner = cloudInfo.getCloudOwner();
733         String tenantId = cloudInfo.getTenantId();
734
735         try {
736             // Query the Cloudify Deployment object and  populate a VduInstance
737             StackInfo stackInfo = queryStack (cloudSiteId, cloudOwner, tenantId, instanceId);
738
739             return stackInfoToVduInstance(stackInfo);
740         }
741         catch (Exception e) {
742             throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
743         }
744     }
745
746
747     /**
748      * VduPlugin interface for delete function.
749      */
750     @Override
751     public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
752         throws VduException
753     {
754         String cloudSiteId = cloudInfo.getCloudSiteId();
755         String cloudOwner = cloudInfo.getCloudOwner();
756         String tenantId = cloudInfo.getTenantId();
757
758         try {
759             // Delete the Multicloud stack
760             StackInfo stackInfo = deleteStack (cloudSiteId, cloudOwner, tenantId, instanceId);
761
762             // Populate a VduInstance based on the deleted Cloudify Deployment object
763             VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
764
765             // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
766             vduInstance.getStatus().setState(VduStateType.DELETED);
767
768             return vduInstance;
769         }
770         catch (Exception e) {
771             throw new VduException ("Delete VDU Exception", e);
772         }
773     }
774
775
776     /**
777      * VduPlugin interface for update function.
778      *
779      * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
780      * Just return a VduException.
781      *
782      */
783     @Override
784     public VduInstance updateVdu (
785             CloudInfo cloudInfo,
786             String instanceId,
787             Map<String,Object> inputs,
788             VduModelInfo vduModel,
789             boolean rollbackOnFailure)
790         throws VduException
791     {
792         throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
793     }
794
795
796     /*
797      * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
798      */
799     protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
800     {
801         VduInstance vduInstance = new VduInstance();
802
803         if (logger.isDebugEnabled()) {
804             logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
805         }
806         // The full canonical name as the instance UUID
807         vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
808         vduInstance.setVduInstanceName(stackInfo.getName());
809
810         // Copy inputs and outputs
811         vduInstance.setInputs(stackInfo.getParameters());
812         vduInstance.setOutputs(stackInfo.getOutputs());
813
814         // Translate the status elements
815         vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
816
817         return vduInstance;
818     }
819
820     private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
821     {
822         VduStatus vduStatus = new VduStatus();
823
824         // Map the status fields to more generic VduStatus.
825         // There are lots of HeatStatus values, so this is a bit long...
826         HeatStatus heatStatus = stackInfo.getStatus();
827         String statusMessage = stackInfo.getStatusMessage();
828         logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
829
830         if (logger.isDebugEnabled()) {
831             logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
832             logger.debug(String.format("Stack Status Message: %s", statusMessage));
833         }
834
835         if (heatStatus == HeatStatus.INIT  ||  heatStatus == HeatStatus.BUILDING) {
836             vduStatus.setState(VduStateType.INSTANTIATING);
837             vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
838         }
839         else if (heatStatus == HeatStatus.NOTFOUND) {
840             vduStatus.setState(VduStateType.NOTFOUND);
841         }
842         else if (heatStatus == HeatStatus.CREATED) {
843             vduStatus.setState(VduStateType.INSTANTIATED);
844             vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
845         }
846         else if (heatStatus == HeatStatus.UPDATED) {
847             vduStatus.setState(VduStateType.INSTANTIATED);
848             vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
849         }
850         else if (heatStatus == HeatStatus.UPDATING) {
851             vduStatus.setState(VduStateType.UPDATING);
852             vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
853         }
854         else if (heatStatus == HeatStatus.DELETING) {
855             vduStatus.setState(VduStateType.DELETING);
856             vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
857         }
858         else if (heatStatus == HeatStatus.FAILED) {
859             vduStatus.setState(VduStateType.FAILED);
860             vduStatus.setErrorMessage(stackInfo.getStatusMessage());
861         } else {
862             vduStatus.setState(VduStateType.UNKNOWN);
863         }
864
865         return vduStatus;
866     }
867 }