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