Springboot 2.0 upgrade
[so.git] / adapters / mso-adapter-utils / src / main / java / org / onap / so / openstack / utils / MsoHeatUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.so.openstack.utils;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32
33 import org.onap.so.adapters.vdu.CloudInfo;
34 import org.onap.so.adapters.vdu.PluginAction;
35 import org.onap.so.adapters.vdu.VduArtifact;
36 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
37 import org.onap.so.adapters.vdu.VduException;
38 import org.onap.so.adapters.vdu.VduInstance;
39 import org.onap.so.adapters.vdu.VduModelInfo;
40 import org.onap.so.adapters.vdu.VduPlugin;
41 import org.onap.so.adapters.vdu.VduStateType;
42 import org.onap.so.adapters.vdu.VduStatus;
43 import org.onap.so.cloud.CloudConfig;
44 import org.onap.so.db.catalog.beans.CloudIdentity;
45 import org.onap.so.db.catalog.beans.CloudSite;
46 import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
47 import org.onap.so.db.catalog.beans.HeatTemplate;
48 import org.onap.so.db.catalog.beans.HeatTemplateParam;
49 import org.onap.so.logger.MessageEnum;
50 import org.onap.so.logger.MsoAlarmLogger;
51 import org.onap.so.logger.MsoLogger;
52 import org.onap.so.openstack.beans.HeatCacheEntry;
53 import org.onap.so.openstack.beans.HeatStatus;
54 import org.onap.so.openstack.beans.StackInfo;
55 import org.onap.so.openstack.exceptions.MsoAdapterException;
56 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
57 import org.onap.so.openstack.exceptions.MsoException;
58 import org.onap.so.openstack.exceptions.MsoIOException;
59 import org.onap.so.openstack.exceptions.MsoOpenstackException;
60 import org.onap.so.openstack.exceptions.MsoStackAlreadyExists;
61 import org.onap.so.openstack.exceptions.MsoTenantNotFound;
62 import org.onap.so.openstack.mappers.StackInfoMapper;
63 import org.onap.so.utils.CryptoUtils;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.context.annotation.Primary;
66 import org.springframework.core.env.Environment;
67 import org.springframework.stereotype.Component;
68
69 import com.fasterxml.jackson.core.type.TypeReference;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72 import com.woorea.openstack.base.client.OpenStackConnectException;
73 import com.woorea.openstack.base.client.OpenStackRequest;
74 import com.woorea.openstack.base.client.OpenStackResponseException;
75 import com.woorea.openstack.heat.Heat;
76 import com.woorea.openstack.heat.model.CreateStackParam;
77 import com.woorea.openstack.heat.model.Stack;
78 import com.woorea.openstack.heat.model.Stack.Output;
79 import com.woorea.openstack.heat.model.Stacks;
80 import com.woorea.openstack.keystone.Keystone;
81 import com.woorea.openstack.keystone.model.Access;
82 import com.woorea.openstack.keystone.model.Authentication;
83 import com.woorea.openstack.keystone.utils.KeystoneUtils;
84
85 @Primary
86 @Component
87 public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
88
89     private static final String TOKEN_AUTH = "TokenAuth";
90
91     private static final String QUERY_ALL_STACKS = "QueryAllStacks";
92
93     private static final String DELETE_STACK = "DeleteStack";
94
95     protected static final String HEAT_ERROR = "HeatError";
96
97     protected static final String CREATE_STACK = "CreateStack";
98
99     // Cache Heat Clients statically. Since there is just one MSO user, there is no
100     // benefit to re-authentication on every request (or across different flows). The
101     // token will be used until it expires.
102     //
103     // The cache key is "tenantId:cloudId"
104     private static Map <String, HeatCacheEntry> heatClientCache = new HashMap <> ();
105
106     // Fetch cloud configuration each time (may be cached in CloudConfig class)
107     @Autowired
108     protected CloudConfig cloudConfig;
109
110     @Autowired
111     private Environment environment;
112
113     @Autowired
114     private AuthenticationMethodFactory authenticationMethodFactory;
115
116     @Autowired
117     private MsoTenantUtilsFactory tenantUtilsFactory;
118
119     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtils.class);
120
121     // Properties names and variables (with default values)
122     protected String createPollIntervalProp = "onap.so.adapters.po.pollInterval";
123     private String deletePollIntervalProp = "onap.so.adapters.po.pollInterval";
124     private String deletePollTimeoutProp = "onap.so.adapters.po.pollTimeout";
125
126     protected static final String createPollIntervalDefault = "15";
127     private static final String deletePollIntervalDefault = "15";
128
129     private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
130
131     /**
132      * keep this old method signature here to maintain backwards compatibility. keep others as well.
133      * this method does not include environment, files, or heatFiles
134      */
135     public StackInfo createStack (String cloudSiteId,
136                                   String tenantId,
137                                   String stackName,
138                                   String heatTemplate,
139                                   Map <String, ?> stackInputs,
140                                   boolean pollForCompletion,
141                                   int timeoutMinutes) throws MsoException {
142         // Just call the new method with the environment & files variable set to null
143         return this.createStack (cloudSiteId,
144                                  tenantId,
145                                  stackName,
146                                  heatTemplate,
147                                  stackInputs,
148                                  pollForCompletion,
149                                  timeoutMinutes,
150                                  null,
151                                  null,
152                                  null,
153                                  true);
154     }
155
156     // This method has environment, but not files or heatFiles
157     public StackInfo createStack (String cloudSiteId,
158                                   String tenantId,
159                                   String stackName,
160                                   String heatTemplate,
161                                   Map <String, ?> stackInputs,
162                                   boolean pollForCompletion,
163                                   int timeoutMinutes,
164                                   String environment) throws MsoException {
165         // Just call the new method with the files/heatFiles variables set to null
166         return this.createStack (cloudSiteId,
167                                  tenantId,
168                                  stackName,
169                                  heatTemplate,
170                                  stackInputs,
171                                  pollForCompletion,
172                                  timeoutMinutes,
173                                  environment,
174                                  null,
175                                  null,
176                                  true);
177     }
178
179     // This method has environment and files, but not heatFiles.
180     public StackInfo createStack (String cloudSiteId,
181                                   String tenantId,
182                                   String stackName,
183                                   String heatTemplate,
184                                   Map <String, ?> stackInputs,
185                                   boolean pollForCompletion,
186                                   int timeoutMinutes,
187                                   String environment,
188                                   Map <String, Object> files) throws MsoException {
189         return this.createStack (cloudSiteId,
190                                  tenantId,
191                                  stackName,
192                                  heatTemplate,
193                                  stackInputs,
194                                  pollForCompletion,
195                                  timeoutMinutes,
196                                  environment,
197                                  files,
198                                  null,
199                                  true);
200     }
201
202     // This method has environment, files, heatfiles
203     public StackInfo createStack (String cloudSiteId,
204                                   String tenantId,
205                                   String stackName,
206                                   String heatTemplate,
207                                   Map <String, ?> stackInputs,
208                                   boolean pollForCompletion,
209                                   int timeoutMinutes,
210                                   String environment,
211                                   Map <String, Object> files,
212                                   Map <String, Object> heatFiles) throws MsoException {
213         return this.createStack (cloudSiteId,
214                                  tenantId,
215                                  stackName,
216                                  heatTemplate,
217                                  stackInputs,
218                                  pollForCompletion,
219                                  timeoutMinutes,
220                                  environment,
221                                  files,
222                                  heatFiles,
223                                  true);
224     }
225
226     /**
227      * Create a new Stack in the specified cloud location and tenant. The Heat template
228      * and parameter map are passed in as arguments, along with the cloud access credentials.
229      * It is expected that parameters have been validated and contain at minimum the required
230      * parameters for the given template with no extra (undefined) parameters..
231      *
232      * The Stack name supplied by the caller must be unique in the scope of this tenant.
233      * However, it should also be globally unique, as it will be the identifier for the
234      * resource going forward in Inventory. This latter is managed by the higher levels
235      * invoking this function.
236      *
237      * The caller may choose to let this function poll Openstack for completion of the
238      * stack creation, or may handle polling itself via separate calls to query the status.
239      * In either case, a StackInfo object will be returned containing the current status.
240      * When polling is enabled, a status of CREATED is expected. When not polling, a
241      * status of BUILDING is expected.
242      *
243      * An error will be thrown if the requested Stack already exists in the specified
244      * Tenant and Cloud.
245      *
246      * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
247      * parameters for createStack. If environment is non-null, it will be added to the stack.
248      * The nested templates and get_file entries both end up being added to the "files" on the
249      * stack. We must combine them before we add them to the stack if they're both non-null.
250      *
251      * @param cloudSiteId The cloud (may be a region) in which to create the stack.
252      * @param tenantId The Openstack ID of the tenant in which to create the Stack
253      * @param stackName The name of the stack to create
254      * @param heatTemplate The Heat template
255      * @param stackInputs A map of key/value inputs
256      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
257      * @param environment An optional yaml-format string to specify environmental parameters
258      * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
259      *        Template id)
260      * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
261      * @param backout Donot delete stack on create Failure - defaulted to True
262      * @return A StackInfo object
263      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
264      */
265
266     @SuppressWarnings("unchecked")
267     public StackInfo createStack (String cloudSiteId,
268                                   String tenantId,
269                                   String stackName,
270                                   String heatTemplate,
271                                   Map <String, ?> stackInputs,
272                                   boolean pollForCompletion,
273                                   int timeoutMinutes,
274                                   String environment,
275                                   Map <String, Object> files,
276                                   Map <String, Object> heatFiles,
277                                   boolean backout) throws MsoException {
278
279         // Take out the multicloud inputs, if present.
280         for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
281             if (stackInputs.containsKey(key)) {
282                 stackInputs.remove(key);
283                 if (stackInputs.isEmpty()) {
284                     break;
285                 }
286             }
287         }
288
289         CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
290
291         // Obtain the cloud site information where we will create the stack
292         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
293                 () -> new MsoCloudSiteNotFound(cloudSiteId));
294         LOGGER.debug("Found: " + cloudSite.toString());
295         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
296         // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
297         Heat heatClient = getHeatClient (cloudSite, tenantId);
298         if (heatClient != null) {
299             LOGGER.debug("Found: " + heatClient.toString());
300         }
301
302         LOGGER.debug ("Ready to Create Stack (" + heatTemplate + ") with input params: " + stackInputs);
303
304         Stack heatStack = null;
305         try {
306             // Execute the actual Openstack command to create the Heat stack
307             OpenStackRequest <Stack> request = heatClient.getStacks ().create (stack);
308             // Begin X-Auth-User
309             // Obtain an MSO token for the tenant
310             CloudIdentity cloudIdentity = cloudSite.getIdentityService();
311             // cloudIdentity.getMsoId(), cloudIdentity.getMsoPass()
312             //req
313             request.header ("X-Auth-User", cloudIdentity.getMsoId ());
314             request.header ("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
315             LOGGER.debug ("headers added, about to executeAndRecordOpenstackRequest");
316             //LOGGER.debug(this.requestToStringBuilder(stack).toString());
317             // END - try to fix X-Auth-User
318             heatStack = executeAndRecordOpenstackRequest (request);
319         } catch (OpenStackResponseException e) {
320             // Since this came on the 'Create Stack' command, nothing was changed
321             // in the cloud. Return the error as an exception.
322             if (e.getStatus () == 409) {
323                 // Stack already exists. Return a specific error for this case
324                 MsoStackAlreadyExists me = new MsoStackAlreadyExists (stackName, tenantId, cloudSiteId);
325                 me.addContext (CREATE_STACK);
326                 throw me;
327             } else {
328                 // Convert the OpenStackResponseException to an MsoOpenstackException
329                 LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage());
330                 throw heatExceptionToMsoException (e, CREATE_STACK);
331             }
332         } catch (OpenStackConnectException e) {
333             // Error connecting to Openstack instance. Convert to an MsoException
334             throw heatExceptionToMsoException (e, CREATE_STACK);
335         } catch (RuntimeException e) {
336             // Catch-all
337             throw runtimeExceptionToMsoException (e, CREATE_STACK);
338         }
339
340         // Subsequent access by the canonical name "<stack name>/<stack-id>".
341         // Otherwise, simple query by name returns a 302 redirect.
342         // NOTE: This is specific to the v1 Orchestration API.
343         String canonicalName = stackName + "/" + heatStack.getId ();
344
345         // If client has requested a final response, poll for stack completion
346         if (pollForCompletion) {
347             // Set a time limit on overall polling.
348             // Use the resource (template) timeout for Openstack (expressed in minutes)
349             // and add one poll interval to give Openstack a chance to fail on its own.s
350
351             int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
352             int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
353             // New 1610 - poll on delete if we rollback - use same values for now
354             int deletePollInterval = createPollInterval;
355             int deletePollTimeout = pollTimeout;
356             boolean createTimedOut = false;
357             StringBuilder stackErrorStatusReason = new StringBuilder("");
358             LOGGER.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
359
360             while (true) {
361                 try {
362                     heatStack = queryHeatStack (heatClient, canonicalName);
363                     LOGGER.debug (heatStack.getStackStatus () + " (" + canonicalName + ")");
364                     try {
365                         LOGGER.debug("Current stack " + this.getOutputsAsStringBuilder(heatStack).toString());
366                     } catch (Exception e) {
367                         LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e);
368                     }
369
370                     if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) {
371                         // Stack creation is still running.
372                         // Sleep and try again unless timeout has been reached
373                         if (pollTimeout <= 0) {
374                             // Note that this should not occur, since there is a timeout specified
375                             // in the Openstack call.
376                             LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Create stack timeout");
377                             createTimedOut = true;
378                             break;
379                         }
380
381                         sleep(createPollInterval * 1000L);
382
383                         pollTimeout -= createPollInterval;
384                                 LOGGER.debug("pollTimeout remaining: " + pollTimeout);
385                     } else {
386                         //save off the status & reason msg before we attempt delete
387                         stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
388                         break;
389                     }
390                 } catch (MsoException me) {
391                         // Cannot query the stack status. Something is wrong.
392                         // Try to roll back the stack
393                         if (!backout)
394                         {
395                                 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack, stack deletion suppressed");
396                         }
397                         else
398                         {
399                                 try {
400                                         LOGGER.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + canonicalName + " - This will likely fail and/or we won't be able to query to see if delete worked");
401                                         OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
402                                         executeAndRecordOpenstackRequest (request);
403                                         // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
404                                         // get another one, n'est-ce pas?
405                                         boolean deleted = false;
406                                         while (!deleted) {
407                                                 try {
408                                                         heatStack = queryHeatStack(heatClient, canonicalName);
409                                                         if (heatStack != null) {
410                                                         LOGGER.debug(heatStack.getStackStatus());
411                                                         if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
412                                                                 if (deletePollTimeout <= 0) {
413                                                                         LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
414                                                                                         heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError,
415                                                                                         "Rollback: DELETE stack timeout");
416                                                                         break;
417                                                                 } else {
418                                                                         sleep(deletePollInterval * 1000L);
419                                                                         deletePollTimeout -= deletePollInterval;
420                                                                 }
421                                                         } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
422                                                                 LOGGER.debug("DELETE_COMPLETE for " + canonicalName);
423                                                                 deleted = true;
424                                                                 continue;
425                                                         } else {
426                                                                 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
427                                                                 break;
428                                                         }
429                                                 } else {
430                                                         // assume if we can't find it - it's deleted
431                                                         LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted");
432                                                         deleted = true;
433                                                         continue;
434                                                         }
435
436                                                 } catch (Exception e3) {
437                                                         // Just log this one. We will report the original exception.
438                                                         LOGGER.error (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");
439
440                                                 }
441                                         }
442                                 } catch (Exception e2) {
443                                         // Just log this one. We will report the original exception.
444                                         LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack");
445                                 }
446                         }
447
448                     // Propagate the original exception from Stack Query.
449                     me.addContext (CREATE_STACK);
450                     throw me;
451                 }
452             }
453
454             if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) {
455                 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error:  Polling complete with non-success status: "
456                               + heatStack.getStackStatus () + ", " + heatStack.getStackStatusReason (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error");
457
458                 // Rollback the stack creation, since it is in an indeterminate state.
459                 if (!backout)
460                 {
461                         LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion suppressed");
462                 }
463                 else
464                 {
465                         try {
466                                 LOGGER.debug("Create Stack errored - attempting to DELETE stack: " + canonicalName);
467                                 LOGGER.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
468                                 OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
469                                 executeAndRecordOpenstackRequest (request);
470                                 boolean deleted = false;
471                                 while (!deleted) {
472                                         try {
473                                                 heatStack = queryHeatStack(heatClient, canonicalName);
474                                                 if (heatStack != null) {
475                                                         LOGGER.debug(heatStack.getStackStatus() + " (" + canonicalName + ")");
476                                                         if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
477                                                                 if (deletePollTimeout <= 0) {
478                                                                         LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
479                                                                                         heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError,
480                                                                                         "Rollback: DELETE stack timeout");
481                                                                         break;
482                                                                 } else {
483                                                                         sleep(deletePollInterval * 1000L);
484                                                                         deletePollTimeout -= deletePollInterval;
485                                                                         LOGGER.debug("deletePollTimeout remaining: " + deletePollTimeout);
486                                                                 }
487                                                         } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
488                                                                 LOGGER.debug("DELETE_COMPLETE for " + canonicalName);
489                                                                 deleted = true;
490                                                                 continue;
491                                                         } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
492                                                                 // Warn about this (?) - but still throw the original exception
493                                                                 LOGGER.warn(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 - " + canonicalName + ", status=" + heatStack.getStackStatus() + ", reason=" + heatStack.getStackStatusReason());
495                                                                 break;
496                                                         } else {
497                                                                 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
498                                                                 break;
499                                                         }
500                                                 } else {
501                                                         // assume if we can't find it - it's deleted
502                                                         LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted");
503                                                         deleted = true;
504                                                         continue;
505                                                 }
506
507                                         } catch (MsoException me2) {
508                                                 // We got an exception on the delete - don't throw this exception - throw the original - just log.
509                                                 LOGGER.debug("Exception thrown trying to delete " + canonicalName + " on a create->rollback: " + me2.getContextMessage(), me2);
510                                                 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", MsoLogger.ErrorCode.BusinessProcesssError, me2.getContextMessage());
511                                         }
512
513                                 } // end while !deleted
514                                 StringBuilder errorContextMessage;
515                                 if (createTimedOut) {
516                                         errorContextMessage = new StringBuilder("Stack Creation Timeout");
517                                 } else {
518                                         errorContextMessage  = stackErrorStatusReason;
519                                 }
520                                 if (deleted) {
521                                         errorContextMessage.append(" - stack successfully deleted");
522                                 } else {
523                                         errorContextMessage.append(" - encountered an error trying to delete the stack");
524                                 }
525 //                              MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
526  //                             me.addContext(CREATE_STACK);
527   //                            alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
528    //                           throw me;
529                         } catch (Exception e2) {
530                                 // shouldn't happen - but handle
531                                 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack: rolling back stack");
532                         }
533                 }
534                 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
535                 me.addContext(CREATE_STACK);
536                 alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
537                 throw me;
538             }
539
540         } else {
541             // Get initial status, since it will have been null after the create.
542             heatStack = queryHeatStack (heatClient, canonicalName);
543             LOGGER.debug (heatStack.getStackStatus ());
544         }
545
546         return new StackInfoMapper(heatStack).map();
547     }
548
549     /**
550      * Query for a single stack (by Name) in a tenant. This call will always return a
551      * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
552      * returned - containing only the stack name and a status of NOTFOUND.
553      *
554      * @param tenantId The Openstack ID of the tenant in which to query
555      * @param cloudSiteId The cloud identifier (may be a region) in which to query
556      * @param stackName The name of the stack to query (may be simple or canonical)
557      * @return A StackInfo object
558      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
559      */
560     public StackInfo queryStack (String cloudSiteId, String tenantId, String stackName) throws MsoException {
561         LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId);
562
563         // Obtain the cloud site information where we will create the stack
564         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
565                 () -> new MsoCloudSiteNotFound(cloudSiteId));
566         LOGGER.debug("Found: " + cloudSite.toString());
567
568         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
569         Heat heatClient = null;
570         try {
571             heatClient = getHeatClient (cloudSite, tenantId);
572             if (heatClient != null) {
573                 LOGGER.debug("Found: " + heatClient.toString());
574             }
575         } catch (MsoTenantNotFound e) {
576             // Tenant doesn't exist, so stack doesn't either
577             LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
578             return new StackInfo (stackName, HeatStatus.NOTFOUND);
579         } catch (MsoException me) {
580             // Got an Openstack error. Propagate it
581             LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
582             me.addContext ("QueryStack");
583             throw me;
584         }
585
586         // Query the Stack.
587         // An MsoException will propagate transparently to the caller.
588         Stack heatStack = queryHeatStack (heatClient, stackName);
589
590         if (heatStack == null) {
591             // Stack does not exist. Return a StackInfo with status NOTFOUND
592             return new StackInfo (stackName, HeatStatus.NOTFOUND);
593         }
594
595         return new StackInfoMapper(heatStack).map();
596     }
597
598     /**
599      * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be
600      * considered a successful deletion. The return value is a StackInfo object which
601      * contains the current stack status.
602      *
603      * The client may choose to let the adapter poll Openstack for completion of the
604      * stack deletion, or may handle polling itself via separate query calls. In either
605      * case, a StackInfo object will be returned. When polling is enabled, a final
606      * status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
607      *
608      * There is no rollback from a successful stack deletion. A deletion failure will
609      * also result in an undefined stack state - the components may or may not have been
610      * all or partially deleted, so the resulting stack must be considered invalid.
611      *
612      * @param tenantId The Openstack ID of the tenant in which to perform the delete
613      * @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
614      * @param stackName The name/id of the stack to delete. May be simple or canonical
615      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
616      * @return A StackInfo object
617      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
618      * @throws MsoCloudSiteNotFound
619      */
620     public StackInfo deleteStack (String tenantId,
621                                   String cloudSiteId,
622                                   String stackName,
623                                   boolean pollForCompletion) throws MsoException {
624         // Obtain the cloud site information where we will create the stack
625         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
626                 () -> new MsoCloudSiteNotFound(cloudSiteId));
627         LOGGER.debug("Found: " + cloudSite.toString());
628
629         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
630         Heat heatClient = null;
631         try {
632             heatClient = getHeatClient (cloudSite, tenantId);
633             if (heatClient != null) {
634                 LOGGER.debug("Found: " + heatClient.toString());
635             }
636         } catch (MsoTenantNotFound e) {
637             // Tenant doesn't exist, so stack doesn't either
638             LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
639             return new StackInfo (stackName, HeatStatus.NOTFOUND);
640         } catch (MsoException me) {
641             // Got an Openstack error. Propagate it
642             LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
643             me.addContext (DELETE_STACK);
644             throw me;
645         }
646
647         // OK if stack not found, perform a query first
648         Stack heatStack = queryHeatStack (heatClient, stackName);
649         if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
650             // Not found. Return a StackInfo with status NOTFOUND
651             return new StackInfo (stackName, HeatStatus.NOTFOUND);
652         }
653
654         // Delete the stack.
655
656         // Use canonical name "<stack name>/<stack-id>" to delete.
657         // Otherwise, deletion by name returns a 302 redirect.
658         // NOTE: This is specific to the v1 Orchestration API.
659         String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
660
661         try {
662             OpenStackRequest <Void> request = null;
663             if(null != heatClient) {
664                 request = heatClient.getStacks ().deleteByName (canonicalName);
665             }
666             else {
667                 LOGGER.debug ("Heat Client is NULL" );
668             }
669
670             executeAndRecordOpenstackRequest (request);
671         } catch (OpenStackResponseException e) {
672             if (e.getStatus () == 404) {
673                 // Not found. We are OK with this. Return a StackInfo with status NOTFOUND
674                 return new StackInfo (stackName, HeatStatus.NOTFOUND);
675             } else {
676                 // Convert the OpenStackResponseException to an MsoOpenstackException
677                 throw heatExceptionToMsoException (e, DELETE_STACK);
678             }
679         } catch (OpenStackConnectException e) {
680             // Error connecting to Openstack instance. Convert to an MsoException
681             throw heatExceptionToMsoException (e, DELETE_STACK);
682         } catch (RuntimeException e) {
683             // Catch-all
684             throw runtimeExceptionToMsoException (e, DELETE_STACK);
685         }
686
687         // Requery the stack for current status.
688         // It will probably still exist with "DELETE_IN_PROGRESS" status.
689         heatStack = queryHeatStack (heatClient, canonicalName);
690
691         if (pollForCompletion) {
692             // Set a timeout on polling
693
694             int pollInterval = Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
695             int pollTimeout = Integer.parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
696
697             // When querying by canonical name, Openstack returns DELETE_COMPLETE status
698             // instead of "404" (which would result from query by stack name).
699             while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
700                 LOGGER.debug ("Stack status: " + heatStack.getStackStatus ());
701
702                 if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) {
703                     // Throw a 'special case' of MsoOpenstackException to report the Heat status
704                     String error = "Stack delete error (" + heatStack.getStackStatus ()
705                                    + "): "
706                                    + heatStack.getStackStatusReason ();
707                     MsoOpenstackException me = new MsoOpenstackException (0, "", error);
708                     me.addContext (DELETE_STACK);
709
710                     // Alarm this condition, stack deletion failed
711                     alarmLogger.sendAlarm (HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage ());
712
713                     throw me;
714                 }
715
716                 if (pollTimeout <= 0) {
717                     LOGGER.error (MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Delete Stack Timeout");
718
719                     // Throw a 'special case' of MsoOpenstackException to report the Heat status
720                     MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout");
721                     me.addContext (DELETE_STACK);
722
723                     // Alarm this condition, stack deletion failed
724                     alarmLogger.sendAlarm (HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage ());
725
726                     throw me;
727                 }
728
729                 sleep(pollInterval * 1000L);
730
731                 pollTimeout -= pollInterval;
732                 LOGGER.debug("pollTimeout remaining: " + pollTimeout);
733
734                 heatStack = queryHeatStack (heatClient, canonicalName);
735             }
736
737             // The stack is gone when this point is reached
738             return new StackInfo (stackName, HeatStatus.NOTFOUND);
739         }
740
741         // Return the current status (if not polling, the delete may still be in progress)
742         StackInfo stackInfo = new StackInfoMapper(heatStack).map();
743         stackInfo.setName (stackName);
744
745         return stackInfo;
746     }
747
748     /**
749      * Query for all stacks in a tenant site. This call will return a List of StackInfo
750      * objects, one for each deployed stack.
751      *
752      * Note that this is limited to a single site. To ensure that a tenant is truly
753      * empty would require looping across all tenant endpoints.
754      *
755      * @param tenantId The Openstack ID of the tenant to query
756      * @param cloudSiteId The cloud identifier (may be a region) in which to query.
757      * @return A List of StackInfo objects
758      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
759      * @throws MsoCloudSiteNotFound
760      */
761     public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
762         // Obtain the cloud site information where we will create the stack
763         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
764                 () -> new MsoCloudSiteNotFound(cloudSiteId));
765         // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
766         Heat heatClient = getHeatClient (cloudSite, tenantId);
767
768         try {
769             OpenStackRequest <Stacks> request = heatClient.getStacks ().list ();
770             Stacks stacks = executeAndRecordOpenstackRequest (request);
771
772             List <StackInfo> stackList = new ArrayList <> ();
773
774             // Not sure if returns an empty list or null if no stacks exist
775             if (stacks != null) {
776                 for (Stack stack : stacks) {
777                     stackList.add (new StackInfoMapper(stack).map());
778                 }
779             }
780
781             return stackList;
782         } catch (OpenStackResponseException e) {
783             if (e.getStatus () == 404) {
784                 // Not sure if this can happen, but return an empty list
785                 LOGGER.debug ("queryAllStacks - stack not found: ");
786                 return new ArrayList <> ();
787             } else {
788                 // Convert the OpenStackResponseException to an MsoOpenstackException
789                 throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
790             }
791         } catch (OpenStackConnectException e) {
792             // Error connecting to Openstack instance. Convert to an MsoException
793             throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
794         } catch (RuntimeException e) {
795             // Catch-all
796             throw runtimeExceptionToMsoException (e, QUERY_ALL_STACKS);
797         }
798     }
799
800     /**
801      * Validate parameters to be passed to Heat template. This method performs
802      * three functions:
803      * 1. Apply default values to parameters which have them defined
804      * 2. Report any required parameters that are missing. This will generate an
805      * exception in the caller, since stack create/update operations would fail.
806      * 3. Report and remove any extraneous parameters. This will allow clients to
807      * pass supersets of parameters and not get errors.
808      *
809      * These functions depend on the HeatTemplate definition from the MSO Catalog DB,
810      * along with the input parameter Map. The output is an updated parameter map.
811      * If the parameters are invalid for the template, an IllegalArgumentException
812      * is thrown.
813      */
814     public Map <String, Object> validateStackParams (Map <String, Object> inputParams,
815                                                      HeatTemplate heatTemplate) {
816         // Check that required parameters have been supplied for this template type
817         StringBuilder missingParams = null;
818         List <String> paramList = new ArrayList <> ();
819
820         // TODO: Enhance DB to support defaults for Heat Template parameters
821
822         for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
823             if (parm.isRequired () && !inputParams.containsKey (parm.getParamName ())) {
824                 if (missingParams == null) {
825                     missingParams = new StringBuilder(parm.getParamName());
826                 } else {
827                     missingParams.append("," + parm.getParamName());
828                 }
829             }
830             paramList.add (parm.getParamName ());
831         }
832         if (missingParams != null) {
833             // Problem - missing one or more required parameters
834             String error = "Missing Required inputs for HEAT Template: " + missingParams;
835             LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams + " for HEAT Template", "", "", MsoLogger.ErrorCode.SchemaError, "Missing Required inputs for HEAT Template: " + missingParams);
836             throw new IllegalArgumentException (error);
837         }
838
839         // Remove any extraneous parameters (don't throw an error)
840         Map <String, Object> updatedParams = new HashMap <> ();
841         List <String> extraParams = new ArrayList <> ();
842
843         for (Entry<String, Object> entry : inputParams.entrySet()) {
844                 if (!paramList.contains(entry.getKey())) {
845                         // This is not a valid parameter for this template
846                         extraParams.add(entry.getKey());
847                 } else {
848                         updatedParams.put(entry.getKey(), entry.getValue());
849                 }
850         }
851
852         if (!extraParams.isEmpty ()) {
853             LOGGER.warn (MessageEnum.RA_GENERAL_WARNING, "Heat Stack (" + heatTemplate.getTemplateName ()
854                          + ") extra input params received: "
855                          + extraParams, "", "", MsoLogger.ErrorCode.DataError, "Heat Stack (" + heatTemplate.getTemplateName () + ") extra input params received: "+ extraParams);
856         }
857
858         return updatedParams;
859     }
860
861     // ---------------------------------------------------------------
862     // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
863
864     /**
865      * Get a Heat client for the Openstack Identity service.
866      * This requires a 'member'-level userId + password, which will be retrieved from
867      * properties based on the specified cloud Id. The tenant in which to operate
868      * must also be provided.
869      * <p>
870      * On successful authentication, the Heat object will be cached for the
871      * tenantID + cloudId so that it can be reused without reauthenticating with
872      * Openstack every time.
873      *
874      * @return an authenticated Heat object
875      */
876     public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
877         String cloudId = cloudSite.getId();
878
879         // Check first in the cache of previously authorized clients
880         String cacheKey = cloudId + ":" + tenantId;
881         if (heatClientCache.containsKey (cacheKey)) {
882             if (!heatClientCache.get (cacheKey).isExpired ()) {
883                 LOGGER.debug ("Using Cached HEAT Client for " + cacheKey);
884                 return heatClientCache.get (cacheKey).getHeatClient ();
885             } else {
886                 // Token is expired. Remove it from cache.
887                 heatClientCache.remove (cacheKey);
888                 LOGGER.debug ("Expired Cached HEAT Client for " + cacheKey);
889             }
890         }
891
892         // Obtain an MSO token for the tenant
893         CloudIdentity cloudIdentity = cloudSite.getIdentityService();
894         LOGGER.debug("Found: " + cloudIdentity.toString());
895         MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
896         String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
897         LOGGER.debug("keystoneUrl=" + keystoneUrl);
898         Keystone keystoneTenantClient = new Keystone (keystoneUrl);
899         Access access = null;
900         try {
901                 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
902
903                 OpenStackRequest <Access> request = keystoneTenantClient.tokens ()
904                        .authenticate (credentials).withTenantId (tenantId);
905
906             access = executeAndRecordOpenstackRequest (request);
907         } catch (OpenStackResponseException e) {
908             if (e.getStatus () == 401) {
909                 // Authentication error.
910                 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId ();
911                 alarmLogger.sendAlarm ("MsoAuthenticationError", MsoAlarmLogger.CRITICAL, error);
912                 throw new MsoAdapterException (error);
913             } else {
914                 throw keystoneErrorToMsoException (e, TOKEN_AUTH);
915             }
916         } catch (OpenStackConnectException e) {
917             // Connection to Openstack failed
918             MsoIOException me = new MsoIOException (e.getMessage (), e);
919             me.addContext (TOKEN_AUTH);
920             throw me;
921         } catch (RuntimeException e) {
922             // Catch-all
923             throw runtimeExceptionToMsoException (e, TOKEN_AUTH);
924         }
925
926         // For DCP/LCP, the region should be the cloudId.
927         String region = cloudSite.getRegionId ();
928         String heatUrl = null;
929         try {
930                 // Isolate trying to printout the region IDs
931                 try {
932                         LOGGER.debug("access=" + access.toString());
933                         for (Access.Service service : access.getServiceCatalog()) {
934                                 List<Access.Service.Endpoint> endpoints = service.getEndpoints();
935                                 for (Access.Service.Endpoint endpoint : endpoints) {
936                                         LOGGER.debug("AIC returned region=" + endpoint.getRegion());
937                                 }
938                         }
939                 } catch (Exception e) {
940                         LOGGER.debug("Encountered an error trying to printout Access object returned from AIC. " + e.getMessage());
941                 }
942             heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public");
943             LOGGER.debug("heatUrl=" + heatUrl + ", region=" + region);
944         } catch (RuntimeException e) {
945             // This comes back for not found (probably an incorrect region ID)
946             String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
947             alarmLogger.sendAlarm ("MsoConfigurationError", MsoAlarmLogger.CRITICAL, error);
948             throw new MsoAdapterException (error, e);
949         }
950
951         Heat heatClient = new Heat (heatUrl);
952         heatClient.token (access.getToken ().getId ());
953
954         heatClientCache.put (cacheKey,
955                              new HeatCacheEntry (heatUrl,
956                                                  access.getToken ().getId (),
957                                                  access.getToken ().getExpires ()));
958         LOGGER.debug ("Caching HEAT Client for " + cacheKey);
959
960         return heatClient;
961     }
962
963     /**
964      * Forcibly expire a HEAT client from the cache. This call is for use by
965      * the KeystoneClient in case where a tenant is deleted. In that case,
966      * all cached credentials must be purged so that fresh authentication is
967      * done if a similarly named tenant is re-created.
968      * <p>
969      * Note: This is probably only applicable to dev/test environments where
970      * the same Tenant Name is repeatedly used for creation/deletion.
971      * <p>
972      *
973      */
974     public void expireHeatClient (String tenantId, String cloudId) {
975         String cacheKey = cloudId + ":" + tenantId;
976         if (heatClientCache.containsKey (cacheKey)) {
977             heatClientCache.remove (cacheKey);
978             LOGGER.debug ("Deleted Cached HEAT Client for " + cacheKey);
979         }
980     }
981
982     /*
983      * Query for a Heat Stack. This function is needed in several places, so
984      * a common method is useful. This method takes an authenticated Heat Client
985      * (which internally identifies the cloud & tenant to search), and returns
986      * a Stack object if found, Null if not found, or an MsoOpenstackException
987      * if the Openstack API call fails.
988      *
989      * The stack name may be a simple name or a canonical name ("{name}/{id}").
990      * When simple name is used, Openstack always returns a 302 redirect which
991      * results in a 2nd request (to the canonical name). Note that query by
992      * canonical name for a deleted stack returns a Stack object with status
993      * "DELETE_COMPLETE" while query by simple name for a deleted stack returns
994      * HTTP 404.
995      *
996      * @param heatClient an authenticated Heat client
997      *
998      * @param stackName the stack name to query
999      *
1000      * @return a Stack object that describes the current stack or null if the
1001      * requested stack doesn't exist.
1002      *
1003      * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
1004      */
1005     protected Stack queryHeatStack (Heat heatClient, String stackName) throws MsoException {
1006         if (stackName == null) {
1007             return null;
1008         }
1009         try {
1010             OpenStackRequest <Stack> request = heatClient.getStacks ().byName (stackName);
1011             return executeAndRecordOpenstackRequest (request);
1012         } catch (OpenStackResponseException e) {
1013             if (e.getStatus () == 404) {
1014                 LOGGER.debug ("queryHeatStack - stack not found: " + stackName);
1015                 return null;
1016             } else {
1017                 // Convert the OpenStackResponseException to an MsoOpenstackException
1018                 throw heatExceptionToMsoException (e, "QueryStack");
1019             }
1020         } catch (OpenStackConnectException e) {
1021             // Connection to Openstack failed
1022             throw heatExceptionToMsoException (e, "QueryAllStack");
1023         }
1024     }
1025
1026
1027         public Map<String, Object> queryStackForOutputs(String cloudSiteId,
1028                         String tenantId, String stackName) throws MsoException {
1029                 LOGGER.debug("MsoHeatUtils.queryStackForOutputs)");
1030                 StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
1031                 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
1032                         return null;
1033                 }
1034                 return heatStack.getOutputs();
1035         }
1036
1037         public void copyStringOutputsToInputs(Map<String, String> inputs,
1038                         Map<String, Object> otherStackOutputs, boolean overWrite) {
1039                 if (inputs == null || otherStackOutputs == null)
1040                         return;
1041                 for (String key : otherStackOutputs.keySet()) {
1042                         if (!inputs.containsKey(key)) {
1043                                 Object obj = otherStackOutputs.get(key);
1044                                 if (obj instanceof String) {
1045                                         inputs.put(key, (String) otherStackOutputs.get(key));
1046                                 } else if (obj instanceof JsonNode ){
1047                                         // This is a bit of mess - but I think it's the least impacting
1048                                         // let's convert it BACK to a string - then it will get converted back later
1049                                         try {
1050                                                 String str = this.convertNode((JsonNode) obj);
1051                                                 inputs.put(key, str);
1052                                         } catch (Exception e) {
1053                                                 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e);
1054                                                 //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
1055                                         }
1056                                 } else if (obj instanceof java.util.LinkedHashMap) {
1057                                         LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
1058                                         try {
1059                                                 String str = JSON_MAPPER.writeValueAsString(obj);
1060                                                 inputs.put(key, str);
1061                                         } catch (Exception e) {
1062                                                 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e);
1063                                         }
1064                                 } else if (obj instanceof Integer) {
1065                                         try {
1066                                                 String str = "" + obj;
1067                                                 inputs.put(key, str);
1068                                         } catch (Exception e) {
1069                                                 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key, e);
1070                                         }
1071                                 } else {
1072                                         try {
1073                                                 String str = obj.toString();
1074                                                 inputs.put(key, str);
1075                                         } catch (Exception e) {
1076                                                 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Other "+ key +" (" + e.getMessage() + ")", e);
1077                                                 //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
1078                                         }
1079                                 }
1080                         }
1081                 }
1082                 return;
1083         }
1084         public StringBuilder requestToStringBuilder(CreateStackParam stack) {
1085                 StringBuilder sb = new StringBuilder();
1086                 sb.append("Stack:\n");
1087                 sb.append("\tStackName: " + stack.getStackName());
1088                 sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
1089                 sb.append("\tTemplate: " + stack.getTemplate());
1090                 sb.append("\tEnvironment: " + stack.getEnvironment());
1091                 sb.append("\tTimeout: " + stack.getTimeoutMinutes());
1092                 sb.append("\tParameters:\n");
1093                 Map<String, Object> params = stack.getParameters();
1094                 if (params == null || params.size() < 1) {
1095                         sb.append("\nNONE");
1096                 } else {
1097                         for (String key : params.keySet()) {
1098                                 if (params.get(key) instanceof String) {
1099                                         sb.append("\n").append(key).append("=").append((String) params.get(key));
1100                                 } else if (params.get(key) instanceof JsonNode) {
1101                                         String jsonStringOut = this.convertNode((JsonNode)params.get(key));
1102                                         sb.append("\n").append(key).append("=").append(jsonStringOut);
1103                                 } else if (params.get(key) instanceof Integer) {
1104                                         String integerOut = "" + params.get(key);
1105                                         sb.append("\n").append(key).append("=").append(integerOut);
1106
1107                                 } else {
1108                                         try {
1109                                                 String str = params.get(key).toString();
1110                                                 sb.append("\n").append(key).append("=").append(str);
1111                                         } catch (Exception e) {
1112                                                 LOGGER.debug("Exception :",e);
1113                                         }
1114                                 }
1115                         }
1116                 }
1117                 return sb;
1118         }
1119
1120         private String convertNode(final JsonNode node) {
1121                 try {
1122                         final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
1123                         final String json = JSON_MAPPER.writeValueAsString(obj);
1124                         return json;
1125                 } catch (Exception e) {
1126                         LOGGER.debug("Error converting json to string " + e.getMessage(), e);
1127                 }
1128                 return "[Error converting json to string]";
1129         }
1130
1131
1132         protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
1133                 // This should only be used as a utility to print out the stack outputs
1134                 // to the log
1135                 StringBuilder sb = new StringBuilder("");
1136                 if (heatStack == null) {
1137                         sb.append("(heatStack is null)");
1138                         return sb;
1139                 }
1140                 List<Output> outputList = heatStack.getOutputs();
1141                 if (outputList == null || outputList.isEmpty()) {
1142                         sb.append("(outputs is empty)");
1143                         return sb;
1144                 }
1145                 Map<String, Object> outputs = new HashMap<>();
1146                 for (Output outputItem : outputList) {
1147                         outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
1148                 }
1149                 int counter = 0;
1150                 sb.append("OUTPUTS:\n");
1151                 for (String key : outputs.keySet()) {
1152                         sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
1153                         Object obj = outputs.get(key);
1154                         if (obj instanceof String) {
1155                                 sb.append((String) obj).append(" (a string)");
1156                         } else if (obj instanceof JsonNode) {
1157                                 sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
1158                         } else if (obj instanceof java.util.LinkedHashMap) {
1159                                 try {
1160                                         String str = JSON_MAPPER.writeValueAsString(obj);
1161                                         sb.append(str).append(" (a java.util.LinkedHashMap)");
1162                                 } catch (Exception e) {
1163                                         LOGGER.debug("Exception :",e);
1164                                         sb.append("(a LinkedHashMap value that would not convert nicely)");
1165                                 }
1166                         } else if (obj instanceof Integer) {
1167                                 String str = "";
1168                                 try {
1169                                         str = obj.toString() + " (an Integer)\n";
1170                                 } catch (Exception e) {
1171                                         LOGGER.debug("Exception :",e);
1172                                         str = "(an Integer unable to call .toString() on)";
1173                                 }
1174                                 sb.append(str);
1175                         } else if (obj instanceof ArrayList) {
1176                                 String str = "";
1177                                 try {
1178                                         str = obj.toString() + " (an ArrayList)";
1179                                 } catch (Exception e) {
1180                                         LOGGER.debug("Exception :",e);
1181                                         str = "(an ArrayList unable to call .toString() on?)";
1182                                 }
1183                                 sb.append(str);
1184                         } else if (obj instanceof Boolean) {
1185                                 String str = "";
1186                                 try {
1187                                         str = obj.toString() + " (a Boolean)";
1188                                 } catch (Exception e) {
1189                                         LOGGER.debug("Exception :",e);
1190                                         str = "(an Boolean unable to call .toString() on?)";
1191                                 }
1192                                 sb.append(str);
1193                         }
1194                         else {
1195                                 String str = "";
1196                                 try {
1197                                         str = obj.toString() + " (unknown Object type)";
1198                                 } catch (Exception e) {
1199                                         LOGGER.debug("Exception :",e);
1200                                         str = "(a value unable to call .toString() on?)";
1201                                 }
1202                                 sb.append(str);
1203                         }
1204                         sb.append("\n");
1205                 }
1206                 sb.append("[END]");
1207                 return sb;
1208         }
1209
1210
1211         public void copyBaseOutputsToInputs(Map<String, Object> inputs,
1212                         Map<String, Object> otherStackOutputs, List<String> paramNames, Map<String, String> aliases) {
1213                 if (inputs == null || otherStackOutputs == null)
1214                         return;
1215                 for (String key : otherStackOutputs.keySet()) {
1216                         if (paramNames != null) {
1217                                 if (!paramNames.contains(key) && !aliases.containsKey(key)) {
1218                                         LOGGER.debug("\tParameter " + key + " is NOT defined to be in the template - do not copy to inputs");
1219                                         continue;
1220                                 }
1221                                 if (aliases.containsKey(key)) {
1222                                         LOGGER.debug("Found an alias! Will move " + key + " to " + aliases.get(key));
1223                                         Object obj = otherStackOutputs.get(key);
1224                                         key = aliases.get(key);
1225                                         otherStackOutputs.put(key, obj);
1226                                 }
1227                         }
1228                         if (!inputs.containsKey(key)) {
1229                                 Object obj = otherStackOutputs.get(key);
1230                                 LOGGER.debug("\t**Adding " + key + " to inputs (.toString()=" + obj.toString());
1231                                 if (obj instanceof String) {
1232                                         LOGGER.debug("\t\t**A String");
1233                                         inputs.put(key, obj);
1234                                 } else if (obj instanceof Integer) {
1235                                         LOGGER.debug("\t\t**An Integer");
1236                                         inputs.put(key, obj);
1237                                 } else if (obj instanceof JsonNode) {
1238                                         LOGGER.debug("\t\t**A JsonNode");
1239                                         inputs.put(key, obj);
1240                                 } else if (obj instanceof Boolean) {
1241                                         LOGGER.debug("\t\t**A Boolean");
1242                                         inputs.put(key, obj);
1243                                 } else if (obj instanceof java.util.LinkedHashMap) {
1244                                         LOGGER.debug("\t\t**A java.util.LinkedHashMap **");
1245                                         inputs.put(key, obj);
1246                                 } else if (obj instanceof java.util.ArrayList) {
1247                                         LOGGER.debug("\t\t**An ArrayList");
1248                                         inputs.put(key, obj);
1249                                 } else {
1250                                         LOGGER.debug("\t\t**UNKNOWN OBJECT TYPE");
1251                                         inputs.put(key, obj);
1252                                 }
1253                         } else {
1254                                 LOGGER.debug("key=" + key + " is already in the inputs - will not overwrite");
1255                         }
1256                 }
1257                 return;
1258         }
1259
1260         public List<String> convertCdlToArrayList(String cdl) {
1261                 String cdl2 = cdl.trim();
1262                 String cdl3;
1263                 if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
1264                         cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
1265                 } else {
1266                         cdl3 = cdl2;
1267                 }
1268                 return new ArrayList<>(Arrays.asList(cdl3.split(",")));
1269         }
1270
1271     /**
1272      * New with 1707 - this method will convert all the String *values* of the inputs
1273      * to their "actual" object type (based on the param type: in the db - which comes from the template):
1274      * (heat variable type) -> java Object type
1275      * string -> String
1276      * number -> Integer
1277      * json -> JsonNode XXX Removed with MSO-1475 / 1802
1278      * comma_delimited_list -> ArrayList
1279      * boolean -> Boolean
1280      * if any of the conversions should fail, we will default to adding it to the inputs
1281      * as a string - see if Openstack can handle it.
1282      * Also, will remove any params that are extra.
1283      * Any aliases will be converted to their appropriate name (anyone use this feature?)
1284      * @param inputs - the Map<String, String> of the inputs received on the request
1285      * @param template the HeatTemplate object - this is so we can also verify if the param is valid for this template
1286      * @return HashMap<String, Object> of the inputs, cleaned and converted
1287      */
1288         public Map<String, Object> convertInputMap(Map<String, String> inputs, HeatTemplate template) {
1289                 HashMap<String, Object> newInputs = new HashMap<>();
1290                 HashMap<String, HeatTemplateParam> params = new HashMap<>();
1291                 HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
1292
1293                 if (inputs == null) {
1294                         LOGGER.debug("convertInputMap - inputs is null - nothing to do here");
1295                         return new HashMap<>();
1296                 }
1297
1298                 LOGGER.debug("convertInputMap in MsoHeatUtils called, with " + inputs.size() + " inputs, and template " + template.getArtifactUuid());
1299                 try {
1300                         LOGGER.debug(template.toString());
1301                         Set<HeatTemplateParam> paramSet = template.getParameters();
1302                         LOGGER.debug("paramSet has " + paramSet.size() + " entries");
1303                 } catch (Exception e) {
1304                         LOGGER.debug("Exception occurred in convertInputMap:" + e.getMessage(), e);
1305                 }
1306
1307                 for (HeatTemplateParam htp : template.getParameters()) {
1308                         LOGGER.debug("Adding " + htp.getParamName());
1309                         params.put(htp.getParamName(), htp);
1310                         if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
1311                                 LOGGER.debug("\tFound ALIAS " + htp.getParamName() + "->" + htp.getParamAlias());
1312                                 paramAliases.put(htp.getParamAlias(), htp);
1313                         }
1314                 }
1315                 LOGGER.debug("Now iterate through the inputs...");
1316                 for (String key : inputs.keySet()) {
1317                         LOGGER.debug("key=" + key);
1318                         boolean alias = false;
1319                         String realName = null;
1320                         if (!params.containsKey(key)) {
1321                                 LOGGER.debug(key + " is not a parameter in the template! - check for an alias");
1322                                 // add check here for an alias
1323                                 if (!paramAliases.containsKey(key)) {
1324                                         LOGGER.debug("The parameter " + key + " is in the inputs, but it's not a parameter for this template - omit");
1325                                         continue;
1326                                 } else {
1327                                         alias = true;
1328                                         realName = paramAliases.get(key).getParamName();
1329                                         LOGGER.debug("FOUND AN ALIAS! Will use " + realName + " in lieu of give key/alias " + key);
1330                                 }
1331                         }
1332                         String type = params.get(key).getParamType();
1333                         if (type == null || "".equals(type)) {
1334                                 LOGGER.debug("**PARAM_TYPE is null/empty for " + key + ", will default to string");
1335                                 type = "string";
1336                         }
1337                         LOGGER.debug("Parameter: " + key + " is of type " + type);
1338                         if ("string".equalsIgnoreCase(type)) {
1339                                 // Easiest!
1340                                 String str = inputs.get(key);
1341                                 if (alias)
1342                                         newInputs.put(realName, str);
1343                                 else
1344                                         newInputs.put(key, str);
1345                         } else if ("number".equalsIgnoreCase(type)) {
1346                                 String integerString = inputs.get(key);
1347                                 Integer anInteger = null;
1348                                 try {
1349                                         anInteger = Integer.parseInt(integerString);
1350                                 } catch (Exception e) {
1351                                         LOGGER.debug("Unable to convert " + integerString + " to an integer!!", e);
1352                                         anInteger = null;
1353                                 }
1354                                 if (anInteger != null) {
1355                                         if (alias)
1356                                                 newInputs.put(realName, anInteger);
1357                                         else
1358                                                 newInputs.put(key, anInteger);
1359                                 }
1360                                 else {
1361                                         if (alias)
1362                                                 newInputs.put(realName, integerString);
1363                                         else
1364                                                 newInputs.put(key, integerString);
1365                                 }
1366                         } else if ("json".equalsIgnoreCase(type)) {
1367                                 // MSO-1475 - Leave this as a string now
1368                                 String jsonString = inputs.get(key);
1369                                 LOGGER.debug("Skipping conversion to jsonNode...");
1370                         if (alias)
1371                                 newInputs.put(realName, jsonString);
1372                         else
1373                                 newInputs.put(key, jsonString);
1374                         //}
1375                         } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
1376                                 String commaSeparated = inputs.get(key);
1377                                 try {
1378                                         List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
1379                                         if (alias)
1380                                                 newInputs.put(realName, anArrayList);
1381                                         else
1382                                                 newInputs.put(key, anArrayList);
1383                                 } catch (Exception e) {
1384                                         LOGGER.debug("Unable to convert " + commaSeparated + " to an ArrayList!!", e);
1385                                         if (alias)
1386                                                 newInputs.put(realName, commaSeparated);
1387                                         else
1388                                                 newInputs.put(key, commaSeparated);
1389                                 }
1390                         } else if ("boolean".equalsIgnoreCase(type)) {
1391                                 String booleanString = inputs.get(key);
1392                                 Boolean aBool = Boolean.valueOf(booleanString);
1393                                 if (alias)
1394                                         newInputs.put(realName, aBool);
1395                                 else
1396                                         newInputs.put(key, aBool);
1397                         } else {
1398                                 // it's null or something undefined - just add it back as a String
1399                                 String str = inputs.get(key);
1400                                 if (alias)
1401                                         newInputs.put(realName, str);
1402                                 else
1403                                         newInputs.put(key, str);
1404                         }
1405                 }
1406                 return newInputs;
1407         }
1408
1409         /*
1410          * This helpful method added for Valet
1411          */
1412         public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
1413                 String keystone_url = null;
1414                 try {
1415                         CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
1416                         CloudIdentity cloudIdentity = cloudSite.getIdentityService();
1417                         keystone_url = cloudIdentity.getIdentityUrl();
1418                 } catch (Exception e) {
1419                         throw new MsoCloudSiteNotFound(cloudSiteId);
1420                 }
1421                 if (keystone_url == null || keystone_url.isEmpty()) {
1422                         throw new MsoCloudSiteNotFound(cloudSiteId);
1423                 }
1424                 return keystone_url;
1425         }
1426
1427         /*
1428          * Create a string suitable for being dumped to a debug log that creates a
1429          * pseudo-JSON request dumping what's being sent to Openstack API in the create or update request
1430          */
1431
1432         private String printStackRequest(String tenantId,
1433                         Map<String, Object> heatFiles,
1434                         Map<String, Object> nestedTemplates,
1435                         String environment,
1436                         Map<String, Object> inputs,
1437                         String vfModuleName,
1438                         String template,
1439                         int timeoutMinutes,
1440                         boolean backout,
1441                         String cloudSiteId) {
1442                 StringBuilder sb = new StringBuilder();
1443                 sb.append("CREATE STACK REQUEST (formatted for readability)\n");
1444                 sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
1445                 sb.append("{\n");
1446                 sb.append("  \"stack_name\": \"" + vfModuleName + "\",\n");
1447                 sb.append("  \"disable_rollback\": " + backout + ",\n");
1448                 sb.append("  \"timeout_mins\": " + timeoutMinutes + ",\n");
1449                 sb.append("  \"template\": {\n");
1450                 sb.append(template);
1451                 sb.append("  },\n");
1452                 sb.append("  \"environment\": {\n");
1453                 if (environment == null)
1454                         sb.append("<none>");
1455                 else
1456                         sb.append(environment);
1457                 sb.append("  },\n");
1458                 sb.append("  \"files\": {\n");
1459                 int filesCounter = 0;
1460                 if (heatFiles != null) {
1461                         for (String key : heatFiles.keySet()) {
1462                                 filesCounter++;
1463                                 if (filesCounter > 1) {
1464                                         sb.append(",\n");
1465                                 }
1466                                 sb.append("    \"" + key + "\": {\n");
1467                                 sb.append(heatFiles.get(key).toString() + "\n    }");
1468                         }
1469                 }
1470                 if (nestedTemplates != null) {
1471                         for (String key : nestedTemplates.keySet()) {
1472                                 filesCounter++;
1473                                 if (filesCounter > 1) {
1474                                         sb.append(",\n");
1475                                 }
1476                                 sb.append("    \"" + key + "\": {\n");
1477                                 sb.append(nestedTemplates.get(key).toString() + "\n    }");
1478                         }
1479                 }
1480                 sb.append("\n  },\n");
1481                 sb.append("  \"parameters\": {\n");
1482                 int paramCounter = 0;
1483                 for (String name : inputs.keySet()) {
1484                         paramCounter++;
1485                         if (paramCounter > 1) {
1486                                 sb.append(",\n");
1487                         }
1488                         Object o = inputs.get(name);
1489                         if (o instanceof java.lang.String) {
1490                                 sb.append("    \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
1491                         } else if (o instanceof Integer) {
1492                                 sb.append("    \"" + name + "\": " + inputs.get(name).toString() );
1493                         } else if (o instanceof ArrayList) {
1494                                 sb.append("    \"" + name + "\": " + inputs.get(name).toString() );
1495                         } else if (o instanceof Boolean) {
1496                                 sb.append("    \"" + name + "\": " + inputs.get(name).toString() );
1497                         } else {
1498                                 sb.append("    \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"" );
1499                         }
1500                 }
1501                 sb.append("\n  }\n}\n");
1502
1503                 return sb.toString();
1504         }
1505
1506         /*******************************************************************************
1507      *
1508      * Methods (and associated utilities) to implement the VduPlugin interface
1509      *
1510      *******************************************************************************/
1511
1512     /**
1513      * VduPlugin interface for instantiate function.
1514      *
1515      * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
1516      * and then invoke the existing function.
1517      */
1518     @Override
1519         public VduInstance instantiateVdu (
1520                         CloudInfo cloudInfo,
1521                         String instanceName,
1522                         Map<String,Object> inputs,
1523                         VduModelInfo vduModel,
1524                         boolean rollbackOnFailure)
1525         throws VduException
1526     {
1527         String cloudSiteId = cloudInfo.getCloudSiteId();
1528         String tenantId = cloudInfo.getTenantId();
1529
1530         // Translate the VDU ModelInformation structure to that which is needed for
1531         // creating the Heat stack.  Loop through the artifacts, looking specifically
1532         // for MAIN_TEMPLATE and ENVIRONMENT.  Any other artifact will
1533         // be attached as a FILE.
1534         String heatTemplate = null;
1535         Map<String,Object> nestedTemplates = new HashMap<>();
1536         Map<String,Object> files = new HashMap<>();
1537         String heatEnvironment = null;
1538
1539         for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
1540                 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
1541                         heatTemplate = new String(vduArtifact.getContent());
1542                 }
1543                 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
1544                         nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
1545                 }
1546                 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
1547                         heatEnvironment = new String(vduArtifact.getContent());
1548                 }
1549         }
1550
1551         try {
1552             StackInfo stackInfo = createStack (cloudSiteId,
1553                     tenantId,
1554                     instanceName,
1555                     heatTemplate,
1556                     inputs,
1557                     true,       // poll for completion
1558                     vduModel.getTimeoutMinutes(),
1559                     heatEnvironment,
1560                     nestedTemplates,
1561                     files,
1562                     rollbackOnFailure);
1563
1564             // Populate a vduInstance from the StackInfo
1565                 return stackInfoToVduInstance(stackInfo);
1566         }
1567         catch (Exception e) {
1568                 throw new VduException ("MsoHeatUtils (instantiateVDU): createStack Exception", e);
1569         }
1570     }
1571
1572
1573     /**
1574      * VduPlugin interface for query function.
1575      */
1576     @Override
1577         public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
1578         throws VduException
1579     {
1580         String cloudSiteId = cloudInfo.getCloudSiteId();
1581         String tenantId = cloudInfo.getTenantId();
1582
1583         try {
1584                 // Query the Cloudify Deployment object and  populate a VduInstance
1585                 StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
1586
1587                 return stackInfoToVduInstance(stackInfo);
1588         }
1589         catch (Exception e) {
1590                 throw new VduException ("MsoHeatUtile (queryVdu): queryStack Exception ", e);
1591         }
1592     }
1593
1594
1595     /**
1596      * VduPlugin interface for delete function.
1597      */
1598     @Override
1599         public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
1600         throws VduException
1601     {
1602         String cloudSiteId = cloudInfo.getCloudSiteId();
1603         String tenantId = cloudInfo.getTenantId();
1604
1605         try {
1606                 // Delete the Heat stack
1607                 StackInfo stackInfo = deleteStack (tenantId, cloudSiteId, instanceId, true);
1608
1609                 // Populate a VduInstance based on the deleted Cloudify Deployment object
1610                 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
1611
1612                 // Override return state to DELETED (HeatUtils sets to NOTFOUND)
1613                 vduInstance.getStatus().setState(VduStateType.DELETED);
1614
1615                 return vduInstance;
1616         }
1617         catch (Exception e) {
1618                 throw new VduException ("Delete VDU Exception", e);
1619         }
1620     }
1621
1622
1623     /**
1624      * VduPlugin interface for update function.
1625      *
1626      * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin.
1627      * Just return a VduException.
1628      *
1629      */
1630     @Override
1631         public VduInstance updateVdu (
1632                         CloudInfo cloudInfo,
1633                         String instanceId,
1634                         Map<String,Object> inputs,
1635                         VduModelInfo vduModel,
1636                         boolean rollbackOnFailure)
1637         throws VduException
1638     {
1639         throw new VduException ("MsoHeatUtils: updateVdu interface not supported");
1640     }
1641
1642
1643     /*
1644      * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
1645      */
1646     protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
1647     {
1648         VduInstance vduInstance = new VduInstance();
1649
1650         // The full canonical name as the instance UUID
1651         vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
1652         vduInstance.setVduInstanceName(stackInfo.getName());
1653
1654         // Copy inputs and outputs
1655         vduInstance.setInputs(stackInfo.getParameters());
1656         vduInstance.setOutputs(stackInfo.getOutputs());
1657
1658         // Translate the status elements
1659         vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
1660
1661         return vduInstance;
1662     }
1663
1664     private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
1665     {
1666         VduStatus vduStatus = new VduStatus();
1667
1668         // Map the status fields to more generic VduStatus.
1669         // There are lots of HeatStatus values, so this is a bit long...
1670         HeatStatus heatStatus = stackInfo.getStatus();
1671         String statusMessage = stackInfo.getStatusMessage();
1672
1673         if (heatStatus == HeatStatus.INIT  ||  heatStatus == HeatStatus.BUILDING) {
1674                 vduStatus.setState(VduStateType.INSTANTIATING);
1675                 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
1676         }
1677         else if (heatStatus == HeatStatus.NOTFOUND) {
1678                 vduStatus.setState(VduStateType.NOTFOUND);
1679         }
1680         else if (heatStatus == HeatStatus.CREATED) {
1681                 vduStatus.setState(VduStateType.INSTANTIATED);
1682                 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
1683         }
1684         else if (heatStatus == HeatStatus.UPDATED) {
1685                 vduStatus.setState(VduStateType.INSTANTIATED);
1686                 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
1687         }
1688         else if (heatStatus == HeatStatus.UPDATING) {
1689                 vduStatus.setState(VduStateType.UPDATING);
1690                 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
1691         }
1692         else if (heatStatus == HeatStatus.DELETING) {
1693                 vduStatus.setState(VduStateType.DELETING);
1694                 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
1695         }
1696         else if (heatStatus == HeatStatus.FAILED) {
1697                 vduStatus.setState(VduStateType.FAILED);
1698                 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
1699         } else {
1700                 vduStatus.setState(VduStateType.UNKNOWN);
1701         }
1702
1703         return vduStatus;
1704     }
1705
1706     protected void sleep(long time) {
1707         try {
1708             Thread.sleep(time);
1709         } catch (InterruptedException e) {
1710             LOGGER.debug ("Thread interrupted while sleeping", e);
1711             Thread.currentThread().interrupt();
1712         }
1713     }
1714
1715 }