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