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.MsoAdapterException;
49 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
50 import org.onap.so.openstack.exceptions.MsoException;
51 import org.onap.so.openstack.exceptions.MsoOpenstackException;
52 import org.onap.so.client.HttpClient;
53 import org.onap.so.client.RestClient;
54 import org.onap.so.db.catalog.beans.CloudSite;
55 import org.onap.so.logger.MessageEnum;
56 import org.onap.so.logger.MsoAlarmLogger;
57 import org.onap.so.logger.MsoLogger;
58 import org.onap.so.utils.TargetEntity;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.core.env.Environment;
61 import org.springframework.http.HttpEntity;
62 import org.springframework.http.HttpHeaders;
63 import org.springframework.http.MediaType;
64 import org.springframework.stereotype.Component;
66 import com.fasterxml.jackson.core.JsonProcessingException;
67 import com.fasterxml.jackson.databind.JsonNode;
68 import com.fasterxml.jackson.databind.ObjectMapper;
69 import com.woorea.openstack.heat.model.CreateStackParam;
72 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
74 public static final String OOF_DIRECTIVES = "oof_directives";
75 public static final String SDNC_DIRECTIVES = "sdnc_directives";
76 public static final String VNF_ID = "vnf_id";
77 public static final String VF_MODULE_ID = "vf_module_id";
78 public static final String TEMPLATE_TYPE = "template_type";
79 public static final List<String> MULTICLOUD_INPUTS =
80 Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE);
82 private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
84 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
87 private Environment environment;
90 /******************************************************************************
92 * Methods (and associated utilities) to implement the VduPlugin interface
94 *******************************************************************************/
97 * Create a new Stack in the specified cloud location and tenant. The Heat template
98 * and parameter map are passed in as arguments, along with the cloud access credentials.
99 * It is expected that parameters have been validated and contain at minimum the required
100 * parameters for the given template with no extra (undefined) parameters..
102 * The Stack name supplied by the caller must be unique in the scope of this tenant.
103 * However, it should also be globally unique, as it will be the identifier for the
104 * resource going forward in Inventory. This latter is managed by the higher levels
105 * invoking this function.
107 * The caller may choose to let this function poll Openstack for completion of the
108 * stack creation, or may handle polling itself via separate calls to query the status.
109 * In either case, a StackInfo object will be returned containing the current status.
110 * When polling is enabled, a status of CREATED is expected. When not polling, a
111 * status of BUILDING is expected.
113 * An error will be thrown if the requested Stack already exists in the specified
116 * For 1510 - add "environment", "files" (nested templates), and "heatFiles" (get_files) as
117 * parameters for createStack. If environment is non-null, it will be added to the stack.
118 * The nested templates and get_file entries both end up being added to the "files" on the
119 * stack. We must combine them before we add them to the stack if they're both non-null.
121 * @param cloudSiteId The cloud (may be a region) in which to create the stack.
122 * @param tenantId The Openstack ID of the tenant in which to create the Stack
123 * @param stackName The name of the stack to create
124 * @param heatTemplate The Heat template
125 * @param stackInputs A map of key/value inputs
126 * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
127 * @param environment An optional yaml-format string to specify environmental parameters
128 * @param files a Map<String, Object> that lists the child template IDs (file is the string, object is an int of
130 * @param heatFiles a Map<String, Object> that lists the get_file entries (fileName, fileBody)
131 * @param backout Do not delete stack on create Failure - defaulted to True
132 * @return A StackInfo object
133 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
136 @SuppressWarnings("unchecked")
138 public StackInfo createStack (String cloudSiteId,
142 Map <String, ?> stackInputs,
143 boolean pollForCompletion,
146 Map <String, Object> files,
147 Map <String, Object> heatFiles,
148 boolean backout) throws MsoException {
150 logger.trace("Started MsoMulticloudUtils.createStack");
152 // Get the directives, if present.
153 String oofDirectives = "{}";
154 String sdncDirectives = "{}";
155 String genericVnfId = "";
156 String vfModuleId = "";
157 String templateType = "";
159 for (String key: MULTICLOUD_INPUTS) {
160 if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
161 if (key == OOF_DIRECTIVES) {
162 oofDirectives = (String) stackInputs.get(key);
164 if (key == SDNC_DIRECTIVES) {
165 sdncDirectives = (String) stackInputs.get(key);
167 if (key == TEMPLATE_TYPE) {
168 templateType = (String) stackInputs.get(key);
170 if (logger.isDebugEnabled()) {
171 logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
173 stackInputs.remove(key);
177 if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
178 vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
180 if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
181 genericVnfId = (String) stackInputs.get(VNF_ID);
184 // create the multicloud payload
185 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
187 MulticloudRequest multicloudRequest= new MulticloudRequest();
189 multicloudRequest.setGenericVnfId(genericVnfId);
190 multicloudRequest.setVfModuleId(vfModuleId);
191 multicloudRequest.setTemplateType(templateType);
192 multicloudRequest.setTemplateData(stack);
193 multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives));
194 multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives));
195 if (logger.isDebugEnabled()) {
196 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
199 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, null);
200 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
202 Response response = multicloudClient.post(multicloudRequest);
204 StackInfo createInfo = new StackInfo();
205 createInfo.setName(stackName);
207 MulticloudCreateResponse multicloudResponseBody = null;
208 if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
209 multicloudResponseBody = getCreateBody((java.io.InputStream)response.getEntity());
210 createInfo.setCanonicalName(stackName + "/" + multicloudResponseBody.getWorkloadId());
211 if (logger.isDebugEnabled()) {
212 logger.debug("Multicloud Create Response Body: " + multicloudResponseBody);
214 return getStackStatus(cloudSiteId, tenantId, createInfo.getCanonicalName(), pollForCompletion, timeoutMinutes, backout);
216 createInfo.setStatus(HeatStatus.FAILED);
217 createInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
223 public Map<String, Object> queryStackForOutputs(String cloudSiteId,
224 String tenantId, String stackName) throws MsoException {
225 logger.debug("MsoHeatUtils.queryStackForOutputs)");
226 StackInfo heatStack = this.queryStack(cloudSiteId, tenantId, stackName);
227 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
230 return heatStack.getOutputs();
234 * Query for a single stack (by ID) in a tenant. This call will always return a
235 * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
236 * returned - containing only the stack name and a status of NOTFOUND.
238 * @param tenantId The Openstack ID of the tenant in which to query
239 * @param cloudSiteId The cloud identifier (may be a region) in which to query
240 * @param stackId The ID of the stack to query
241 * @return A StackInfo object
242 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
245 public StackInfo queryStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
246 if (logger.isDebugEnabled()) {
247 logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
249 String stackName = null;
250 String stackId = null;
251 int offset = instanceId.indexOf('/');
252 if (offset > 0 && offset < (instanceId.length() - 1)) {
253 stackName = instanceId.substring(0, offset);
254 stackId = instanceId.substring(offset + 1);
256 stackName = instanceId;
257 stackId = instanceId;
260 StackInfo returnInfo = new StackInfo();
261 returnInfo.setName(stackName);
263 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
264 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
266 if (multicloudClient != null) {
267 Response response = multicloudClient.get();
268 if (logger.isDebugEnabled()) {
269 logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
272 MulticloudQueryResponse multicloudQueryBody = null;
273 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
274 returnInfo.setStatus(HeatStatus.NOTFOUND);
275 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
276 } else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
277 multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
278 returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
279 returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
280 returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
281 if (logger.isDebugEnabled()) {
282 logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
285 returnInfo.setStatus(HeatStatus.FAILED);
286 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
293 public StackInfo deleteStack (String cloudSiteId, String tenantId, String instanceId) throws MsoException {
294 if (logger.isDebugEnabled()) {
295 logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
297 String stackName = null;
298 String stackId = null;
299 int offset = instanceId.indexOf('/');
300 if (offset > 0 && offset < (instanceId.length() - 1)) {
301 stackName = instanceId.substring(0, offset);
302 stackId = instanceId.substring(offset + 1);
304 stackName = instanceId;
305 stackId = instanceId;
308 StackInfo returnInfo = new StackInfo();
309 returnInfo.setName(stackName);
310 Response response = null;
312 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, stackId);
313 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
315 if (multicloudClient != null) {
316 response = multicloudClient.delete();
317 if (logger.isDebugEnabled()) {
318 logger.debug(String.format("Multicloud Delete response is: %s", response.getEntity().toString()));
321 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
322 returnInfo.setStatus(HeatStatus.NOTFOUND);
323 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
324 } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
325 return getStackStatus(cloudSiteId, tenantId, instanceId);
327 returnInfo.setStatus(HeatStatus.FAILED);
328 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
332 returnInfo.setStatus(mapResponseToHeatStatus(response));
336 // ---------------------------------------------------------------
337 // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
339 private HeatStatus getHeatStatus(String workloadStatus) {
340 if (workloadStatus.length() == 0) return HeatStatus.INIT;
341 if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
342 if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
343 if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
344 if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
345 if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
346 if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
347 if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
348 if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
349 if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
350 return HeatStatus.UNKNOWN;
353 private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId) throws MsoException {
354 return getStackStatus(cloudSiteId, tenantId, instanceId, false, 0, false);
357 private StackInfo getStackStatus(String cloudSiteId, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
358 StackInfo stackInfo = new StackInfo();
360 // If client has requested a final response, poll for stack completion
361 if (pollForCompletion) {
362 // Set a time limit on overall polling.
363 // Use the resource (template) timeout for Openstack (expressed in minutes)
364 // and add one poll interval to give Openstack a chance to fail on its own.s
366 int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
367 int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
368 // New 1610 - poll on delete if we rollback - use same values for now
369 int deletePollInterval = createPollInterval;
370 int deletePollTimeout = pollTimeout;
371 boolean createTimedOut = false;
372 StringBuilder stackErrorStatusReason = new StringBuilder("");
373 logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
377 stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
378 logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
380 if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
381 // Stack creation is still running.
382 // Sleep and try again unless timeout has been reached
383 if (pollTimeout <= 0) {
384 // Note that this should not occur, since there is a timeout specified
385 // in the Openstack (multicloud?) call.
386 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"));
387 createTimedOut = true;
391 sleep(createPollInterval * 1000L);
393 pollTimeout -= createPollInterval;
394 logger.debug("pollTimeout remaining: " + pollTimeout);
396 //save off the status & reason msg before we attempt delete
397 stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
400 } catch (MsoException me) {
401 // Cannot query the stack status. Something is wrong.
402 // Try to roll back the stack
404 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"));
407 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");
408 StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
409 // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
410 // get another one, n'est-ce pas?
411 boolean deleted = false;
414 StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
415 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
416 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
417 if (deletePollTimeout <= 0) {
418 logger.error(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
419 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
420 "Rollback: DELETE stack timeout"));
423 sleep(deletePollInterval * 1000L);
424 deletePollTimeout -= deletePollInterval;
426 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
427 logger.debug("DELETE_COMPLETE for " + instanceId);
431 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
434 } catch (Exception e3) {
435 // Just log this one. We will report the original exception.
436 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"));
439 } catch (Exception e2) {
440 // Just log this one. We will report the original exception.
441 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"));
445 // Propagate the original exception from Stack Query.
446 me.addContext (CREATE_STACK);
451 if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
452 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: "
453 + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Create Stack error"));
455 // Rollback the stack creation, since it is in an indeterminate state.
457 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"));
462 logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
463 logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
464 StackInfo deleteInfo = deleteStack(cloudSiteId, tenantId, instanceId);
465 boolean deleted = false;
468 StackInfo queryInfo = queryStack(cloudSiteId, tenantId, instanceId);
469 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
470 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
471 if (deletePollTimeout <= 0) {
472 logger.error(String.format("%d %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT, cloudSiteId, tenantId, instanceId,
473 queryInfo.getStatus(), "", "", MsoLogger.ErrorCode.AvailabilityError,
474 "Rollback: DELETE stack timeout"));
477 sleep(deletePollInterval * 1000L);
478 deletePollTimeout -= deletePollInterval;
480 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
481 logger.debug("DELETE_COMPLETE for " + instanceId);
485 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
486 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"));
487 logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
490 } catch (MsoException me2) {
491 // Just log this one. We will report the original exception.
492 logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
493 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()));
496 StringBuilder errorContextMessage;
497 if (createTimedOut) {
498 errorContextMessage = new StringBuilder("Stack Creation Timeout");
500 errorContextMessage = stackErrorStatusReason;
503 errorContextMessage.append(" - stack successfully deleted");
505 errorContextMessage.append(" - encountered an error trying to delete the stack");
507 } catch (MsoException e2) {
508 // shouldn't happen - but handle
509 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"));
512 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
513 me.addContext(CREATE_STACK);
514 alarmLogger.sendAlarm(HEAT_ERROR, MsoAlarmLogger.CRITICAL, me.getContextMessage());
518 // Get initial status, since it will have been null after the create.
519 stackInfo = queryStack(cloudSiteId, tenantId, instanceId);
520 logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
525 private HeatStatus mapResponseToHeatStatus(Response response) {
526 if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
527 return HeatStatus.CREATED;
528 } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
529 return HeatStatus.CREATED;
530 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
531 return HeatStatus.CREATED;
532 } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
533 return HeatStatus.FAILED;
534 } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
535 return HeatStatus.FAILED;
536 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
537 return HeatStatus.NOTFOUND;
538 } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
539 return HeatStatus.FAILED;
541 return HeatStatus.UNKNOWN;
545 private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
546 Scanner scanner = new Scanner(in);
547 scanner.useDelimiter("\\Z");
549 if (scanner.hasNext()) {
550 body = scanner.next();
555 return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
556 } catch (Exception e) {
557 logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
562 private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
563 Scanner scanner = new Scanner(in);
564 scanner.useDelimiter("\\Z");
566 if (scanner.hasNext()) {
567 body = scanner.next();
572 return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
573 } catch (Exception e) {
574 logger.debug("Exception retrieving multicloud workload query response body " + e);
579 private String getMulticloudEndpoint(String cloudSiteId, String workloadId) throws MsoCloudSiteNotFound {
581 CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId));
582 String endpoint = cloudSite.getIdentityService().getIdentityUrl();
584 if (workloadId != null) {
585 if (logger.isDebugEnabled()) {
586 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
588 return String.format("%s/%s", endpoint, workloadId);
590 if (logger.isDebugEnabled()) {
591 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
597 private RestClient getMulticloudClient(String endpoint) {
598 RestClient client = null;
600 client = new HttpClient(UriBuilder.fromUri(endpoint).build().toURL(),
601 MediaType.APPLICATION_JSON.toString(), TargetEntity.MULTICLOUD);
602 } catch (MalformedURLException e) {
603 logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
604 } catch (IllegalArgumentException e) {
605 logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
606 } catch (UriBuilderException e) {
607 logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
612 private JsonNode getDirectiveNode(String directives) throws MsoException {
614 return JSON_MAPPER.readTree(directives);
615 } catch (Exception e) {
616 logger.error(String.format("%d %s %s %s %d %s",
617 MessageEnum.RA_CREATE_STACK_ERR,
618 "Create Stack: " + e, "", "",
619 MsoLogger.ErrorCode.BusinessProcesssError,
620 "Exception in Create Stack: Invalid JSON format of directives" + directives));
621 MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
622 me.addContext(CREATE_STACK);
628 * VduPlugin interface for instantiate function.
630 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
631 * and then invoke the existing function.
634 public VduInstance instantiateVdu (
637 Map<String,Object> inputs,
638 VduModelInfo vduModel,
639 boolean rollbackOnFailure)
642 String cloudSiteId = cloudInfo.getCloudSiteId();
643 String tenantId = cloudInfo.getTenantId();
645 // Translate the VDU ModelInformation structure to that which is needed for
646 // creating the Heat stack. Loop through the artifacts, looking specifically
647 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
648 // be attached as a FILE.
649 String heatTemplate = null;
650 Map<String,Object> nestedTemplates = new HashMap<>();
651 Map<String,Object> files = new HashMap<>();
652 String heatEnvironment = null;
654 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
655 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
656 heatTemplate = new String(vduArtifact.getContent());
658 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
659 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
661 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
662 heatEnvironment = new String(vduArtifact.getContent());
667 StackInfo stackInfo = createStack (cloudSiteId,
672 true, // poll for completion
673 vduModel.getTimeoutMinutes(),
678 // Populate a vduInstance from the StackInfo
679 return stackInfoToVduInstance(stackInfo);
681 catch (Exception e) {
682 throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
688 * VduPlugin interface for query function.
691 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
694 String cloudSiteId = cloudInfo.getCloudSiteId();
695 String tenantId = cloudInfo.getTenantId();
698 // Query the Cloudify Deployment object and populate a VduInstance
699 StackInfo stackInfo = queryStack (cloudSiteId, tenantId, instanceId);
701 return stackInfoToVduInstance(stackInfo);
703 catch (Exception e) {
704 throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
710 * VduPlugin interface for delete function.
713 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
716 String cloudSiteId = cloudInfo.getCloudSiteId();
717 String tenantId = cloudInfo.getTenantId();
720 // Delete the Multicloud stack
721 StackInfo stackInfo = deleteStack (cloudSiteId, tenantId, instanceId);
723 // Populate a VduInstance based on the deleted Cloudify Deployment object
724 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
726 // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
727 vduInstance.getStatus().setState(VduStateType.DELETED);
731 catch (Exception e) {
732 throw new VduException ("Delete VDU Exception", e);
738 * VduPlugin interface for update function.
740 * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
741 * Just return a VduException.
745 public VduInstance updateVdu (
748 Map<String,Object> inputs,
749 VduModelInfo vduModel,
750 boolean rollbackOnFailure)
753 throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
758 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
760 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
762 VduInstance vduInstance = new VduInstance();
764 if (logger.isDebugEnabled()) {
765 logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
767 // The full canonical name as the instance UUID
768 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
769 vduInstance.setVduInstanceName(stackInfo.getName());
771 // Copy inputs and outputs
772 vduInstance.setInputs(stackInfo.getParameters());
773 vduInstance.setOutputs(stackInfo.getOutputs());
775 // Translate the status elements
776 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
781 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
783 VduStatus vduStatus = new VduStatus();
785 // Map the status fields to more generic VduStatus.
786 // There are lots of HeatStatus values, so this is a bit long...
787 HeatStatus heatStatus = stackInfo.getStatus();
788 String statusMessage = stackInfo.getStatusMessage();
789 logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
791 if (logger.isDebugEnabled()) {
792 logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
793 logger.debug(String.format("Stack Status Message: %s", statusMessage));
796 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
797 vduStatus.setState(VduStateType.INSTANTIATING);
798 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
800 else if (heatStatus == HeatStatus.NOTFOUND) {
801 vduStatus.setState(VduStateType.NOTFOUND);
803 else if (heatStatus == HeatStatus.CREATED) {
804 vduStatus.setState(VduStateType.INSTANTIATED);
805 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
807 else if (heatStatus == HeatStatus.UPDATED) {
808 vduStatus.setState(VduStateType.INSTANTIATED);
809 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
811 else if (heatStatus == HeatStatus.UPDATING) {
812 vduStatus.setState(VduStateType.UPDATING);
813 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
815 else if (heatStatus == HeatStatus.DELETING) {
816 vduStatus.setState(VduStateType.DELETING);
817 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
819 else if (heatStatus == HeatStatus.FAILED) {
820 vduStatus.setState(VduStateType.FAILED);
821 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
823 vduStatus.setState(VduStateType.UNKNOWN);