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