2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Intel Corp. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.openstack.utils;
23 import java.net.MalformedURLException;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Scanner;
30 import javax.ws.rs.core.UriBuilder;
31 import javax.ws.rs.core.UriBuilderException;
32 import javax.ws.rs.core.Response;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.onap.so.adapters.vdu.CloudInfo;
37 import org.onap.so.adapters.vdu.PluginAction;
38 import org.onap.so.adapters.vdu.VduArtifact;
39 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
40 import org.onap.so.adapters.vdu.VduException;
41 import org.onap.so.adapters.vdu.VduInstance;
42 import org.onap.so.adapters.vdu.VduModelInfo;
43 import org.onap.so.adapters.vdu.VduPlugin;
44 import org.onap.so.adapters.vdu.VduStateType;
45 import org.onap.so.adapters.vdu.VduStatus;
46 import org.onap.so.openstack.beans.HeatStatus;
47 import org.onap.so.openstack.beans.StackInfo;
48 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
49 import org.onap.so.openstack.exceptions.MsoException;
50 import org.onap.so.openstack.exceptions.MsoOpenstackException;
51 import org.onap.so.client.HttpClient;
52 import org.onap.so.client.RestClient;
53 import org.onap.so.db.catalog.beans.CloudSite;
54 import org.onap.so.logger.MessageEnum;
55 import org.onap.so.logger.MsoAlarmLogger;
56 import org.onap.so.logger.MsoLogger;
57 import org.onap.so.utils.TargetEntity;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.core.env.Environment;
60 import org.springframework.http.HttpEntity;
61 import org.springframework.http.HttpHeaders;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Component;
65 import com.fasterxml.jackson.core.JsonProcessingException;
66 import com.fasterxml.jackson.databind.JsonNode;
67 import com.fasterxml.jackson.databind.ObjectMapper;
68 import com.woorea.openstack.heat.model.CreateStackParam;
71 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
73 public static final String OOF_DIRECTIVES = "oof_directives";
74 public static final String SDNC_DIRECTIVES = "sdnc_directives";
75 public static final String GENERIC_VNF_ID = "generic_vnf_id";
76 public static final String VF_MODULE_ID = "vf_module_id";
77 public static final String TEMPLATE_TYPE = "template_type";
78 public static final List<String> MULTICLOUD_INPUTS =
79 Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
81 private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
83 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
86 private Environment environment;
89 /******************************************************************************
91 * Methods (and associated utilities) to implement the VduPlugin interface
93 *******************************************************************************/
96 * Create a new Stack in the specified cloud location and tenant. The Heat template
97 * and parameter map are passed in as arguments, along with the cloud access credentials.
98 * It is expected that parameters have been validated and contain at minimum the required
99 * parameters for the given template with no extra (undefined) parameters..
101 * The Stack name supplied by the caller must be unique in the scope of this tenant.
102 * However, it should also be globally unique, as it will be the identifier for the
103 * resource going forward in Inventory. This latter is managed by the higher levels
104 * invoking this function.
106 * The caller may choose to let this function poll Openstack for completion of the
107 * stack creation, or may handle polling itself via separate calls to query the status.
108 * In either case, a StackInfo object will be returned containing the current status.
109 * When polling is enabled, a status of CREATED is expected. When not polling, a
110 * status of BUILDING is expected.
112 * An error will be thrown if the requested Stack already exists in the specified
115 * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
116 * parameters for createStack. If environment is non-null, it will be added to the stack.
117 * The nested templates and get_file entries both end up being added to the "files" on the
118 * stack. We must combine them before we add them to the stack if they're both non-null.
120 * @param cloudSiteId The cloud (may be a region) in which to create the stack.
121 * @param tenantId The Openstack ID of the tenant in which to create the Stack
122 * @param stackName The name of the stack to create
123 * @param heatTemplate The Heat template
124 * @param stackInputs A map of key/value inputs
125 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
126 * @param environment An optional yaml-format string to specify environmental parameters
127 * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
129 * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
130 * @param backout Do not delete stack on create Failure - defaulted to True
131 * @return A StackInfo object
132 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
135 @SuppressWarnings("unchecked")
137 public StackInfo createStack (String cloudSiteId,
141 Map <String, ?> stackInputs,
142 boolean pollForCompletion,
145 Map <String, Object> files,
146 Map <String, Object> heatFiles,
147 boolean backout) throws MsoException {
149 logger.trace("Started MsoMulticloudUtils.createStack");
151 // Get the directives, if present.
152 String oofDirectives = "";
153 String sdncDirectives = "";
154 String genericVnfId = "";
155 String vfModuleId = "";
156 String templateType = "";
158 for (String key: MULTICLOUD_INPUTS) {
159 if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
160 if (key == OOF_DIRECTIVES) {
161 oofDirectives = (String) stackInputs.get(key);
163 if (key == SDNC_DIRECTIVES) {
164 sdncDirectives = (String) stackInputs.get(key);
166 if (key == TEMPLATE_TYPE) {
167 templateType = (String) stackInputs.get(key);
169 if (logger.isDebugEnabled()) {
170 logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
172 stackInputs.remove(key);
176 if (!stackInputs.isEmpty() && stackInputs.containsKey("VF_MODULE_ID")){
177 vfModuleId = (String) stackInputs.get("VF_MODULE_ID");
179 if (!stackInputs.isEmpty() && stackInputs.containsKey("GENERIC_VNF_ID")){
180 genericVnfId = (String) stackInputs.get("GENERIC_VNF_ID");
183 // create the multicloud payload
184 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
186 MulticloudRequest multicloudRequest= new MulticloudRequest();
189 multicloudRequest.setGenericVnfId(genericVnfId);
190 multicloudRequest.setVfModuleId(vfModuleId);
191 multicloudRequest.setOofDirectives(JSON_MAPPER.readTree(oofDirectives));
192 multicloudRequest.setSdncDirectives(JSON_MAPPER.readTree(sdncDirectives));
193 multicloudRequest.setTemplateType(templateType);
194 if (logger.isDebugEnabled()) {
195 logger.debug(String.format("Stack Template Data is: %s", stack.toString().substring(16)));
197 multicloudRequest.setTemplateData(stack);
198 if (logger.isDebugEnabled()) {
199 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
201 } catch (Exception e) {
202 logger.debug("ERROR making multicloud JSON body ", e);
204 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, null);
205 if (logger.isDebugEnabled()) {
206 logger.debug(String.format("Multicloud Endpoint is: %s", multicloudEndpoint));
208 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
210 Response response = multicloudClient.post(multicloudRequest);
212 StackInfo createInfo = new StackInfo();
213 createInfo.setName(stackName);
215 MulticloudCreateResponse multicloudResponseBody = null;
216 if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
217 multicloudResponseBody = getCreateBody((java.io.InputStream)response.getEntity());
218 createInfo.setCanonicalName(stackName + "/" + multicloudResponseBody.getWorkloadId());
219 if (logger.isDebugEnabled()) {
220 logger.debug("Multicloud Create Response Body: " + multicloudResponseBody);
222 return getStackStatus(cloudSiteId, tenantId, createInfo.getCanonicalName(), pollForCompletion, timeoutMinutes, backout);
224 createInfo.setStatus(HeatStatus.FAILED);
225 createInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
231 public Map<String, Object> queryStackForOutputs(String cloudSiteId,
232 String tenantId, String stackName) throws MsoException {
233 logger.debug("MsoHeatUtils.queryStackForOutputs)");
234 StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
235 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
238 return heatStack.getOutputs();
242 * Query for a single stack (by ID) in a tenant. This call will always return a
243 * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
244 * returned - containing only the stack name and a status of NOTFOUND.
246 * @param tenantId The Openstack ID of the tenant in which to query
247 * @param cloudSiteId The cloud identifier (may be a region) 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 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, 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 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, 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, 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 tenantId, String instanceId) throws MsoException {
362 return getStackStatus(cloudSiteId, tenantId, instanceId, false, 0, false);
365 private StackInfo getStackStatus(String cloudSiteId, 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, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError, "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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "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, 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, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
427 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
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("%d %s %s %s %d %s", 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"));
447 } catch (Exception e2) {
448 // Just log this one. We will report the original exception.
449 logger.error(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack error: Polling complete with non-success status: "
461 + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"));
463 // Rollback the stack creation, since it is in an indeterminate state.
465 logger.warn(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion suppressed", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "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, tenantId, instanceId);
473 boolean deleted = false;
476 StackInfo queryInfo = queryStack(cloudSiteId, 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("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
481 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
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("%d %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, stack deletion FAILED", "", "", MsoLogger.ErrorCode.BusinessProcesssError, "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("%d %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", MsoLogger.ErrorCode.BusinessProcesssError, 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("%d %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR, "Create Stack: Nested exception rolling back stack: " + e2, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in Create Stack: rolling back stack"));
520 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
521 me.addContext(CREATE_STACK);
522 alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
526 // Get initial status, since it will have been null after the create.
527 stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
528 logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
533 private HeatStatus mapResponseToHeatStatus(Response response) {
534 if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
535 return HeatStatus.CREATED;
536 } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
537 return HeatStatus.CREATED;
538 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
539 return HeatStatus.CREATED;
540 } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
541 return HeatStatus.FAILED;
542 } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
543 return HeatStatus.FAILED;
544 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
545 return HeatStatus.NOTFOUND;
546 } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
547 return HeatStatus.FAILED;
549 return HeatStatus.UNKNOWN;
553 private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
554 Scanner scanner = new Scanner(in);
555 scanner.useDelimiter("\\Z");
557 if (scanner.hasNext()) {
558 body = scanner.next();
563 return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
564 } catch (Exception e) {
565 logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
570 private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
571 Scanner scanner = new Scanner(in);
572 scanner.useDelimiter("\\Z");
574 if (scanner.hasNext()) {
575 body = scanner.next();
580 return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
581 } catch (Exception e) {
582 logger.debug("Exception retrieving multicloud workload query response body " + e);
587 private String getMulticloudEndpoint(String cloudSiteId, String workloadId) throws MsoCloudSiteNotFound {
589 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
590 String endpoint = cloudSite.getIdentityService().getIdentityUrl();
592 if (workloadId != null) {
593 if (logger.isDebugEnabled()) {
594 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
596 return String.format("%s/%s", endpoint, workloadId);
598 if (logger.isDebugEnabled()) {
599 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
605 private RestClient getMulticloudClient(String endpoint) {
606 RestClient client = null;
608 client = new HttpClient(UriBuilder.fromUri(endpoint).build().toURL(),
609 MediaType.APPLICATION_JSON.toString(), 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()));
621 * VduPlugin interface for instantiate function.
623 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
624 * and then invoke the existing function.
627 public VduInstance instantiateVdu (
630 Map<String,Object> inputs,
631 VduModelInfo vduModel,
632 boolean rollbackOnFailure)
635 String cloudSiteId = cloudInfo.getCloudSiteId();
636 String tenantId = cloudInfo.getTenantId();
638 // Translate the VDU ModelInformation structure to that which is needed for
639 // creating the Heat stack. Loop through the artifacts, looking specifically
640 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
641 // be attached as a FILE.
642 String heatTemplate = null;
643 Map<String,Object> nestedTemplates = new HashMap<>();
644 Map<String,Object> files = new HashMap<>();
645 String heatEnvironment = null;
647 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
648 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
649 heatTemplate = new String(vduArtifact.getContent());
651 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
652 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
654 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
655 heatEnvironment = new String(vduArtifact.getContent());
660 StackInfo stackInfo = createStack (cloudSiteId,
665 true, // poll for completion
666 vduModel.getTimeoutMinutes(),
671 // Populate a vduInstance from the StackInfo
672 return stackInfoToVduInstance(stackInfo);
674 catch (Exception e) {
675 throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
681 * VduPlugin interface for query function.
684 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
687 String cloudSiteId = cloudInfo.getCloudSiteId();
688 String tenantId = cloudInfo.getTenantId();
691 // Query the Cloudify Deployment object and populate a VduInstance
692 StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
694 return stackInfoToVduInstance(stackInfo);
696 catch (Exception e) {
697 throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
703 * VduPlugin interface for delete function.
706 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
709 String cloudSiteId = cloudInfo.getCloudSiteId();
710 String tenantId = cloudInfo.getTenantId();
713 // Delete the Multicloud stack
714 StackInfo stackInfo = deleteStack (cloudSiteId, tenantId, instanceId);
716 // Populate a VduInstance based on the deleted Cloudify Deployment object
717 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
719 // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
720 vduInstance.getStatus().setState(VduStateType.DELETED);
724 catch (Exception e) {
725 throw new VduException ("Delete VDU Exception", e);
731 * VduPlugin interface for update function.
733 * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
734 * Just return a VduException.
738 public VduInstance updateVdu (
741 Map<String,Object> inputs,
742 VduModelInfo vduModel,
743 boolean rollbackOnFailure)
746 throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
751 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
753 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
755 VduInstance vduInstance = new VduInstance();
757 if (logger.isDebugEnabled()) {
758 logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
760 // The full canonical name as the instance UUID
761 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
762 vduInstance.setVduInstanceName(stackInfo.getName());
764 // Copy inputs and outputs
765 vduInstance.setInputs(stackInfo.getParameters());
766 vduInstance.setOutputs(stackInfo.getOutputs());
768 // Translate the status elements
769 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
774 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
776 VduStatus vduStatus = new VduStatus();
778 // Map the status fields to more generic VduStatus.
779 // There are lots of HeatStatus values, so this is a bit long...
780 HeatStatus heatStatus = stackInfo.getStatus();
781 String statusMessage = stackInfo.getStatusMessage();
782 logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
784 if (logger.isDebugEnabled()) {
785 logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
786 logger.debug(String.format("Stack Status Message: %s", statusMessage));
789 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
790 vduStatus.setState(VduStateType.INSTANTIATING);
791 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
793 else if (heatStatus == HeatStatus.NOTFOUND) {
794 vduStatus.setState(VduStateType.NOTFOUND);
796 else if (heatStatus == HeatStatus.CREATED) {
797 vduStatus.setState(VduStateType.INSTANTIATED);
798 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
800 else if (heatStatus == HeatStatus.UPDATED) {
801 vduStatus.setState(VduStateType.INSTANTIATED);
802 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
804 else if (heatStatus == HeatStatus.UPDATING) {
805 vduStatus.setState(VduStateType.UPDATING);
806 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
808 else if (heatStatus == HeatStatus.DELETING) {
809 vduStatus.setState(VduStateType.DELETING);
810 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
812 else if (heatStatus == HeatStatus.FAILED) {
813 vduStatus.setState(VduStateType.FAILED);
814 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
816 vduStatus.setState(VduStateType.UNKNOWN);