10/31: merge casablanca to master
[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.MsoAlarmLogger;
56 import org.onap.so.logger.MsoLogger;
57 import org.onap.so.utils.TargetEntity;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.core.env.Environment;
60 import org.springframework.http.HttpEntity;
61 import org.springframework.http.HttpHeaders;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Component;
64
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.fasterxml.jackson.databind.ObjectMapper;
68 import com.woorea.openstack.heat.model.CreateStackParam;
69
70 @Component
71 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
72
73     public static final String OOF_DIRECTIVES = "oof_directives";
74     public static final String SDNC_DIRECTIVES = "sdnc_directives";
75     public static final String GENERIC_VNF_ID = "generic_vnf_id";
76     public static final String VF_MODULE_ID = "vf_module_id";
77     public static final String TEMPLATE_TYPE = "template_type";
78     public static final List<String> MULTICLOUD_INPUTS =
79             Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
80
81     private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
82
83     private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
84
85     @Autowired
86     private Environment environment;
87
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 tenantId The Openstack ID of the tenant in which to create the Stack
122      * @param stackName The name of the stack to create
123      * @param heatTemplate The Heat template
124      * @param stackInputs A map of key/value inputs
125      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
126      * @param environment An optional yaml-format string to specify environmental parameters
127      * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
128      *        Template id)
129      * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
130      * @param backout Do not delete stack on create Failure - defaulted to True
131      * @return A StackInfo object
132      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
133      */
134
135     @SuppressWarnings("unchecked")
136     @Override
137     public StackInfo createStack (String cloudSiteId,
138                                   String tenantId,
139                                   String stackName,
140                                   String heatTemplate,
141                                   Map <String, ?> stackInputs,
142                                   boolean pollForCompletion,
143                                   int timeoutMinutes,
144                                   String environment,
145                                   Map <String, Object> files,
146                                   Map <String, Object> heatFiles,
147                                   boolean backout) throws MsoException {
148
149         logger.trace("Started MsoMulticloudUtils.createStack");
150
151         // Get the directives, if present.
152         String oofDirectives = "";
153         String sdncDirectives = "";
154         String genericVnfId = "";
155         String vfModuleId = "";
156         String templateType = "";
157
158         for (String key: MULTICLOUD_INPUTS) {
159             if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
160                 if (key == OOF_DIRECTIVES) {
161                     oofDirectives = (String) stackInputs.get(key);
162                 }
163                 if (key == SDNC_DIRECTIVES) {
164                     sdncDirectives = (String) stackInputs.get(key);
165                 }
166                 if (key == TEMPLATE_TYPE) {
167                     templateType = (String) stackInputs.get(key);
168                 }
169                 if (logger.isDebugEnabled()) {
170                     logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
171                 }
172                 stackInputs.remove(key);
173             }
174         }
175
176         if (!stackInputs.isEmpty() && stackInputs.containsKey("VF_MODULE_ID")){
177             vfModuleId = (String) stackInputs.get("VF_MODULE_ID");
178         }
179         if (!stackInputs.isEmpty() && stackInputs.containsKey("GENERIC_VNF_ID")){
180             genericVnfId = (String) stackInputs.get("GENERIC_VNF_ID");
181         }
182
183         // create the multicloud payload
184         CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
185
186         MulticloudRequest multicloudRequest= new MulticloudRequest();
187
188         try {
189             multicloudRequest.setGenericVnfId(genericVnfId);
190             multicloudRequest.setVfModuleId(vfModuleId);
191             multicloudRequest.setOofDirectives(JSON_MAPPER.readTree(oofDirectives));
192             multicloudRequest.setSdncDirectives(JSON_MAPPER.readTree(sdncDirectives));
193             multicloudRequest.setTemplateType(templateType);
194             if (logger.isDebugEnabled()) {
195                 logger.debug(String.format("Stack Template Data is: %s", stack.toString().substring(16)));
196             }
197             multicloudRequest.setTemplateData(stack);
198             if (logger.isDebugEnabled()) {
199                 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
200             }
201         } catch (Exception e) {
202             logger.debug("ERROR making multicloud JSON body ", e);
203         }
204         String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, null);
205         if (logger.isDebugEnabled()) {
206             logger.debug(String.format("Multicloud Endpoint is: %s", multicloudEndpoint));
207         }
208         RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
209
210         Response response = multicloudClient.post(multicloudRequest);
211
212         StackInfo createInfo = new StackInfo();
213         createInfo.setName(stackName);
214
215         MulticloudCreateResponse multicloudResponseBody = null;
216         if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
217             multicloudResponseBody = getCreateBody((java.io.InputStream)response.getEntity());
218             createInfo.setCanonicalName(stackName + "/" + multicloudResponseBody.getWorkloadId());
219             if (logger.isDebugEnabled()) {
220                 logger.debug("Multicloud Create Response Body: " + multicloudResponseBody);
221             }
222             return getStackStatus(cloudSiteId, tenantId, createInfo.getCanonicalName(), pollForCompletion, timeoutMinutes, backout);
223         } else {
224             createInfo.setStatus(HeatStatus.FAILED);
225             createInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
226             return createInfo;
227         }
228     }
229
230     @Override
231     public Map<String, Object> queryStackForOutputs(String cloudSiteId,
232                                                            String tenantId, String stackName) throws MsoException {
233         logger.debug("MsoHeatUtils.queryStackForOutputs)");
234         StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
235         if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
236             return null;
237         }
238         return heatStack.getOutputs();
239     }
240
241     /**
242      * Query for a single stack (by ID) in a tenant. This call will always return a
243      * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
244      * returned - containing only the stack name and a status of NOTFOUND.
245      *
246      * @param tenantId The Openstack ID of the tenant in which to query
247      * @param cloudSiteId The cloud identifier (may be a region) 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 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, 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 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, 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, 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 tenantId, String instanceId) throws MsoException {
362         return getStackStatus(cloudSiteId, tenantId, instanceId, false, 0, false);
363     }
364
365     private StackInfo getStackStatus(String cloudSiteId, 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, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError, "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("%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"));
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, 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, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
427                                                     queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
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("%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"));
445                                 }
446                             }
447                         } catch (Exception e2) {
448                             // Just log this one. We will report the original exception.
449                             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"));
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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error:  Polling complete with non-success status: "
461                               + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"));
462
463                 // Rollback the stack creation, since it is in an indeterminate state.
464                 if (!backout) {
465                     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"));
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, tenantId, instanceId);
473                         boolean deleted = false;
474                         while (!deleted) {
475                             try {
476                                 StackInfo queryInfo = queryStack(cloudSiteId, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
481                                                 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
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("%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"));
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("%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()));
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("%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"));
518                     }
519                 }
520                 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
521                 me.addContext(CREATE_STACK);
522                 alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
523                 throw me;
524             }
525         } else {
526             // Get initial status, since it will have been null after the create.
527             stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
528             logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
529         }
530         return stackInfo;
531     }
532
533     private HeatStatus mapResponseToHeatStatus(Response response) {
534         if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
535             return HeatStatus.CREATED;
536         } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
537             return HeatStatus.CREATED;
538         } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
539             return HeatStatus.CREATED;
540         } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
541             return HeatStatus.FAILED;
542         } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
543             return HeatStatus.FAILED;
544         } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
545             return HeatStatus.NOTFOUND;
546         } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
547             return HeatStatus.FAILED;
548         } else {
549             return HeatStatus.UNKNOWN;
550         }
551     }
552
553     private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
554         Scanner scanner = new Scanner(in);
555         scanner.useDelimiter("\\Z");
556         String body = "";
557         if (scanner.hasNext()) {
558             body = scanner.next();
559         }
560         scanner.close();
561
562         try {
563             return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
564         } catch (Exception e) {
565             logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
566         }
567         return null;
568     }
569
570     private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
571         Scanner scanner = new Scanner(in);
572         scanner.useDelimiter("\\Z");
573         String body = "";
574         if (scanner.hasNext()) {
575             body = scanner.next();
576         }
577         scanner.close();
578
579         try {
580             return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
581         } catch (Exception e) {
582             logger.debug("Exception retrieving multicloud workload query response body " + e);
583         }
584         return null;
585     }
586
587     private String getMulticloudEndpoint(String cloudSiteId, String workloadId) throws MsoCloudSiteNotFound {
588
589         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
590         String endpoint = cloudSite.getIdentityService().getIdentityUrl();
591
592         if (workloadId != null) {
593             if (logger.isDebugEnabled()) {
594                 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
595             }
596             return String.format("%s/%s", endpoint, workloadId);
597         } else {
598             if (logger.isDebugEnabled()) {
599                 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
600             }
601             return endpoint;
602         }
603     }
604
605     private RestClient getMulticloudClient(String endpoint) {
606         RestClient client = null;
607         try {
608             client = new HttpClient(UriBuilder.fromUri(endpoint).build().toURL(),
609                     MediaType.APPLICATION_JSON.toString(), 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     /**
621      * VduPlugin interface for instantiate function.
622      *
623      * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
624      * and then invoke the existing function.
625      */
626     @Override
627     public VduInstance instantiateVdu (
628             CloudInfo cloudInfo,
629             String instanceName,
630             Map<String,Object> inputs,
631             VduModelInfo vduModel,
632             boolean rollbackOnFailure)
633         throws VduException
634     {
635         String cloudSiteId = cloudInfo.getCloudSiteId();
636         String tenantId = cloudInfo.getTenantId();
637
638         // Translate the VDU ModelInformation structure to that which is needed for
639         // creating the Heat stack.  Loop through the artifacts, looking specifically
640         // for MAIN_TEMPLATE and ENVIRONMENT.  Any other artifact will
641         // be attached as a FILE.
642         String heatTemplate = null;
643         Map<String,Object> nestedTemplates = new HashMap<>();
644         Map<String,Object> files = new HashMap<>();
645         String heatEnvironment = null;
646
647         for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
648             if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
649                 heatTemplate = new String(vduArtifact.getContent());
650             }
651             else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
652                 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
653             }
654             else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
655                 heatEnvironment = new String(vduArtifact.getContent());
656             }
657         }
658
659         try {
660             StackInfo stackInfo = createStack (cloudSiteId,
661                     tenantId,
662                     instanceName,
663                     heatTemplate,
664                     inputs,
665                     true,    // poll for completion
666                     vduModel.getTimeoutMinutes(),
667                     heatEnvironment,
668                     nestedTemplates,
669                     files,
670                     rollbackOnFailure);
671             // Populate a vduInstance from the StackInfo
672             return stackInfoToVduInstance(stackInfo);
673         }
674         catch (Exception e) {
675             throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
676         }
677     }
678
679
680     /**
681      * VduPlugin interface for query function.
682      */
683     @Override
684     public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
685         throws VduException
686     {
687         String cloudSiteId = cloudInfo.getCloudSiteId();
688         String tenantId = cloudInfo.getTenantId();
689
690         try {
691             // Query the Cloudify Deployment object and  populate a VduInstance
692             StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
693
694             return stackInfoToVduInstance(stackInfo);
695         }
696         catch (Exception e) {
697             throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
698         }
699     }
700
701
702     /**
703      * VduPlugin interface for delete function.
704      */
705     @Override
706     public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
707         throws VduException
708     {
709         String cloudSiteId = cloudInfo.getCloudSiteId();
710         String tenantId = cloudInfo.getTenantId();
711
712         try {
713             // Delete the Multicloud stack
714             StackInfo stackInfo = deleteStack (cloudSiteId, tenantId, instanceId);
715
716             // Populate a VduInstance based on the deleted Cloudify Deployment object
717             VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
718
719             // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
720             vduInstance.getStatus().setState(VduStateType.DELETED);
721
722             return vduInstance;
723         }
724         catch (Exception e) {
725             throw new VduException ("Delete VDU Exception", e);
726         }
727     }
728
729
730     /**
731      * VduPlugin interface for update function.
732      *
733      * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
734      * Just return a VduException.
735      *
736      */
737     @Override
738     public VduInstance updateVdu (
739             CloudInfo cloudInfo,
740             String instanceId,
741             Map<String,Object> inputs,
742             VduModelInfo vduModel,
743             boolean rollbackOnFailure)
744         throws VduException
745     {
746         throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
747     }
748
749
750     /*
751      * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
752      */
753     protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
754     {
755         VduInstance vduInstance = new VduInstance();
756
757         if (logger.isDebugEnabled()) {
758             logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
759         }
760         // The full canonical name as the instance UUID
761         vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
762         vduInstance.setVduInstanceName(stackInfo.getName());
763
764         // Copy inputs and outputs
765         vduInstance.setInputs(stackInfo.getParameters());
766         vduInstance.setOutputs(stackInfo.getOutputs());
767
768         // Translate the status elements
769         vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
770
771         return vduInstance;
772     }
773
774     private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
775     {
776         VduStatus vduStatus = new VduStatus();
777
778         // Map the status fields to more generic VduStatus.
779         // There are lots of HeatStatus values, so this is a bit long...
780         HeatStatus heatStatus = stackInfo.getStatus();
781         String statusMessage = stackInfo.getStatusMessage();
782         logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
783
784         if (logger.isDebugEnabled()) {
785             logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
786             logger.debug(String.format("Stack Status Message: %s", statusMessage));
787         }
788
789         if (heatStatus == HeatStatus.INIT  ||  heatStatus == HeatStatus.BUILDING) {
790             vduStatus.setState(VduStateType.INSTANTIATING);
791             vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
792         }
793         else if (heatStatus == HeatStatus.NOTFOUND) {
794             vduStatus.setState(VduStateType.NOTFOUND);
795         }
796         else if (heatStatus == HeatStatus.CREATED) {
797             vduStatus.setState(VduStateType.INSTANTIATED);
798             vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
799         }
800         else if (heatStatus == HeatStatus.UPDATED) {
801             vduStatus.setState(VduStateType.INSTANTIATED);
802             vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
803         }
804         else if (heatStatus == HeatStatus.UPDATING) {
805             vduStatus.setState(VduStateType.UPDATING);
806             vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
807         }
808         else if (heatStatus == HeatStatus.DELETING) {
809             vduStatus.setState(VduStateType.DELETING);
810             vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
811         }
812         else if (heatStatus == HeatStatus.FAILED) {
813             vduStatus.setState(VduStateType.FAILED);
814             vduStatus.setErrorMessage(stackInfo.getStatusMessage());
815         } else {
816             vduStatus.setState(VduStateType.UNKNOWN);
817         }
818
819         return vduStatus;
820     }
821 }