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.MsoLogger;
56 import org.onap.so.utils.TargetEntity;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.core.env.Environment;
59 import org.springframework.http.HttpEntity;
60 import org.springframework.http.HttpHeaders;
61 import org.springframework.http.MediaType;
62 import org.springframework.stereotype.Component;
64 import com.fasterxml.jackson.core.JsonProcessingException;
65 import com.fasterxml.jackson.databind.JsonNode;
66 import com.fasterxml.jackson.databind.ObjectMapper;
67 import com.woorea.openstack.heat.model.CreateStackParam;
70 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
72 public static final String OOF_DIRECTIVES = "oof_directives";
73 public static final String SDNC_DIRECTIVES = "sdnc_directives";
74 public static final String GENERIC_VNF_ID = "generic_vnf_id";
75 public static final String VF_MODULE_ID = "vf_module_id";
76 public static final String TEMPLATE_TYPE = "template_type";
77 public static final List<String> MULTICLOUD_INPUTS =
78 Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
80 private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
82 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
85 private Environment environment;
88 /******************************************************************************
90 * Methods (and associated utilities) to implement the VduPlugin interface
92 *******************************************************************************/
95 * Create a new Stack in the specified cloud location and tenant. The Heat template
96 * and parameter map are passed in as arguments, along with the cloud access credentials.
97 * It is expected that parameters have been validated and contain at minimum the required
98 * parameters for the given template with no extra (undefined) parameters..
100 * The Stack name supplied by the caller must be unique in the scope of this tenant.
101 * However, it should also be globally unique, as it will be the identifier for the
102 * resource going forward in Inventory. This latter is managed by the higher levels
103 * invoking this function.
105 * The caller may choose to let this function poll Openstack for completion of the
106 * stack creation, or may handle polling itself via separate calls to query the status.
107 * In either case, a StackInfo object will be returned containing the current status.
108 * When polling is enabled, a status of CREATED is expected. When not polling, a
109 * status of BUILDING is expected.
111 * An error will be thrown if the requested Stack already exists in the specified
114 * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
115 * parameters for createStack. If environment is non-null, it will be added to the stack.
116 * The nested templates and get_file entries both end up being added to the "files" on the
117 * stack. We must combine them before we add them to the stack if they're both non-null.
119 * @param cloudSiteId The cloud (may be a region) in which to create the stack.
120 * @param tenantId The Openstack ID of the tenant in which to create the Stack
121 * @param stackName The name of the stack to create
122 * @param heatTemplate The Heat template
123 * @param stackInputs A map of key/value inputs
124 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
125 * @param environment An optional yaml-format string to specify environmental parameters
126 * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
128 * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
129 * @param backout Do not delete stack on create Failure - defaulted to True
130 * @return A StackInfo object
131 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
134 @SuppressWarnings("unchecked")
136 public StackInfo createStack (String cloudSiteId,
140 Map <String, ?> stackInputs,
141 boolean pollForCompletion,
144 Map <String, Object> files,
145 Map <String, Object> heatFiles,
146 boolean backout) throws MsoException {
148 logger.trace("Started MsoMulticloudUtils.createStack");
150 // Get the directives, if present.
151 String oofDirectives = "";
152 String sdncDirectives = "";
153 String genericVnfId = "";
154 String vfModuleId = "";
155 String templateType = "";
157 for (String key: MULTICLOUD_INPUTS) {
158 if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
159 if (key == OOF_DIRECTIVES) {
160 oofDirectives = (String) stackInputs.get(key);
162 if (key == SDNC_DIRECTIVES) {
163 sdncDirectives = (String) stackInputs.get(key);
165 if (key == TEMPLATE_TYPE) {
166 templateType = (String) stackInputs.get(key);
168 if (logger.isDebugEnabled()) {
169 logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
171 stackInputs.remove(key);
175 if (!stackInputs.isEmpty() && stackInputs.containsKey("VF_MODULE_ID")){
176 vfModuleId = (String) stackInputs.get("VF_MODULE_ID");
178 if (!stackInputs.isEmpty() && stackInputs.containsKey("GENERIC_VNF_ID")){
179 genericVnfId = (String) stackInputs.get("GENERIC_VNF_ID");
182 // create the multicloud payload
183 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
185 MulticloudRequest multicloudRequest= new MulticloudRequest();
188 multicloudRequest.setGenericVnfId(genericVnfId);
189 multicloudRequest.setVfModuleId(vfModuleId);
190 multicloudRequest.setOofDirectives(JSON_MAPPER.readTree(oofDirectives));
191 multicloudRequest.setSdncDirectives(JSON_MAPPER.readTree(sdncDirectives));
192 multicloudRequest.setTemplateType(templateType);
193 if (logger.isDebugEnabled()) {
194 logger.debug(String.format("Stack Template Data is: %s", stack.toString().substring(16)));
196 multicloudRequest.setTemplateData(stack);
197 if (logger.isDebugEnabled()) {
198 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
200 } catch (Exception e) {
201 logger.debug("ERROR making multicloud JSON body ", e);
203 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, null);
204 if (logger.isDebugEnabled()) {
205 logger.debug(String.format("Multicloud Endpoint is: %s", multicloudEndpoint));
207 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
209 Response response = multicloudClient.post(multicloudRequest);
211 StackInfo createInfo = new StackInfo();
212 createInfo.setName(stackName);
214 MulticloudCreateResponse multicloudResponseBody = null;
215 if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
216 multicloudResponseBody = getCreateBody((java.io.InputStream)response.getEntity());
217 createInfo.setCanonicalName(stackName + "/" + multicloudResponseBody.getWorkloadId());
218 if (logger.isDebugEnabled()) {
219 logger.debug("Multicloud Create Response Body: " + multicloudResponseBody);
221 return getStackStatus(cloudSiteId, tenantId, createInfo.getCanonicalName(), pollForCompletion, timeoutMinutes, backout);
223 createInfo.setStatus(HeatStatus.FAILED);
224 createInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
230 public Map<String, Object> queryStackForOutputs(String cloudSiteId,
231 String tenantId, String stackName) throws MsoException {
232 logger.debug("MsoHeatUtils.queryStackForOutputs)");
233 StackInfo heatStack = this.queryStack(cloudSiteId, 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 stackId The ID of the stack to query
248 * @return A StackInfo object
249 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
252 public StackInfo queryStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
253 if (logger.isDebugEnabled()) {
254 logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
256 String stackName = null;
257 String stackId = null;
258 int offset = instanceId.indexOf('/');
259 if (offset > 0 && offset < (instanceId.length() - 1)) {
260 stackName = instanceId.substring(0, offset);
261 stackId = instanceId.substring(offset + 1);
263 stackName = instanceId;
264 stackId = instanceId;
267 StackInfo returnInfo = new StackInfo();
268 returnInfo.setName(stackName);
270 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
271 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
273 if (multicloudClient != null) {
274 Response response = multicloudClient.get();
275 if (logger.isDebugEnabled()) {
276 logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
279 MulticloudQueryResponse multicloudQueryBody = null;
280 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
281 returnInfo.setStatus(HeatStatus.NOTFOUND);
282 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
283 } else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
284 multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
285 returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
286 returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
287 returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
288 if (logger.isDebugEnabled()) {
289 logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
292 returnInfo.setStatus(HeatStatus.FAILED);
293 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
300 public StackInfo deleteStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
301 if (logger.isDebugEnabled()) {
302 logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
304 String stackName = null;
305 String stackId = null;
306 int offset = instanceId.indexOf('/');
307 if (offset > 0 && offset < (instanceId.length() - 1)) {
308 stackName = instanceId.substring(0, offset);
309 stackId = instanceId.substring(offset + 1);
311 stackName = instanceId;
312 stackId = instanceId;
315 StackInfo returnInfo = new StackInfo();
316 returnInfo.setName(stackName);
317 Response response = null;
319 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
320 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
322 if (multicloudClient != null) {
323 response = multicloudClient.delete();
324 if (logger.isDebugEnabled()) {
325 logger.debug(String.format("Multicloud Delete response is: %s", response.getEntity().toString()));
328 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
329 returnInfo.setStatus(HeatStatus.NOTFOUND);
330 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
331 } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
332 return getStackStatus(cloudSiteId, tenantId, instanceId);
334 returnInfo.setStatus(HeatStatus.FAILED);
335 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
339 returnInfo.setStatus(mapResponseToHeatStatus(response));
343 // ---------------------------------------------------------------
344 // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
346 private HeatStatus getHeatStatus(String workloadStatus) {
347 if (workloadStatus.length() == 0) return HeatStatus.INIT;
348 if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
349 if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
350 if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
351 if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
352 if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
353 if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
354 if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
355 if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
356 if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
357 return HeatStatus.UNKNOWN;
360 private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId) throws MsoException {
361 return getStackStatus(cloudSiteId, tenantId, instanceId, false, 0, false);
364 private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
365 StackInfo stackInfo = new StackInfo();
367 // If client has requested a final response, poll for stack completion
368 if (pollForCompletion) {
369 // Set a time limit on overall polling.
370 // Use the resource (template) timeout for Openstack (expressed in minutes)
371 // and add one poll interval to give Openstack a chance to fail on its own.s
373 int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
374 int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
375 // New 1610 - poll on delete if we rollback - use same values for now
376 int deletePollInterval = createPollInterval;
377 int deletePollTimeout = pollTimeout;
378 boolean createTimedOut = false;
379 StringBuilder stackErrorStatusReason = new StringBuilder("");
380 logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
384 stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
385 logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
387 if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
388 // Stack creation is still running.
389 // Sleep and try again unless timeout has been reached
390 if (pollTimeout <= 0) {
391 // Note that this should not occur, since there is a timeout specified
392 // in the Openstack (multicloud?) call.
393 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"));
394 createTimedOut = true;
398 sleep(createPollInterval * 1000L);
400 pollTimeout -= createPollInterval;
401 logger.debug("pollTimeout remaining: " + pollTimeout);
403 //save off the status & reason msg before we attempt delete
404 stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
407 } catch (MsoException me) {
408 // Cannot query the stack status. Something is wrong.
409 // Try to roll back the stack
411 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"));
414 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");
415 StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
416 // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
417 // get another one, n'est-ce pas?
418 boolean deleted = false;
421 StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
422 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
423 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
424 if (deletePollTimeout <= 0) {
425 logger.error(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
426 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
427 "Rollback: DELETE stack timeout"));
430 sleep(deletePollInterval * 1000L);
431 deletePollTimeout -= deletePollInterval;
433 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
434 logger.debug("DELETE_COMPLETE for " + instanceId);
438 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
441 } catch (Exception e3) {
442 // Just log this one. We will report the original exception.
443 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"));
446 } catch (Exception e2) {
447 // Just log this one. We will report the original exception.
448 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"));
452 // Propagate the original exception from Stack Query.
453 me.addContext (CREATE_STACK);
458 if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
459 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: "
460 + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"));
462 // Rollback the stack creation, since it is in an indeterminate state.
464 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"));
469 logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
470 logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
471 StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
472 boolean deleted = false;
475 StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
476 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
477 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
478 if (deletePollTimeout <= 0) {
479 logger.error(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
480 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
481 "Rollback: DELETE stack timeout"));
484 sleep(deletePollInterval * 1000L);
485 deletePollTimeout -= deletePollInterval;
487 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
488 logger.debug("DELETE_COMPLETE for " + instanceId);
492 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
493 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"));
494 logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
497 } catch (MsoException me2) {
498 // Just log this one. We will report the original exception.
499 logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
500 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()));
503 StringBuilder errorContextMessage;
504 if (createTimedOut) {
505 errorContextMessage = new StringBuilder("Stack Creation Timeout");
507 errorContextMessage = stackErrorStatusReason;
510 errorContextMessage.append(" - stack successfully deleted");
512 errorContextMessage.append(" - encountered an error trying to delete the stack");
514 } catch (MsoException e2) {
515 // shouldn't happen - but handle
516 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"));
519 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
520 me.addContext(CREATE_STACK);
524 // Get initial status, since it will have been null after the create.
525 stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
526 logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
531 private HeatStatus mapResponseToHeatStatus(Response response) {
532 if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
533 return HeatStatus.CREATED;
534 } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
535 return HeatStatus.CREATED;
536 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
537 return HeatStatus.CREATED;
538 } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
539 return HeatStatus.FAILED;
540 } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
541 return HeatStatus.FAILED;
542 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
543 return HeatStatus.NOTFOUND;
544 } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
545 return HeatStatus.FAILED;
547 return HeatStatus.UNKNOWN;
551 private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
552 Scanner scanner = new Scanner(in);
553 scanner.useDelimiter("\\Z");
555 if (scanner.hasNext()) {
556 body = scanner.next();
561 return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
562 } catch (Exception e) {
563 logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
568 private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
569 Scanner scanner = new Scanner(in);
570 scanner.useDelimiter("\\Z");
572 if (scanner.hasNext()) {
573 body = scanner.next();
578 return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
579 } catch (Exception e) {
580 logger.debug("Exception retrieving multicloud workload query response body " + e);
585 private String getMulticloudEndpoint(String cloudSiteId, String workloadId) throws MsoCloudSiteNotFound {
587 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
588 String endpoint = cloudSite.getIdentityService().getIdentityUrl();
590 if (workloadId != null) {
591 if (logger.isDebugEnabled()) {
592 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
594 return String.format("%s/%s", endpoint, workloadId);
596 if (logger.isDebugEnabled()) {
597 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
603 private RestClient getMulticloudClient(String endpoint) {
604 RestClient client = null;
606 client = new HttpClient(UriBuilder.fromUri(endpoint).build().toURL(),
607 MediaType.APPLICATION_JSON.toString(), TargetEntity.MULTICLOUD);
608 } catch (MalformedURLException e) {
609 logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
610 } catch (IllegalArgumentException e) {
611 logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
612 } catch (UriBuilderException e) {
613 logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
619 * VduPlugin interface for instantiate function.
621 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
622 * and then invoke the existing function.
625 public VduInstance instantiateVdu (
628 Map<String,Object> inputs,
629 VduModelInfo vduModel,
630 boolean rollbackOnFailure)
633 String cloudSiteId = cloudInfo.getCloudSiteId();
634 String tenantId = cloudInfo.getTenantId();
636 // Translate the VDU ModelInformation structure to that which is needed for
637 // creating the Heat stack. Loop through the artifacts, looking specifically
638 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
639 // be attached as a FILE.
640 String heatTemplate = null;
641 Map<String,Object> nestedTemplates = new HashMap<>();
642 Map<String,Object> files = new HashMap<>();
643 String heatEnvironment = null;
645 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
646 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
647 heatTemplate = new String(vduArtifact.getContent());
649 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
650 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
652 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
653 heatEnvironment = new String(vduArtifact.getContent());
658 StackInfo stackInfo = createStack (cloudSiteId,
663 true, // poll for completion
664 vduModel.getTimeoutMinutes(),
669 // Populate a vduInstance from the StackInfo
670 return stackInfoToVduInstance(stackInfo);
672 catch (Exception e) {
673 throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
679 * VduPlugin interface for query function.
682 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
685 String cloudSiteId = cloudInfo.getCloudSiteId();
686 String tenantId = cloudInfo.getTenantId();
689 // Query the Cloudify Deployment object and populate a VduInstance
690 StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
692 return stackInfoToVduInstance(stackInfo);
694 catch (Exception e) {
695 throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
701 * VduPlugin interface for delete function.
704 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
707 String cloudSiteId = cloudInfo.getCloudSiteId();
708 String tenantId = cloudInfo.getTenantId();
711 // Delete the Multicloud stack
712 StackInfo stackInfo = deleteStack (cloudSiteId, tenantId, instanceId);
714 // Populate a VduInstance based on the deleted Cloudify Deployment object
715 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
717 // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
718 vduInstance.getStatus().setState(VduStateType.DELETED);
722 catch (Exception e) {
723 throw new VduException ("Delete VDU Exception", e);
729 * VduPlugin interface for update function.
731 * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
732 * Just return a VduException.
736 public VduInstance updateVdu (
739 Map<String,Object> inputs,
740 VduModelInfo vduModel,
741 boolean rollbackOnFailure)
744 throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
749 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
751 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
753 VduInstance vduInstance = new VduInstance();
755 if (logger.isDebugEnabled()) {
756 logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
758 // The full canonical name as the instance UUID
759 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
760 vduInstance.setVduInstanceName(stackInfo.getName());
762 // Copy inputs and outputs
763 vduInstance.setInputs(stackInfo.getParameters());
764 vduInstance.setOutputs(stackInfo.getOutputs());
766 // Translate the status elements
767 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
772 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
774 VduStatus vduStatus = new VduStatus();
776 // Map the status fields to more generic VduStatus.
777 // There are lots of HeatStatus values, so this is a bit long...
778 HeatStatus heatStatus = stackInfo.getStatus();
779 String statusMessage = stackInfo.getStatusMessage();
780 logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
782 if (logger.isDebugEnabled()) {
783 logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
784 logger.debug(String.format("Stack Status Message: %s", statusMessage));
787 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
788 vduStatus.setState(VduStateType.INSTANTIATING);
789 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
791 else if (heatStatus == HeatStatus.NOTFOUND) {
792 vduStatus.setState(VduStateType.NOTFOUND);
794 else if (heatStatus == HeatStatus.CREATED) {
795 vduStatus.setState(VduStateType.INSTANTIATED);
796 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
798 else if (heatStatus == HeatStatus.UPDATED) {
799 vduStatus.setState(VduStateType.INSTANTIATED);
800 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
802 else if (heatStatus == HeatStatus.UPDATING) {
803 vduStatus.setState(VduStateType.UPDATING);
804 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
806 else if (heatStatus == HeatStatus.DELETING) {
807 vduStatus.setState(VduStateType.DELETING);
808 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
810 else if (heatStatus == HeatStatus.FAILED) {
811 vduStatus.setState(VduStateType.FAILED);
812 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
814 vduStatus.setState(VduStateType.UNKNOWN);