2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.so.openstack.utils;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Map.Entry;
33 import org.onap.so.adapters.vdu.CloudInfo;
34 import org.onap.so.adapters.vdu.PluginAction;
35 import org.onap.so.adapters.vdu.VduArtifact;
36 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
37 import org.onap.so.adapters.vdu.VduException;
38 import org.onap.so.adapters.vdu.VduInstance;
39 import org.onap.so.adapters.vdu.VduModelInfo;
40 import org.onap.so.adapters.vdu.VduPlugin;
41 import org.onap.so.adapters.vdu.VduStateType;
42 import org.onap.so.adapters.vdu.VduStatus;
43 import org.onap.so.cloud.CloudConfig;
44 import org.onap.so.db.catalog.beans.CloudIdentity;
45 import org.onap.so.db.catalog.beans.CloudSite;
46 import org.onap.so.cloud.authentication.AuthenticationMethodFactory;
47 import org.onap.so.db.catalog.beans.HeatTemplate;
48 import org.onap.so.db.catalog.beans.HeatTemplateParam;
49 import org.onap.so.logger.MessageEnum;
50 import org.onap.so.logger.MsoAlarmLogger;
51 import org.onap.so.logger.MsoLogger;
52 import org.onap.so.openstack.beans.HeatCacheEntry;
53 import org.onap.so.openstack.beans.HeatStatus;
54 import org.onap.so.openstack.beans.StackInfo;
55 import org.onap.so.openstack.exceptions.MsoAdapterException;
56 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
57 import org.onap.so.openstack.exceptions.MsoException;
58 import org.onap.so.openstack.exceptions.MsoIOException;
59 import org.onap.so.openstack.exceptions.MsoOpenstackException;
60 import org.onap.so.openstack.exceptions.MsoStackAlreadyExists;
61 import org.onap.so.openstack.exceptions.MsoTenantNotFound;
62 import org.onap.so.openstack.mappers.StackInfoMapper;
63 import org.onap.so.utils.CryptoUtils;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.context.annotation.Primary;
66 import org.springframework.core.env.Environment;
67 import org.springframework.stereotype.Component;
69 import com.fasterxml.jackson.core.type.TypeReference;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72 import com.woorea.openstack.base.client.OpenStackConnectException;
73 import com.woorea.openstack.base.client.OpenStackRequest;
74 import com.woorea.openstack.base.client.OpenStackResponseException;
75 import com.woorea.openstack.heat.Heat;
76 import com.woorea.openstack.heat.model.CreateStackParam;
77 import com.woorea.openstack.heat.model.Stack;
78 import com.woorea.openstack.heat.model.Stack.Output;
79 import com.woorea.openstack.heat.model.Stacks;
80 import com.woorea.openstack.keystone.Keystone;
81 import com.woorea.openstack.keystone.model.Access;
82 import com.woorea.openstack.keystone.model.Authentication;
83 import com.woorea.openstack.keystone.utils.KeystoneUtils;
87 public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{
89 private static final String TOKEN_AUTH = "TokenAuth";
91 private static final String QUERY_ALL_STACKS = "QueryAllStacks";
93 private static final String DELETE_STACK = "DeleteStack";
95 protected static final String HEAT_ERROR = "HeatError";
97 protected static final String CREATE_STACK = "CreateStack";
99 // Cache Heat Clients statically. Since there is just one MSO user, there is no
100 // benefit to re-authentication on every request (or across different flows). The
101 // token will be used until it expires.
103 // The cache key is "tenantId:cloudId"
104 private static Map <String, HeatCacheEntry> heatClientCache = new HashMap <> ();
106 // Fetch cloud configuration each time (may be cached in CloudConfig class)
108 protected CloudConfig cloudConfig;
111 private Environment environment;
114 private AuthenticationMethodFactory authenticationMethodFactory;
117 private MsoTenantUtilsFactory tenantUtilsFactory;
119 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, MsoHeatUtils.class);
121 // Properties names and variables (with default values)
122 protected String createPollIntervalProp = "onap.so.adapters.po.pollInterval";
123 private String deletePollIntervalProp = "onap.so.adapters.po.pollInterval";
124 private String deletePollTimeoutProp = "onap.so.adapters.po.pollTimeout";
126 protected static final String createPollIntervalDefault = "15";
127 private static final String deletePollIntervalDefault = "15";
129 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
132 * keep this old method signature here to maintain backwards compatibility. keep others as well.
133 * this method does not include environment, files, or heatFiles
135 public StackInfo createStack (String cloudSiteId,
139 Map <String, ?> stackInputs,
140 boolean pollForCompletion,
141 int timeoutMinutes) throws MsoException {
142 // Just call the new method with the environment & files variable set to null
143 return this.createStack (cloudSiteId,
156 // This method has environment, but not files or heatFiles
157 public StackInfo createStack (String cloudSiteId,
161 Map <String, ?> stackInputs,
162 boolean pollForCompletion,
164 String environment) throws MsoException {
165 // Just call the new method with the files/heatFiles variables set to null
166 return this.createStack (cloudSiteId,
179 // This method has environment and files, but not heatFiles.
180 public StackInfo createStack (String cloudSiteId,
184 Map <String, ?> stackInputs,
185 boolean pollForCompletion,
188 Map <String, Object> files) throws MsoException {
189 return this.createStack (cloudSiteId,
202 // This method has environment, files, heatfiles
203 public StackInfo createStack (String cloudSiteId,
207 Map <String, ?> stackInputs,
208 boolean pollForCompletion,
211 Map <String, Object> files,
212 Map <String, Object> heatFiles) throws MsoException {
213 return this.createStack (cloudSiteId,
227 * Create a new Stack in the specified cloud location and tenant. The Heat template
228 * and parameter map are passed in as arguments, along with the cloud access credentials.
229 * It is expected that parameters have been validated and contain at minimum the required
230 * parameters for the given template with no extra (undefined) parameters..
232 * The Stack name supplied by the caller must be unique in the scope of this tenant.
233 * However, it should also be globally unique, as it will be the identifier for the
234 * resource going forward in Inventory. This latter is managed by the higher levels
235 * invoking this function.
237 * The caller may choose to let this function poll Openstack for completion of the
238 * stack creation, or may handle polling itself via separate calls to query the status.
239 * In either case, a StackInfo object will be returned containing the current status.
240 * When polling is enabled, a status of CREATED is expected. When not polling, a
241 * status of BUILDING is expected.
243 * An error will be thrown if the requested Stack already exists in the specified
246 * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
247 * parameters for createStack. If environment is non-null, it will be added to the stack.
248 * The nested templates and get_file entries both end up being added to the "files" on the
249 * stack. We must combine them before we add them to the stack if they're both non-null.
251 * @param cloudSiteId The cloud (may be a region) in which to create the stack.
252 * @param tenantId The Openstack ID of the tenant in which to create the Stack
253 * @param stackName The name of the stack to create
254 * @param heatTemplate The Heat template
255 * @param stackInputs A map of key/value inputs
256 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
257 * @param environment An optional yaml-format string to specify environmental parameters
258 * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
260 * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
261 * @param backout Donot delete stack on create Failure - defaulted to True
262 * @return A StackInfo object
263 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
266 @SuppressWarnings("unchecked")
267 public StackInfo createStack (String cloudSiteId,
271 Map <String, ?> stackInputs,
272 boolean pollForCompletion,
275 Map <String, Object> files,
276 Map <String, Object> heatFiles,
277 boolean backout) throws MsoException {
279 // Take out the multicloud inputs, if present.
280 for (String key : MsoMulticloudUtils.MULTICLOUD_INPUTS) {
281 if (stackInputs.containsKey(key)) {
282 stackInputs.remove(key);
283 if (stackInputs.isEmpty()) {
289 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
291 // Obtain the cloud site information where we will create the stack
292 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
293 () -> new MsoCloudSiteNotFound(cloudSiteId));
294 LOGGER.debug("Found: " + cloudSite.toString());
295 // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
296 // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated)
297 Heat heatClient = getHeatClient (cloudSite, tenantId);
298 if (heatClient != null) {
299 LOGGER.debug("Found: " + heatClient.toString());
302 LOGGER.debug ("Ready to Create Stack (" + heatTemplate + ") with input params: " + stackInputs);
304 Stack heatStack = null;
306 // Execute the actual Openstack command to create the Heat stack
307 OpenStackRequest <Stack> request = heatClient.getStacks ().create (stack);
309 // Obtain an MSO token for the tenant
310 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
311 // cloudIdentity.getMsoId(), cloudIdentity.getMsoPass()
313 request.header ("X-Auth-User", cloudIdentity.getMsoId ());
314 request.header ("X-Auth-Key", CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass ()));
315 LOGGER.debug ("headers added, about to executeAndRecordOpenstackRequest");
316 //LOGGER.debug(this.requestToStringBuilder(stack).toString());
317 // END - try to fix X-Auth-User
318 heatStack = executeAndRecordOpenstackRequest (request);
319 } catch (OpenStackResponseException e) {
320 // Since this came on the 'Create Stack' command, nothing was changed
321 // in the cloud. Return the error as an exception.
322 if (e.getStatus () == 409) {
323 // Stack already exists. Return a specific error for this case
324 MsoStackAlreadyExists me = new MsoStackAlreadyExists (stackName, tenantId, cloudSiteId);
325 me.addContext (CREATE_STACK);
328 // Convert the OpenStackResponseException to an MsoOpenstackException
329 LOGGER.debug("ERROR STATUS = " + e.getStatus() + ",\n" + e.getMessage() + "\n" + e.getLocalizedMessage());
330 throw heatExceptionToMsoException (e, CREATE_STACK);
332 } catch (OpenStackConnectException e) {
333 // Error connecting to Openstack instance. Convert to an MsoException
334 throw heatExceptionToMsoException (e, CREATE_STACK);
335 } catch (RuntimeException e) {
337 throw runtimeExceptionToMsoException (e, CREATE_STACK);
340 // Subsequent access by the canonical name "<stack name>/<stack-id>".
341 // Otherwise, simple query by name returns a 302 redirect.
342 // NOTE: This is specific to the v1 Orchestration API.
343 String canonicalName = stackName + "/" + heatStack.getId ();
345 // If client has requested a final response, poll for stack completion
346 if (pollForCompletion) {
347 // Set a time limit on overall polling.
348 // Use the resource (template) timeout for Openstack (expressed in minutes)
349 // and add one poll interval to give Openstack a chance to fail on its own.s
351 int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
352 int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
353 // New 1610 - poll on delete if we rollback - use same values for now
354 int deletePollInterval = createPollInterval;
355 int deletePollTimeout = pollTimeout;
356 boolean createTimedOut = false;
357 StringBuilder stackErrorStatusReason = new StringBuilder("");
358 LOGGER.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
362 heatStack = queryHeatStack (heatClient, canonicalName);
363 LOGGER.debug (heatStack.getStackStatus () + " (" + canonicalName + ")");
365 LOGGER.debug("Current stack " + this.getOutputsAsStringBuilder(heatStack).toString());
366 } catch (Exception e) {
367 LOGGER.debug("an error occurred trying to print out the current outputs of the stack", e);
370 if ("CREATE_IN_PROGRESS".equals (heatStack.getStackStatus ())) {
371 // Stack creation is still running.
372 // Sleep and try again unless timeout has been reached
373 if (pollTimeout <= 0) {
374 // Note that this should not occur, since there is a timeout specified
375 // in the Openstack call.
376 LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Create stack timeout");
377 createTimedOut = true;
381 sleep(createPollInterval * 1000L);
383 pollTimeout -= createPollInterval;
384 LOGGER.debug("pollTimeout remaining: " + pollTimeout);
386 //save off the status & reason msg before we attempt delete
387 stackErrorStatusReason.append("Stack error (" + heatStack.getStackStatus() + "): " + heatStack.getStackStatusReason());
390 } catch (MsoException me) {
391 // Cannot query the stack status. Something is wrong.
392 // Try to roll back the stack
395 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack, stack deletion suppressed");
400 LOGGER.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + canonicalName + " - This will likely fail and/or we won't be able to query to see if delete worked");
401 OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
402 executeAndRecordOpenstackRequest (request);
403 // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
404 // get another one, n'est-ce pas?
405 boolean deleted = false;
408 heatStack = queryHeatStack(heatClient, canonicalName);
409 if (heatStack != null) {
410 LOGGER.debug(heatStack.getStackStatus());
411 if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
412 if (deletePollTimeout <= 0) {
413 LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
414 heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError,
415 "Rollback: DELETE stack timeout");
418 sleep(deletePollInterval * 1000L);
419 deletePollTimeout -= deletePollInterval;
421 } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
422 LOGGER.debug("DELETE_COMPLETE for " + canonicalName);
426 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
430 // assume if we can't find it - it's deleted
431 LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted");
436 } catch (Exception e3) {
437 // Just log this one. We will report the original exception.
438 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e3, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack on error on query");
442 } catch (Exception e2) {
443 // Just log this one. We will report the original exception.
444 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack: Nested exception rolling back stack");
448 // Propagate the original exception from Stack Query.
449 me.addContext (CREATE_STACK);
454 if (!"CREATE_COMPLETE".equals (heatStack.getStackStatus ())) {
455 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error: Polling complete with non-success status: "
456 + heatStack.getStackStatus () + ", " + heatStack.getStackStatusReason (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error");
458 // Rollback the stack creation, since it is in an indeterminate state.
461 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion suppressed");
466 LOGGER.debug("Create Stack errored - attempting to DELETE stack: " + canonicalName);
467 LOGGER.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
468 OpenStackRequest <Void> request = heatClient.getStacks ().deleteByName (canonicalName);
469 executeAndRecordOpenstackRequest (request);
470 boolean deleted = false;
473 heatStack = queryHeatStack(heatClient, canonicalName);
474 if (heatStack != null) {
475 LOGGER.debug(heatStack.getStackStatus() + " (" + canonicalName + ")");
476 if ("DELETE_IN_PROGRESS".equals(heatStack.getStackStatus())) {
477 if (deletePollTimeout <= 0) {
478 LOGGER.error (MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName,
479 heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError,
480 "Rollback: DELETE stack timeout");
483 sleep(deletePollInterval * 1000L);
484 deletePollTimeout -= deletePollInterval;
485 LOGGER.debug("deletePollTimeout remaining: " + deletePollTimeout);
487 } else if ("DELETE_COMPLETE".equals(heatStack.getStackStatus())){
488 LOGGER.debug("DELETE_COMPLETE for " + canonicalName);
491 } else if ("DELETE_FAILED".equals(heatStack.getStackStatus())) {
492 // Warn about this (?) - but still throw the original exception
493 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion FAILED", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error, stack deletion FAILED");
494 LOGGER.debug("Stack deletion FAILED on a rollback of a create - " + canonicalName + ", status=" + heatStack.getStackStatus() + ", reason=" + heatStack.getStackStatusReason());
497 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
501 // assume if we can't find it - it's deleted
502 LOGGER.debug("heatStack returned null - assume the stack " + canonicalName + " has been deleted");
507 } catch (MsoException me2) {
508 // We got an exception on the delete - don't throw this exception - throw the original - just log.
509 LOGGER.debug("Exception thrown trying to delete " + canonicalName + " on a create->rollback: " + me2.getContextMessage(), me2);
510 LOGGER.warn(MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", MsoLogger.ErrorCode.BusinessProcesssError, me2.getContextMessage());
513 } // end while !deleted
514 StringBuilder errorContextMessage;
515 if (createTimedOut) {
516 errorContextMessage = new StringBuilder("Stack Creation Timeout");
518 errorContextMessage = stackErrorStatusReason;
521 errorContextMessage.append(" - stack successfully deleted");
523 errorContextMessage.append(" - encountered an error trying to delete the stack");
525 // MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
526 // me.addContext(CREATE_STACK);
527 // alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
529 } catch (Exception e2) {
530 // shouldn't happen - but handle
531 LOGGER.error (MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack: rolling back stack");
534 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
535 me.addContext(CREATE_STACK);
536 alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
541 // Get initial status, since it will have been null after the create.
542 heatStack = queryHeatStack (heatClient, canonicalName);
543 LOGGER.debug (heatStack.getStackStatus ());
546 return new StackInfoMapper(heatStack).map();
550 * Query for a single stack (by Name) in a tenant. This call will always return a
551 * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
552 * returned - containing only the stack name and a status of NOTFOUND.
554 * @param tenantId The Openstack ID of the tenant in which to query
555 * @param cloudSiteId The cloud identifier (may be a region) in which to query
556 * @param stackName The name of the stack to query (may be simple or canonical)
557 * @return A StackInfo object
558 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
560 public StackInfo queryStack (String cloudSiteId, String tenantId, String stackName) throws MsoException {
561 LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId);
563 // Obtain the cloud site information where we will create the stack
564 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
565 () -> new MsoCloudSiteNotFound(cloudSiteId));
566 LOGGER.debug("Found: " + cloudSite.toString());
568 // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
569 Heat heatClient = null;
571 heatClient = getHeatClient (cloudSite, tenantId);
572 if (heatClient != null) {
573 LOGGER.debug("Found: " + heatClient.toString());
575 } catch (MsoTenantNotFound e) {
576 // Tenant doesn't exist, so stack doesn't either
577 LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
578 return new StackInfo (stackName, HeatStatus.NOTFOUND);
579 } catch (MsoException me) {
580 // Got an Openstack error. Propagate it
581 LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
582 me.addContext ("QueryStack");
587 // An MsoException will propagate transparently to the caller.
588 Stack heatStack = queryHeatStack (heatClient, stackName);
590 if (heatStack == null) {
591 // Stack does not exist. Return a StackInfo with status NOTFOUND
592 return new StackInfo (stackName, HeatStatus.NOTFOUND);
595 return new StackInfoMapper(heatStack).map();
599 * Delete a stack (by Name/ID) in a tenant. If the stack is not found, it will be
600 * considered a successful deletion. The return value is a StackInfo object which
601 * contains the current stack status.
603 * The client may choose to let the adapter poll Openstack for completion of the
604 * stack deletion, or may handle polling itself via separate query calls. In either
605 * case, a StackInfo object will be returned. When polling is enabled, a final
606 * status of NOTFOUND is expected. When not polling, a status of DELETING is expected.
608 * There is no rollback from a successful stack deletion. A deletion failure will
609 * also result in an undefined stack state - the components may or may not have been
610 * all or partially deleted, so the resulting stack must be considered invalid.
612 * @param tenantId The Openstack ID of the tenant in which to perform the delete
613 * @param cloudSiteId The cloud identifier (may be a region) from which to delete the stack.
614 * @param stackName The name/id of the stack to delete. May be simple or canonical
615 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
616 * @return A StackInfo object
617 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
618 * @throws MsoCloudSiteNotFound
620 public StackInfo deleteStack (String tenantId,
623 boolean pollForCompletion) throws MsoException {
624 // Obtain the cloud site information where we will create the stack
625 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
626 () -> new MsoCloudSiteNotFound(cloudSiteId));
627 LOGGER.debug("Found: " + cloudSite.toString());
629 // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
630 Heat heatClient = null;
632 heatClient = getHeatClient (cloudSite, tenantId);
633 if (heatClient != null) {
634 LOGGER.debug("Found: " + heatClient.toString());
636 } catch (MsoTenantNotFound e) {
637 // Tenant doesn't exist, so stack doesn't either
638 LOGGER.debug ("Tenant with id " + tenantId + "not found.", e);
639 return new StackInfo (stackName, HeatStatus.NOTFOUND);
640 } catch (MsoException me) {
641 // Got an Openstack error. Propagate it
642 LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception");
643 me.addContext (DELETE_STACK);
647 // OK if stack not found, perform a query first
648 Stack heatStack = queryHeatStack (heatClient, stackName);
649 if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
650 // Not found. Return a StackInfo with status NOTFOUND
651 return new StackInfo (stackName, HeatStatus.NOTFOUND);
656 // Use canonical name "<stack name>/<stack-id>" to delete.
657 // Otherwise, deletion by name returns a 302 redirect.
658 // NOTE: This is specific to the v1 Orchestration API.
659 String canonicalName = heatStack.getStackName () + "/" + heatStack.getId ();
662 OpenStackRequest <Void> request = null;
663 if(null != heatClient) {
664 request = heatClient.getStacks ().deleteByName (canonicalName);
667 LOGGER.debug ("Heat Client is NULL" );
670 executeAndRecordOpenstackRequest (request);
671 } catch (OpenStackResponseException e) {
672 if (e.getStatus () == 404) {
673 // Not found. We are OK with this. Return a StackInfo with status NOTFOUND
674 return new StackInfo (stackName, HeatStatus.NOTFOUND);
676 // Convert the OpenStackResponseException to an MsoOpenstackException
677 throw heatExceptionToMsoException (e, DELETE_STACK);
679 } catch (OpenStackConnectException e) {
680 // Error connecting to Openstack instance. Convert to an MsoException
681 throw heatExceptionToMsoException (e, DELETE_STACK);
682 } catch (RuntimeException e) {
684 throw runtimeExceptionToMsoException (e, DELETE_STACK);
687 // Requery the stack for current status.
688 // It will probably still exist with "DELETE_IN_PROGRESS" status.
689 heatStack = queryHeatStack (heatClient, canonicalName);
691 if (pollForCompletion) {
692 // Set a timeout on polling
694 int pollInterval = Integer.parseInt(this.environment.getProperty(deletePollIntervalProp, "" + deletePollIntervalDefault));
695 int pollTimeout = Integer.parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + deletePollIntervalDefault));
697 // When querying by canonical name, Openstack returns DELETE_COMPLETE status
698 // instead of "404" (which would result from query by stack name).
699 while (heatStack != null && !"DELETE_COMPLETE".equals (heatStack.getStackStatus ())) {
700 LOGGER.debug ("Stack status: " + heatStack.getStackStatus ());
702 if ("DELETE_FAILED".equals (heatStack.getStackStatus ())) {
703 // Throw a 'special case' of MsoOpenstackException to report the Heat status
704 String error = "Stack delete error (" + heatStack.getStackStatus ()
706 + heatStack.getStackStatusReason ();
707 MsoOpenstackException me = new MsoOpenstackException (0, "", error);
708 me.addContext (DELETE_STACK);
710 // Alarm this condition, stack deletion failed
711 alarmLogger.sendAlarm (HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage ());
716 if (pollTimeout <= 0) {
717 LOGGER.error (MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, heatStack.getStackStatus (), "", "", MsoLogger.ErrorCode.AvailabilityError, "Delete Stack Timeout");
719 // Throw a 'special case' of MsoOpenstackException to report the Heat status
720 MsoOpenstackException me = new MsoOpenstackException (0, "", "Stack Deletion Timeout");
721 me.addContext (DELETE_STACK);
723 // Alarm this condition, stack deletion failed
724 alarmLogger.sendAlarm (HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage ());
729 sleep(pollInterval * 1000L);
731 pollTimeout -= pollInterval;
732 LOGGER.debug("pollTimeout remaining: " + pollTimeout);
734 heatStack = queryHeatStack (heatClient, canonicalName);
737 // The stack is gone when this point is reached
738 return new StackInfo (stackName, HeatStatus.NOTFOUND);
741 // Return the current status (if not polling, the delete may still be in progress)
742 StackInfo stackInfo = new StackInfoMapper(heatStack).map();
743 stackInfo.setName (stackName);
749 * Query for all stacks in a tenant site. This call will return a List of StackInfo
750 * objects, one for each deployed stack.
752 * Note that this is limited to a single site. To ensure that a tenant is truly
753 * empty would require looping across all tenant endpoints.
755 * @param tenantId The Openstack ID of the tenant to query
756 * @param cloudSiteId The cloud identifier (may be a region) in which to query.
757 * @return A List of StackInfo objects
758 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
759 * @throws MsoCloudSiteNotFound
761 public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException {
762 // Obtain the cloud site information where we will create the stack
763 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(
764 () -> new MsoCloudSiteNotFound(cloudSiteId));
765 // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId)
766 Heat heatClient = getHeatClient (cloudSite, tenantId);
769 OpenStackRequest <Stacks> request = heatClient.getStacks ().list ();
770 Stacks stacks = executeAndRecordOpenstackRequest (request);
772 List <StackInfo> stackList = new ArrayList <> ();
774 // Not sure if returns an empty list or null if no stacks exist
775 if (stacks != null) {
776 for (Stack stack : stacks) {
777 stackList.add (new StackInfoMapper(stack).map());
782 } catch (OpenStackResponseException e) {
783 if (e.getStatus () == 404) {
784 // Not sure if this can happen, but return an empty list
785 LOGGER.debug ("queryAllStacks - stack not found: ");
786 return new ArrayList <> ();
788 // Convert the OpenStackResponseException to an MsoOpenstackException
789 throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
791 } catch (OpenStackConnectException e) {
792 // Error connecting to Openstack instance. Convert to an MsoException
793 throw heatExceptionToMsoException (e, QUERY_ALL_STACKS);
794 } catch (RuntimeException e) {
796 throw runtimeExceptionToMsoException (e, QUERY_ALL_STACKS);
801 * Validate parameters to be passed to Heat template. This method performs
803 * 1. Apply default values to parameters which have them defined
804 * 2. Report any required parameters that are missing. This will generate an
805 * exception in the caller, since stack create/update operations would fail.
806 * 3. Report and remove any extraneous parameters. This will allow clients to
807 * pass supersets of parameters and not get errors.
809 * These functions depend on the HeatTemplate definition from the MSO Catalog DB,
810 * along with the input parameter Map. The output is an updated parameter map.
811 * If the parameters are invalid for the template, an IllegalArgumentException
814 public Map <String, Object> validateStackParams (Map <String, Object> inputParams,
815 HeatTemplate heatTemplate) {
816 // Check that required parameters have been supplied for this template type
817 StringBuilder missingParams = null;
818 List <String> paramList = new ArrayList <> ();
820 // TODO: Enhance DB to support defaults for Heat Template parameters
822 for (HeatTemplateParam parm : heatTemplate.getParameters ()) {
823 if (parm.isRequired () && !inputParams.containsKey (parm.getParamName ())) {
824 if (missingParams == null) {
825 missingParams = new StringBuilder(parm.getParamName());
827 missingParams.append("," + parm.getParamName());
830 paramList.add (parm.getParamName ());
832 if (missingParams != null) {
833 // Problem - missing one or more required parameters
834 String error = "Missing Required inputs for HEAT Template: " + missingParams;
835 LOGGER.error (MessageEnum.RA_MISSING_PARAM, missingParams + " for HEAT Template", "", "", MsoLogger.ErrorCode.SchemaError, "Missing Required inputs for HEAT Template: " + missingParams);
836 throw new IllegalArgumentException (error);
839 // Remove any extraneous parameters (don't throw an error)
840 Map <String, Object> updatedParams = new HashMap <> ();
841 List <String> extraParams = new ArrayList <> ();
843 for (Entry<String, Object> entry : inputParams.entrySet()) {
844 if (!paramList.contains(entry.getKey())) {
845 // This is not a valid parameter for this template
846 extraParams.add(entry.getKey());
848 updatedParams.put(entry.getKey(), entry.getValue());
852 if (!extraParams.isEmpty ()) {
853 LOGGER.warn (MessageEnum.RA_GENERAL_WARNING, "Heat Stack (" + heatTemplate.getTemplateName ()
854 + ") extra input params received: "
855 + extraParams, "", "", MsoLogger.ErrorCode.DataError, "Heat Stack (" + heatTemplate.getTemplateName () + ") extra input params received: "+ extraParams);
858 return updatedParams;
861 // ---------------------------------------------------------------
862 // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
865 * Get a Heat client for the Openstack Identity service.
866 * This requires a 'member'-level userId + password, which will be retrieved from
867 * properties based on the specified cloud Id. The tenant in which to operate
868 * must also be provided.
870 * On successful authentication, the Heat object will be cached for the
871 * tenantID + cloudId so that it can be reused without reauthenticating with
872 * Openstack every time.
874 * @return an authenticated Heat object
876 public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException {
877 String cloudId = cloudSite.getId();
879 // Check first in the cache of previously authorized clients
880 String cacheKey = cloudId + ":" + tenantId;
881 if (heatClientCache.containsKey (cacheKey)) {
882 if (!heatClientCache.get (cacheKey).isExpired ()) {
883 LOGGER.debug ("Using Cached HEAT Client for " + cacheKey);
884 return heatClientCache.get (cacheKey).getHeatClient ();
886 // Token is expired. Remove it from cache.
887 heatClientCache.remove (cacheKey);
888 LOGGER.debug ("Expired Cached HEAT Client for " + cacheKey);
892 // Obtain an MSO token for the tenant
893 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
894 LOGGER.debug("Found: " + cloudIdentity.toString());
895 MsoTenantUtils tenantUtils = tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType());
896 String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity);
897 LOGGER.debug("keystoneUrl=" + keystoneUrl);
898 Keystone keystoneTenantClient = new Keystone (keystoneUrl);
899 Access access = null;
901 Authentication credentials = authenticationMethodFactory.getAuthenticationFor(cloudIdentity);
903 OpenStackRequest <Access> request = keystoneTenantClient.tokens ()
904 .authenticate (credentials).withTenantId (tenantId);
906 access = executeAndRecordOpenstackRequest (request);
907 } catch (OpenStackResponseException e) {
908 if (e.getStatus () == 401) {
909 // Authentication error.
910 String error = "Authentication Failure: tenant=" + tenantId + ",cloud=" + cloudIdentity.getId ();
911 alarmLogger.sendAlarm ("MsoAuthenticationError", MsoAlarmLogger.CRITICAL, error);
912 throw new MsoAdapterException (error);
914 throw keystoneErrorToMsoException (e, TOKEN_AUTH);
916 } catch (OpenStackConnectException e) {
917 // Connection to Openstack failed
918 MsoIOException me = new MsoIOException (e.getMessage (), e);
919 me.addContext (TOKEN_AUTH);
921 } catch (RuntimeException e) {
923 throw runtimeExceptionToMsoException (e, TOKEN_AUTH);
926 // For DCP/LCP, the region should be the cloudId.
927 String region = cloudSite.getRegionId ();
928 String heatUrl = null;
930 // Isolate trying to printout the region IDs
932 LOGGER.debug("access=" + access.toString());
933 for (Access.Service service : access.getServiceCatalog()) {
934 List<Access.Service.Endpoint> endpoints = service.getEndpoints();
935 for (Access.Service.Endpoint endpoint : endpoints) {
936 LOGGER.debug("AIC returned region=" + endpoint.getRegion());
939 } catch (Exception e) {
940 LOGGER.debug("Encountered an error trying to printout Access object returned from AIC. " + e.getMessage());
942 heatUrl = KeystoneUtils.findEndpointURL (access.getServiceCatalog (), "orchestration", region, "public");
943 LOGGER.debug("heatUrl=" + heatUrl + ", region=" + region);
944 } catch (RuntimeException e) {
945 // This comes back for not found (probably an incorrect region ID)
946 String error = "AIC did not match an orchestration service for: region=" + region + ",cloud=" + cloudIdentity.getIdentityUrl();
947 alarmLogger.sendAlarm ("MsoConfigurationError", MsoAlarmLogger.CRITICAL, error);
948 throw new MsoAdapterException (error, e);
951 Heat heatClient = new Heat (heatUrl);
952 heatClient.token (access.getToken ().getId ());
954 heatClientCache.put (cacheKey,
955 new HeatCacheEntry (heatUrl,
956 access.getToken ().getId (),
957 access.getToken ().getExpires ()));
958 LOGGER.debug ("Caching HEAT Client for " + cacheKey);
964 * Forcibly expire a HEAT client from the cache. This call is for use by
965 * the KeystoneClient in case where a tenant is deleted. In that case,
966 * all cached credentials must be purged so that fresh authentication is
967 * done if a similarly named tenant is re-created.
969 * Note: This is probably only applicable to dev/test environments where
970 * the same Tenant Name is repeatedly used for creation/deletion.
974 public void expireHeatClient (String tenantId, String cloudId) {
975 String cacheKey = cloudId + ":" + tenantId;
976 if (heatClientCache.containsKey (cacheKey)) {
977 heatClientCache.remove (cacheKey);
978 LOGGER.debug ("Deleted Cached HEAT Client for " + cacheKey);
983 * Query for a Heat Stack. This function is needed in several places, so
984 * a common method is useful. This method takes an authenticated Heat Client
985 * (which internally identifies the cloud & tenant to search), and returns
986 * a Stack object if found, Null if not found, or an MsoOpenstackException
987 * if the Openstack API call fails.
989 * The stack name may be a simple name or a canonical name ("{name}/{id}").
990 * When simple name is used, Openstack always returns a 302 redirect which
991 * results in a 2nd request (to the canonical name). Note that query by
992 * canonical name for a deleted stack returns a Stack object with status
993 * "DELETE_COMPLETE" while query by simple name for a deleted stack returns
996 * @param heatClient an authenticated Heat client
998 * @param stackName the stack name to query
1000 * @return a Stack object that describes the current stack or null if the
1001 * requested stack doesn't exist.
1003 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception
1005 protected Stack queryHeatStack (Heat heatClient, String stackName) throws MsoException {
1006 if (stackName == null) {
1010 OpenStackRequest <Stack> request = heatClient.getStacks ().byName (stackName);
1011 return executeAndRecordOpenstackRequest (request);
1012 } catch (OpenStackResponseException e) {
1013 if (e.getStatus () == 404) {
1014 LOGGER.debug ("queryHeatStack - stack not found: " + stackName);
1017 // Convert the OpenStackResponseException to an MsoOpenstackException
1018 throw heatExceptionToMsoException (e, "QueryStack");
1020 } catch (OpenStackConnectException e) {
1021 // Connection to Openstack failed
1022 throw heatExceptionToMsoException (e, "QueryAllStack");
1027 public Map<String, Object> queryStackForOutputs(String cloudSiteId,
1028 String tenantId, String stackName) throws MsoException {
1029 LOGGER.debug("MsoHeatUtils.queryStackForOutputs)");
1030 StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
1031 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
1034 return heatStack.getOutputs();
1037 public void copyStringOutputsToInputs(Map<String, String> inputs,
1038 Map<String, Object> otherStackOutputs, boolean overWrite) {
1039 if (inputs == null || otherStackOutputs == null)
1041 for (String key : otherStackOutputs.keySet()) {
1042 if (!inputs.containsKey(key)) {
1043 Object obj = otherStackOutputs.get(key);
1044 if (obj instanceof String) {
1045 inputs.put(key, (String) otherStackOutputs.get(key));
1046 } else if (obj instanceof JsonNode ){
1047 // This is a bit of mess - but I think it's the least impacting
1048 // let's convert it BACK to a string - then it will get converted back later
1050 String str = this.convertNode((JsonNode) obj);
1051 inputs.put(key, str);
1052 } catch (Exception e) {
1053 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for JsonNode "+ key, e);
1054 //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
1056 } else if (obj instanceof java.util.LinkedHashMap) {
1057 LOGGER.debug("LinkedHashMap - this is showing up as a LinkedHashMap instead of JsonNode");
1059 String str = JSON_MAPPER.writeValueAsString(obj);
1060 inputs.put(key, str);
1061 } catch (Exception e) {
1062 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for LinkedHashMap "+ key, e);
1064 } else if (obj instanceof Integer) {
1066 String str = "" + obj;
1067 inputs.put(key, str);
1068 } catch (Exception e) {
1069 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Integer "+ key, e);
1073 String str = obj.toString();
1074 inputs.put(key, str);
1075 } catch (Exception e) {
1076 LOGGER.debug("DANGER WILL ROBINSON: unable to convert value for Other "+ key +" (" + e.getMessage() + ")", e);
1077 //effect here is this value will not have been copied to the inputs - and therefore will error out downstream
1084 public StringBuilder requestToStringBuilder(CreateStackParam stack) {
1085 StringBuilder sb = new StringBuilder();
1086 sb.append("Stack:\n");
1087 sb.append("\tStackName: " + stack.getStackName());
1088 sb.append("\tTemplateUrl: " + stack.getTemplateUrl());
1089 sb.append("\tTemplate: " + stack.getTemplate());
1090 sb.append("\tEnvironment: " + stack.getEnvironment());
1091 sb.append("\tTimeout: " + stack.getTimeoutMinutes());
1092 sb.append("\tParameters:\n");
1093 Map<String, Object> params = stack.getParameters();
1094 if (params == null || params.size() < 1) {
1095 sb.append("\nNONE");
1097 for (String key : params.keySet()) {
1098 if (params.get(key) instanceof String) {
1099 sb.append("\n").append(key).append("=").append((String) params.get(key));
1100 } else if (params.get(key) instanceof JsonNode) {
1101 String jsonStringOut = this.convertNode((JsonNode)params.get(key));
1102 sb.append("\n").append(key).append("=").append(jsonStringOut);
1103 } else if (params.get(key) instanceof Integer) {
1104 String integerOut = "" + params.get(key);
1105 sb.append("\n").append(key).append("=").append(integerOut);
1109 String str = params.get(key).toString();
1110 sb.append("\n").append(key).append("=").append(str);
1111 } catch (Exception e) {
1112 LOGGER.debug("Exception :",e);
1120 private String convertNode(final JsonNode node) {
1122 final Object obj = JSON_MAPPER.treeToValue(node, Object.class);
1123 final String json = JSON_MAPPER.writeValueAsString(obj);
1125 } catch (Exception e) {
1126 LOGGER.debug("Error converting json to string " + e.getMessage(), e);
1128 return "[Error converting json to string]";
1132 protected StringBuilder getOutputsAsStringBuilder(Stack heatStack) {
1133 // This should only be used as a utility to print out the stack outputs
1135 StringBuilder sb = new StringBuilder("");
1136 if (heatStack == null) {
1137 sb.append("(heatStack is null)");
1140 List<Output> outputList = heatStack.getOutputs();
1141 if (outputList == null || outputList.isEmpty()) {
1142 sb.append("(outputs is empty)");
1145 Map<String, Object> outputs = new HashMap<>();
1146 for (Output outputItem : outputList) {
1147 outputs.put(outputItem.getOutputKey(), outputItem.getOutputValue());
1150 sb.append("OUTPUTS:\n");
1151 for (String key : outputs.keySet()) {
1152 sb.append("outputs[").append(counter++).append("]: ").append(key).append("=");
1153 Object obj = outputs.get(key);
1154 if (obj instanceof String) {
1155 sb.append((String) obj).append(" (a string)");
1156 } else if (obj instanceof JsonNode) {
1157 sb.append(this.convertNode((JsonNode) obj)).append(" (a JsonNode)");
1158 } else if (obj instanceof java.util.LinkedHashMap) {
1160 String str = JSON_MAPPER.writeValueAsString(obj);
1161 sb.append(str).append(" (a java.util.LinkedHashMap)");
1162 } catch (Exception e) {
1163 LOGGER.debug("Exception :",e);
1164 sb.append("(a LinkedHashMap value that would not convert nicely)");
1166 } else if (obj instanceof Integer) {
1169 str = obj.toString() + " (an Integer)\n";
1170 } catch (Exception e) {
1171 LOGGER.debug("Exception :",e);
1172 str = "(an Integer unable to call .toString() on)";
1175 } else if (obj instanceof ArrayList) {
1178 str = obj.toString() + " (an ArrayList)";
1179 } catch (Exception e) {
1180 LOGGER.debug("Exception :",e);
1181 str = "(an ArrayList unable to call .toString() on?)";
1184 } else if (obj instanceof Boolean) {
1187 str = obj.toString() + " (a Boolean)";
1188 } catch (Exception e) {
1189 LOGGER.debug("Exception :",e);
1190 str = "(an Boolean unable to call .toString() on?)";
1197 str = obj.toString() + " (unknown Object type)";
1198 } catch (Exception e) {
1199 LOGGER.debug("Exception :",e);
1200 str = "(a value unable to call .toString() on?)";
1211 public void copyBaseOutputsToInputs(Map<String, Object> inputs,
1212 Map<String, Object> otherStackOutputs, List<String> paramNames, Map<String, String> aliases) {
1213 if (inputs == null || otherStackOutputs == null)
1215 for (String key : otherStackOutputs.keySet()) {
1216 if (paramNames != null) {
1217 if (!paramNames.contains(key) && !aliases.containsKey(key)) {
1218 LOGGER.debug("\tParameter " + key + " is NOT defined to be in the template - do not copy to inputs");
1221 if (aliases.containsKey(key)) {
1222 LOGGER.debug("Found an alias! Will move " + key + " to " + aliases.get(key));
1223 Object obj = otherStackOutputs.get(key);
1224 key = aliases.get(key);
1225 otherStackOutputs.put(key, obj);
1228 if (!inputs.containsKey(key)) {
1229 Object obj = otherStackOutputs.get(key);
1230 LOGGER.debug("\t**Adding " + key + " to inputs (.toString()=" + obj.toString());
1231 if (obj instanceof String) {
1232 LOGGER.debug("\t\t**A String");
1233 inputs.put(key, obj);
1234 } else if (obj instanceof Integer) {
1235 LOGGER.debug("\t\t**An Integer");
1236 inputs.put(key, obj);
1237 } else if (obj instanceof JsonNode) {
1238 LOGGER.debug("\t\t**A JsonNode");
1239 inputs.put(key, obj);
1240 } else if (obj instanceof Boolean) {
1241 LOGGER.debug("\t\t**A Boolean");
1242 inputs.put(key, obj);
1243 } else if (obj instanceof java.util.LinkedHashMap) {
1244 LOGGER.debug("\t\t**A java.util.LinkedHashMap **");
1245 inputs.put(key, obj);
1246 } else if (obj instanceof java.util.ArrayList) {
1247 LOGGER.debug("\t\t**An ArrayList");
1248 inputs.put(key, obj);
1250 LOGGER.debug("\t\t**UNKNOWN OBJECT TYPE");
1251 inputs.put(key, obj);
1254 LOGGER.debug("key=" + key + " is already in the inputs - will not overwrite");
1260 public List<String> convertCdlToArrayList(String cdl) {
1261 String cdl2 = cdl.trim();
1263 if (cdl2.startsWith("[") && cdl2.endsWith("]")) {
1264 cdl3 = cdl2.substring(1, cdl2.lastIndexOf("]"));
1268 return new ArrayList<>(Arrays.asList(cdl3.split(",")));
1272 * New with 1707 - this method will convert all the String *values* of the inputs
1273 * to their "actual" object type (based on the param type: in the db - which comes from the template):
1274 * (heat variable type) -> java Object type
1277 * json -> JsonNode XXX Removed with MSO-1475 / 1802
1278 * comma_delimited_list -> ArrayList
1279 * boolean -> Boolean
1280 * if any of the conversions should fail, we will default to adding it to the inputs
1281 * as a string - see if Openstack can handle it.
1282 * Also, will remove any params that are extra.
1283 * Any aliases will be converted to their appropriate name (anyone use this feature?)
1284 * @param inputs - the Map<String, String> of the inputs received on the request
1285 * @param template the HeatTemplate object - this is so we can also verify if the param is valid for this template
1286 * @return HashMap<String, Object> of the inputs, cleaned and converted
1288 public Map<String, Object> convertInputMap(Map<String, String> inputs, HeatTemplate template) {
1289 HashMap<String, Object> newInputs = new HashMap<>();
1290 HashMap<String, HeatTemplateParam> params = new HashMap<>();
1291 HashMap<String, HeatTemplateParam> paramAliases = new HashMap<>();
1293 if (inputs == null) {
1294 LOGGER.debug("convertInputMap - inputs is null - nothing to do here");
1295 return new HashMap<>();
1298 LOGGER.debug("convertInputMap in MsoHeatUtils called, with " + inputs.size() + " inputs, and template " + template.getArtifactUuid());
1300 LOGGER.debug(template.toString());
1301 Set<HeatTemplateParam> paramSet = template.getParameters();
1302 LOGGER.debug("paramSet has " + paramSet.size() + " entries");
1303 } catch (Exception e) {
1304 LOGGER.debug("Exception occurred in convertInputMap:" + e.getMessage(), e);
1307 for (HeatTemplateParam htp : template.getParameters()) {
1308 LOGGER.debug("Adding " + htp.getParamName());
1309 params.put(htp.getParamName(), htp);
1310 if (htp.getParamAlias() != null && !"".equals(htp.getParamAlias())) {
1311 LOGGER.debug("\tFound ALIAS " + htp.getParamName() + "->" + htp.getParamAlias());
1312 paramAliases.put(htp.getParamAlias(), htp);
1315 LOGGER.debug("Now iterate through the inputs...");
1316 for (String key : inputs.keySet()) {
1317 LOGGER.debug("key=" + key);
1318 boolean alias = false;
1319 String realName = null;
1320 if (!params.containsKey(key)) {
1321 LOGGER.debug(key + " is not a parameter in the template! - check for an alias");
1322 // add check here for an alias
1323 if (!paramAliases.containsKey(key)) {
1324 LOGGER.debug("The parameter " + key + " is in the inputs, but it's not a parameter for this template - omit");
1328 realName = paramAliases.get(key).getParamName();
1329 LOGGER.debug("FOUND AN ALIAS! Will use " + realName + " in lieu of give key/alias " + key);
1332 String type = params.get(key).getParamType();
1333 if (type == null || "".equals(type)) {
1334 LOGGER.debug("**PARAM_TYPE is null/empty for " + key + ", will default to string");
1337 LOGGER.debug("Parameter: " + key + " is of type " + type);
1338 if ("string".equalsIgnoreCase(type)) {
1340 String str = inputs.get(key);
1342 newInputs.put(realName, str);
1344 newInputs.put(key, str);
1345 } else if ("number".equalsIgnoreCase(type)) {
1346 String integerString = inputs.get(key);
1347 Integer anInteger = null;
1349 anInteger = Integer.parseInt(integerString);
1350 } catch (Exception e) {
1351 LOGGER.debug("Unable to convert " + integerString + " to an integer!!", e);
1354 if (anInteger != null) {
1356 newInputs.put(realName, anInteger);
1358 newInputs.put(key, anInteger);
1362 newInputs.put(realName, integerString);
1364 newInputs.put(key, integerString);
1366 } else if ("json".equalsIgnoreCase(type)) {
1367 // MSO-1475 - Leave this as a string now
1368 String jsonString = inputs.get(key);
1369 LOGGER.debug("Skipping conversion to jsonNode...");
1371 newInputs.put(realName, jsonString);
1373 newInputs.put(key, jsonString);
1375 } else if ("comma_delimited_list".equalsIgnoreCase(type)) {
1376 String commaSeparated = inputs.get(key);
1378 List<String> anArrayList = this.convertCdlToArrayList(commaSeparated);
1380 newInputs.put(realName, anArrayList);
1382 newInputs.put(key, anArrayList);
1383 } catch (Exception e) {
1384 LOGGER.debug("Unable to convert " + commaSeparated + " to an ArrayList!!", e);
1386 newInputs.put(realName, commaSeparated);
1388 newInputs.put(key, commaSeparated);
1390 } else if ("boolean".equalsIgnoreCase(type)) {
1391 String booleanString = inputs.get(key);
1392 Boolean aBool = Boolean.valueOf(booleanString);
1394 newInputs.put(realName, aBool);
1396 newInputs.put(key, aBool);
1398 // it's null or something undefined - just add it back as a String
1399 String str = inputs.get(key);
1401 newInputs.put(realName, str);
1403 newInputs.put(key, str);
1410 * This helpful method added for Valet
1412 public String getCloudSiteKeystoneUrl(String cloudSiteId) throws MsoCloudSiteNotFound {
1413 String keystone_url = null;
1415 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
1416 CloudIdentity cloudIdentity = cloudSite.getIdentityService();
1417 keystone_url = cloudIdentity.getIdentityUrl();
1418 } catch (Exception e) {
1419 throw new MsoCloudSiteNotFound(cloudSiteId);
1421 if (keystone_url == null || keystone_url.isEmpty()) {
1422 throw new MsoCloudSiteNotFound(cloudSiteId);
1424 return keystone_url;
1428 * Create a string suitable for being dumped to a debug log that creates a
1429 * pseudo-JSON request dumping what's being sent to Openstack API in the create or update request
1432 private String printStackRequest(String tenantId,
1433 Map<String, Object> heatFiles,
1434 Map<String, Object> nestedTemplates,
1436 Map<String, Object> inputs,
1437 String vfModuleName,
1441 String cloudSiteId) {
1442 StringBuilder sb = new StringBuilder();
1443 sb.append("CREATE STACK REQUEST (formatted for readability)\n");
1444 sb.append("tenant=" + tenantId + ", cloud=" + cloudSiteId);
1446 sb.append(" \"stack_name\": \"" + vfModuleName + "\",\n");
1447 sb.append(" \"disable_rollback\": " + backout + ",\n");
1448 sb.append(" \"timeout_mins\": " + timeoutMinutes + ",\n");
1449 sb.append(" \"template\": {\n");
1450 sb.append(template);
1452 sb.append(" \"environment\": {\n");
1453 if (environment == null)
1454 sb.append("<none>");
1456 sb.append(environment);
1458 sb.append(" \"files\": {\n");
1459 int filesCounter = 0;
1460 if (heatFiles != null) {
1461 for (String key : heatFiles.keySet()) {
1463 if (filesCounter > 1) {
1466 sb.append(" \"" + key + "\": {\n");
1467 sb.append(heatFiles.get(key).toString() + "\n }");
1470 if (nestedTemplates != null) {
1471 for (String key : nestedTemplates.keySet()) {
1473 if (filesCounter > 1) {
1476 sb.append(" \"" + key + "\": {\n");
1477 sb.append(nestedTemplates.get(key).toString() + "\n }");
1480 sb.append("\n },\n");
1481 sb.append(" \"parameters\": {\n");
1482 int paramCounter = 0;
1483 for (String name : inputs.keySet()) {
1485 if (paramCounter > 1) {
1488 Object o = inputs.get(name);
1489 if (o instanceof java.lang.String) {
1490 sb.append(" \"" + name + "\": \"" + inputs.get(name).toString() + "\"");
1491 } else if (o instanceof Integer) {
1492 sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
1493 } else if (o instanceof ArrayList) {
1494 sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
1495 } else if (o instanceof Boolean) {
1496 sb.append(" \"" + name + "\": " + inputs.get(name).toString() );
1498 sb.append(" \"" + name + "\": " + "\"(there was an issue trying to dump this value...)\"" );
1501 sb.append("\n }\n}\n");
1503 return sb.toString();
1506 /*******************************************************************************
1508 * Methods (and associated utilities) to implement the VduPlugin interface
1510 *******************************************************************************/
1513 * VduPlugin interface for instantiate function.
1515 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
1516 * and then invoke the existing function.
1519 public VduInstance instantiateVdu (
1520 CloudInfo cloudInfo,
1521 String instanceName,
1522 Map<String,Object> inputs,
1523 VduModelInfo vduModel,
1524 boolean rollbackOnFailure)
1527 String cloudSiteId = cloudInfo.getCloudSiteId();
1528 String tenantId = cloudInfo.getTenantId();
1530 // Translate the VDU ModelInformation structure to that which is needed for
1531 // creating the Heat stack. Loop through the artifacts, looking specifically
1532 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
1533 // be attached as a FILE.
1534 String heatTemplate = null;
1535 Map<String,Object> nestedTemplates = new HashMap<>();
1536 Map<String,Object> files = new HashMap<>();
1537 String heatEnvironment = null;
1539 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
1540 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
1541 heatTemplate = new String(vduArtifact.getContent());
1543 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
1544 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
1546 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
1547 heatEnvironment = new String(vduArtifact.getContent());
1552 StackInfo stackInfo = createStack (cloudSiteId,
1557 true, // poll for completion
1558 vduModel.getTimeoutMinutes(),
1564 // Populate a vduInstance from the StackInfo
1565 return stackInfoToVduInstance(stackInfo);
1567 catch (Exception e) {
1568 throw new VduException ("MsoHeatUtils (instantiateVDU): createStack Exception", e);
1574 * VduPlugin interface for query function.
1577 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
1580 String cloudSiteId = cloudInfo.getCloudSiteId();
1581 String tenantId = cloudInfo.getTenantId();
1584 // Query the Cloudify Deployment object and populate a VduInstance
1585 StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
1587 return stackInfoToVduInstance(stackInfo);
1589 catch (Exception e) {
1590 throw new VduException ("MsoHeatUtile (queryVdu): queryStack Exception ", e);
1596 * VduPlugin interface for delete function.
1599 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
1602 String cloudSiteId = cloudInfo.getCloudSiteId();
1603 String tenantId = cloudInfo.getTenantId();
1606 // Delete the Heat stack
1607 StackInfo stackInfo = deleteStack (tenantId, cloudSiteId, instanceId, true);
1609 // Populate a VduInstance based on the deleted Cloudify Deployment object
1610 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
1612 // Override return state to DELETED (HeatUtils sets to NOTFOUND)
1613 vduInstance.getStatus().setState(VduStateType.DELETED);
1617 catch (Exception e) {
1618 throw new VduException ("Delete VDU Exception", e);
1624 * VduPlugin interface for update function.
1626 * Update is currently not supported in the MsoHeatUtils implementation of VduPlugin.
1627 * Just return a VduException.
1631 public VduInstance updateVdu (
1632 CloudInfo cloudInfo,
1634 Map<String,Object> inputs,
1635 VduModelInfo vduModel,
1636 boolean rollbackOnFailure)
1639 throw new VduException ("MsoHeatUtils: updateVdu interface not supported");
1644 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
1646 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
1648 VduInstance vduInstance = new VduInstance();
1650 // The full canonical name as the instance UUID
1651 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
1652 vduInstance.setVduInstanceName(stackInfo.getName());
1654 // Copy inputs and outputs
1655 vduInstance.setInputs(stackInfo.getParameters());
1656 vduInstance.setOutputs(stackInfo.getOutputs());
1658 // Translate the status elements
1659 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
1664 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
1666 VduStatus vduStatus = new VduStatus();
1668 // Map the status fields to more generic VduStatus.
1669 // There are lots of HeatStatus values, so this is a bit long...
1670 HeatStatus heatStatus = stackInfo.getStatus();
1671 String statusMessage = stackInfo.getStatusMessage();
1673 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
1674 vduStatus.setState(VduStateType.INSTANTIATING);
1675 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
1677 else if (heatStatus == HeatStatus.NOTFOUND) {
1678 vduStatus.setState(VduStateType.NOTFOUND);
1680 else if (heatStatus == HeatStatus.CREATED) {
1681 vduStatus.setState(VduStateType.INSTANTIATED);
1682 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
1684 else if (heatStatus == HeatStatus.UPDATED) {
1685 vduStatus.setState(VduStateType.INSTANTIATED);
1686 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
1688 else if (heatStatus == HeatStatus.UPDATING) {
1689 vduStatus.setState(VduStateType.UPDATING);
1690 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
1692 else if (heatStatus == HeatStatus.DELETING) {
1693 vduStatus.setState(VduStateType.DELETING);
1694 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
1696 else if (heatStatus == HeatStatus.FAILED) {
1697 vduStatus.setState(VduStateType.FAILED);
1698 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
1700 vduStatus.setState(VduStateType.UNKNOWN);
1706 protected void sleep(long time) {
1709 } catch (InterruptedException e) {
1710 LOGGER.debug ("Thread interrupted while sleeping", e);
1711 Thread.currentThread().interrupt();