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