2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Intel Corp. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.so.openstack.utils;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.woorea.openstack.heat.model.CreateStackParam;
28 import java.net.MalformedURLException;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.Scanner;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.UriBuilderException;
37 import org.onap.so.adapters.vdu.CloudInfo;
38 import org.onap.so.adapters.vdu.PluginAction;
39 import org.onap.so.adapters.vdu.VduArtifact;
40 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
41 import org.onap.so.adapters.vdu.VduException;
42 import org.onap.so.adapters.vdu.VduInstance;
43 import org.onap.so.adapters.vdu.VduModelInfo;
44 import org.onap.so.adapters.vdu.VduPlugin;
45 import org.onap.so.adapters.vdu.VduStateType;
46 import org.onap.so.adapters.vdu.VduStatus;
47 import org.onap.so.client.HttpClientFactory;
48 import org.onap.so.client.RestClient;
49 import org.onap.so.db.catalog.beans.CloudSite;
50 import org.onap.so.logger.ErrorCode;
51 import org.onap.so.logger.MessageEnum;
52 import org.onap.so.openstack.beans.HeatStatus;
53 import org.onap.so.openstack.beans.StackInfo;
54 import org.onap.so.openstack.exceptions.MsoAdapterException;
55 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
56 import org.onap.so.openstack.exceptions.MsoException;
57 import org.onap.so.openstack.exceptions.MsoOpenstackException;
58 import org.onap.so.utils.TargetEntity;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.core.env.Environment;
63 import org.springframework.stereotype.Component;
66 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
68 public static final String OOF_DIRECTIVES = "oof_directives";
69 public static final String SDNC_DIRECTIVES = "sdnc_directives";
70 public static final String VNF_ID = "vnf_id";
71 public static final String VF_MODULE_ID = "vf_module_id";
72 public static final String TEMPLATE_TYPE = "template_type";
73 public static final List<String> MULTICLOUD_INPUTS =
74 Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
76 private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
78 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
79 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
82 private Environment environment;
84 /******************************************************************************
86 * Methods (and associated utilities) to implement the VduPlugin interface
88 *******************************************************************************/
91 * Create a new Stack in the specified cloud location and tenant. The Heat template
92 * and parameter map are passed in as arguments, along with the cloud access credentials.
93 * It is expected that parameters have been validated and contain at minimum the required
94 * parameters for the given template with no extra (undefined) parameters..
96 * The Stack name supplied by the caller must be unique in the scope of this tenant.
97 * However, it should also be globally unique, as it will be the identifier for the
98 * resource going forward in Inventory. This latter is managed by the higher levels
99 * invoking this function.
101 * The caller may choose to let this function poll Openstack for completion of the
102 * stack creation, or may handle polling itself via separate calls to query the status.
103 * In either case, a StackInfo object will be returned containing the current status.
104 * When polling is enabled, a status of CREATED is expected. When not polling, a
105 * status of BUILDING is expected.
107 * An error will be thrown if the requested Stack already exists in the specified
110 * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
111 * parameters for createStack. If environment is non-null, it will be added to the stack.
112 * The nested templates and get_file entries both end up being added to the "files" on the
113 * stack. We must combine them before we add them to the stack if they're both non-null.
115 * @param cloudSiteId The cloud (may be a region) in which to create the stack
116 * @param cloudOwner the cloud owner of the cloud site in which to create the stack
117 * @param tenantId The Openstack ID of the tenant in which to create the Stack
118 * @param stackName The name of the stack to create
119 * @param heatTemplate The Heat template
120 * @param stackInputs A map of key/value inputs
121 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
122 * @param environment An optional yaml-format string to specify environmental parameters
123 * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
125 * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
126 * @param backout Do not delete stack on create Failure - defaulted to True
127 * @return A StackInfo object
128 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
131 @SuppressWarnings("unchecked")
133 public StackInfo createStack (String cloudSiteId,
138 Map <String, ?> stackInputs,
139 boolean pollForCompletion,
142 Map <String, Object> files,
143 Map <String, Object> heatFiles,
144 boolean backout) throws MsoException {
146 logger.trace("Started MsoMulticloudUtils.createStack");
148 // Get the directives, if present.
149 String oofDirectives = "{}";
150 String sdncDirectives = "{}";
151 String genericVnfId = "";
152 String vfModuleId = "";
153 String templateType = "";
155 for (String key: MULTICLOUD_INPUTS) {
156 if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
157 if (key == OOF_DIRECTIVES) {
158 oofDirectives = (String) stackInputs.get(key);
160 if (key == SDNC_DIRECTIVES) {
161 sdncDirectives = (String) stackInputs.get(key);
163 if (key == TEMPLATE_TYPE) {
164 templateType = (String) stackInputs.get(key);
166 if (logger.isDebugEnabled()) {
167 logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
169 stackInputs.remove(key);
173 if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
174 vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
176 if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
177 genericVnfId = (String) stackInputs.get(VNF_ID);
180 // create the multicloud payload
181 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
183 MulticloudRequest multicloudRequest= new MulticloudRequest();
185 multicloudRequest.setGenericVnfId(genericVnfId);
186 multicloudRequest.setVfModuleId(vfModuleId);
187 multicloudRequest.setTemplateType(templateType);
188 multicloudRequest.setTemplateData(stack);
189 multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives));
190 multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives));
191 if (logger.isDebugEnabled()) {
192 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
195 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, null);
196 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
198 if (multicloudClient == null) {
199 MsoOpenstackException me = new MsoOpenstackException(0, "", "Multicloud client could not be initialized");
200 me.addContext(CREATE_STACK);
204 Response response = multicloudClient.post(multicloudRequest);
206 MulticloudCreateResponse multicloudResponseBody = null;
207 if (response.hasEntity()) {
208 multicloudResponseBody = getCreateBody((java.io.InputStream) response.getEntity());
210 if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
211 String canonicalName = stackName + "/";
212 if (multicloudResponseBody != null) {
213 canonicalName = canonicalName + multicloudResponseBody.getWorkloadId();
215 if (logger.isDebugEnabled()) {
216 logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
218 return getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion, timeoutMinutes, backout);
220 StringBuilder stackErrorStatusReason = new StringBuilder(response.getStatusInfo().getReasonPhrase());
221 if (null != multicloudResponseBody) {
222 stackErrorStatusReason.append(multicloudResponseBody.toString());
224 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
225 me.addContext(CREATE_STACK);
230 public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
231 String tenantId, String stackName) throws MsoException {
232 logger.debug("MsoHeatUtils.queryStackForOutputs)");
233 StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
234 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
237 return heatStack.getOutputs();
241 * Query for a single stack (by ID) in a tenant. This call will always return a
242 * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
243 * returned - containing only the stack name and a status of NOTFOUND.
245 * @param tenantId The Openstack ID of the tenant in which to query
246 * @param cloudSiteId The cloud identifier (may be a region) in which to query
247 * @param cloudOwner cloud owner of the cloud site in which to query
248 * @param stackId The ID of the stack to query
249 * @return A StackInfo object
250 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
253 public StackInfo queryStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
254 if (logger.isDebugEnabled()) {
255 logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
257 String stackName = null;
258 String stackId = null;
259 int offset = instanceId.indexOf('/');
260 if (offset > 0 && offset < (instanceId.length() - 1)) {
261 stackName = instanceId.substring(0, offset);
262 stackId = instanceId.substring(offset + 1);
264 stackName = instanceId;
265 stackId = instanceId;
268 StackInfo returnInfo = new StackInfo();
269 returnInfo.setName(stackName);
271 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
272 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
274 if (multicloudClient != null) {
275 Response response = multicloudClient.get();
276 if (logger.isDebugEnabled()) {
277 logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
280 MulticloudQueryResponse multicloudQueryBody = null;
281 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
282 returnInfo.setStatus(HeatStatus.NOTFOUND);
283 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
284 } else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
285 multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
286 returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
287 returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
288 returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
289 if (logger.isDebugEnabled()) {
290 logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
293 returnInfo.setStatus(HeatStatus.FAILED);
294 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
301 public StackInfo deleteStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
302 if (logger.isDebugEnabled()) {
303 logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
305 String stackName = null;
306 String stackId = null;
307 int offset = instanceId.indexOf('/');
308 if (offset > 0 && offset < (instanceId.length() - 1)) {
309 stackName = instanceId.substring(0, offset);
310 stackId = instanceId.substring(offset + 1);
312 stackName = instanceId;
313 stackId = instanceId;
316 StackInfo returnInfo = new StackInfo();
317 returnInfo.setName(stackName);
318 Response response = null;
320 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
321 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
323 if (multicloudClient != null) {
324 response = multicloudClient.delete();
325 if (logger.isDebugEnabled()) {
326 logger.debug(String.format("Multicloud Delete response is: %s", response.getEntity().toString()));
329 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
330 returnInfo.setStatus(HeatStatus.NOTFOUND);
331 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
332 } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
333 return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId);
335 returnInfo.setStatus(HeatStatus.FAILED);
336 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
340 returnInfo.setStatus(mapResponseToHeatStatus(response));
344 // ---------------------------------------------------------------
345 // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
347 private HeatStatus getHeatStatus(String workloadStatus) {
348 if (workloadStatus.length() == 0) return HeatStatus.INIT;
349 if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
350 if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
351 if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
352 if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
353 if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
354 if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
355 if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
356 if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
357 if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
358 return HeatStatus.UNKNOWN;
361 private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
362 return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId, false, 0, false);
365 private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
366 StackInfo stackInfo = new StackInfo();
368 // If client has requested a final response, poll for stack completion
369 if (pollForCompletion) {
370 // Set a time limit on overall polling.
371 // Use the resource (template) timeout for Openstack (expressed in minutes)
372 // and add one poll interval to give Openstack a chance to fail on its own.s
374 int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
375 int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
376 // New 1610 - poll on delete if we rollback - use same values for now
377 int deletePollInterval = createPollInterval;
378 int deletePollTimeout = pollTimeout;
379 boolean createTimedOut = false;
380 StringBuilder stackErrorStatusReason = new StringBuilder("");
381 logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
385 stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
386 logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
388 if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
389 // Stack creation is still running.
390 // Sleep and try again unless timeout has been reached
391 if (pollTimeout <= 0) {
392 // Note that this should not occur, since there is a timeout specified
393 // in the Openstack (multicloud?) call.
394 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(), "Create stack timeout"));
395 createTimedOut = true;
399 sleep(createPollInterval * 1000L);
401 pollTimeout -= createPollInterval;
402 logger.debug("pollTimeout remaining: " + pollTimeout);
404 //save off the status & reason msg before we attempt delete
405 stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
408 } catch (MsoException me) {
409 // Cannot query the stack status. Something is wrong.
410 // Try to roll back the stack
412 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack, stack deletion suppressed"));
415 logger.debug("Create Stack error - unable to query for stack status - attempting to delete stack: " + instanceId + " - This will likely fail and/or we won't be able to query to see if delete worked");
416 StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
417 // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
418 // get another one, n'est-ce pas?
419 boolean deleted = false;
422 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
423 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
424 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
425 if (deletePollTimeout <= 0) {
426 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
427 queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
428 "Rollback: DELETE stack timeout"));
431 sleep(deletePollInterval * 1000L);
432 deletePollTimeout -= deletePollInterval;
434 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
435 logger.debug("DELETE_COMPLETE for " + instanceId);
439 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
442 } catch (Exception e3) {
443 // Just log this one. We will report the original exception.
444 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e3, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack on error on query"));
447 } catch (Exception e2) {
448 // Just log this one. We will report the original exception.
449 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack"));
453 // Propagate the original exception from Stack Query.
454 me.addContext (CREATE_STACK);
459 if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
460 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error: Polling complete with non-success status: "
461 + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
463 // Rollback the stack creation, since it is in an indeterminate state.
465 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion suppressed"));
470 logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
471 logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
472 StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
473 boolean deleted = false;
476 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
477 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
478 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
479 if (deletePollTimeout <= 0) {
480 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
481 queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
482 "Rollback: DELETE stack timeout"));
485 sleep(deletePollInterval * 1000L);
486 deletePollTimeout -= deletePollInterval;
488 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
489 logger.debug("DELETE_COMPLETE for " + instanceId);
493 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
494 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion FAILED", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion FAILED"));
495 logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
498 } catch (MsoException me2) {
499 // Just log this one. We will report the original exception.
500 logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
501 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
504 StringBuilder errorContextMessage;
505 if (createTimedOut) {
506 errorContextMessage = new StringBuilder("Stack Creation Timeout");
508 errorContextMessage = stackErrorStatusReason;
511 errorContextMessage.append(" - stack successfully deleted");
513 errorContextMessage.append(" - encountered an error trying to delete the stack");
515 } catch (MsoException e2) {
516 // shouldn't happen - but handle
517 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack: rolling back stack"));
520 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
521 me.addContext(CREATE_STACK);
525 // Get initial status, since it will have been null after the create.
526 stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
527 logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
532 private HeatStatus mapResponseToHeatStatus(Response response) {
533 if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
534 return HeatStatus.CREATED;
535 } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
536 return HeatStatus.CREATED;
537 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
538 return HeatStatus.CREATED;
539 } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
540 return HeatStatus.FAILED;
541 } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
542 return HeatStatus.FAILED;
543 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
544 return HeatStatus.NOTFOUND;
545 } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
546 return HeatStatus.FAILED;
548 return HeatStatus.UNKNOWN;
552 private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
553 Scanner scanner = new Scanner(in);
554 scanner.useDelimiter("\\Z");
556 if (scanner.hasNext()) {
557 body = scanner.next();
562 return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
563 } catch (Exception e) {
564 logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
569 private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
570 Scanner scanner = new Scanner(in);
571 scanner.useDelimiter("\\Z");
573 if (scanner.hasNext()) {
574 body = scanner.next();
579 return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
580 } catch (Exception e) {
581 logger.debug("Exception retrieving multicloud workload query response body " + e);
586 private String getMulticloudEndpoint(String cloudSiteId, String cloudOwner, String workloadId) throws MsoCloudSiteNotFound {
588 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
589 String endpoint = cloudSite.getIdentityService().getIdentityUrl();
591 if (workloadId != null) {
592 if (logger.isDebugEnabled()) {
593 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
595 return String.format("%s/%s", endpoint, workloadId);
597 if (logger.isDebugEnabled()) {
598 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
604 private RestClient getMulticloudClient(String endpoint) {
605 RestClient client = null;
607 client = httpClientFactory.newJsonClient(
609 TargetEntity.MULTICLOUD);
610 } catch (MalformedURLException e) {
611 logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
612 } catch (IllegalArgumentException e) {
613 logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
614 } catch (UriBuilderException e) {
615 logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
620 private JsonNode getDirectiveNode(String directives) throws MsoException {
622 return JSON_MAPPER.readTree(directives);
623 } catch (Exception e) {
624 logger.error(String.format("%s %s %s %s %d %s",
625 MessageEnum.RA_CREATE_STACK_ERR.toString(),
626 "Create Stack: " + e, "", "",
627 ErrorCode.BusinessProcesssError.getValue(),
628 "Exception in Create Stack: Invalid JSON format of directives" + directives));
629 MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
630 me.addContext(CREATE_STACK);
636 * VduPlugin interface for instantiate function.
638 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
639 * and then invoke the existing function.
642 public VduInstance instantiateVdu (
645 Map<String,Object> inputs,
646 VduModelInfo vduModel,
647 boolean rollbackOnFailure)
650 String cloudSiteId = cloudInfo.getCloudSiteId();
651 String cloudOwner = cloudInfo.getCloudOwner();
652 String tenantId = cloudInfo.getTenantId();
654 // Translate the VDU ModelInformation structure to that which is needed for
655 // creating the Heat stack. Loop through the artifacts, looking specifically
656 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
657 // be attached as a FILE.
658 String heatTemplate = null;
659 Map<String,Object> nestedTemplates = new HashMap<>();
660 Map<String,Object> files = new HashMap<>();
661 String heatEnvironment = null;
663 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
664 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
665 heatTemplate = new String(vduArtifact.getContent());
667 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
668 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
670 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
671 heatEnvironment = new String(vduArtifact.getContent());
676 StackInfo stackInfo = createStack (cloudSiteId,
682 true, // poll for completion
683 vduModel.getTimeoutMinutes(),
688 // Populate a vduInstance from the StackInfo
689 return stackInfoToVduInstance(stackInfo);
691 catch (Exception e) {
692 throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
698 * VduPlugin interface for query function.
701 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
704 String cloudSiteId = cloudInfo.getCloudSiteId();
705 String cloudOwner = cloudInfo.getCloudOwner();
706 String tenantId = cloudInfo.getTenantId();
709 // Query the Cloudify Deployment object and populate a VduInstance
710 StackInfo stackInfo = queryStack (cloudSiteId, cloudOwner, tenantId, instanceId);
712 return stackInfoToVduInstance(stackInfo);
714 catch (Exception e) {
715 throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
721 * VduPlugin interface for delete function.
724 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
727 String cloudSiteId = cloudInfo.getCloudSiteId();
728 String cloudOwner = cloudInfo.getCloudOwner();
729 String tenantId = cloudInfo.getTenantId();
732 // Delete the Multicloud stack
733 StackInfo stackInfo = deleteStack (cloudSiteId, cloudOwner, tenantId, instanceId);
735 // Populate a VduInstance based on the deleted Cloudify Deployment object
736 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
738 // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
739 vduInstance.getStatus().setState(VduStateType.DELETED);
743 catch (Exception e) {
744 throw new VduException ("Delete VDU Exception", e);
750 * VduPlugin interface for update function.
752 * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
753 * Just return a VduException.
757 public VduInstance updateVdu (
760 Map<String,Object> inputs,
761 VduModelInfo vduModel,
762 boolean rollbackOnFailure)
765 throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
770 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
772 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
774 VduInstance vduInstance = new VduInstance();
776 if (logger.isDebugEnabled()) {
777 logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
779 // The full canonical name as the instance UUID
780 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
781 vduInstance.setVduInstanceName(stackInfo.getName());
783 // Copy inputs and outputs
784 vduInstance.setInputs(stackInfo.getParameters());
785 vduInstance.setOutputs(stackInfo.getOutputs());
787 // Translate the status elements
788 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
793 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
795 VduStatus vduStatus = new VduStatus();
797 // Map the status fields to more generic VduStatus.
798 // There are lots of HeatStatus values, so this is a bit long...
799 HeatStatus heatStatus = stackInfo.getStatus();
800 String statusMessage = stackInfo.getStatusMessage();
801 logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
803 if (logger.isDebugEnabled()) {
804 logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
805 logger.debug(String.format("Stack Status Message: %s", statusMessage));
808 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
809 vduStatus.setState(VduStateType.INSTANTIATING);
810 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
812 else if (heatStatus == HeatStatus.NOTFOUND) {
813 vduStatus.setState(VduStateType.NOTFOUND);
815 else if (heatStatus == HeatStatus.CREATED) {
816 vduStatus.setState(VduStateType.INSTANTIATED);
817 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
819 else if (heatStatus == HeatStatus.UPDATED) {
820 vduStatus.setState(VduStateType.INSTANTIATED);
821 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
823 else if (heatStatus == HeatStatus.UPDATING) {
824 vduStatus.setState(VduStateType.UPDATING);
825 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
827 else if (heatStatus == HeatStatus.DELETING) {
828 vduStatus.setState(VduStateType.DELETING);
829 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
831 else if (heatStatus == HeatStatus.FAILED) {
832 vduStatus.setState(VduStateType.FAILED);
833 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
835 vduStatus.setState(VduStateType.UNKNOWN);