2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 Intel Corp. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.so.openstack.utils;
25 import com.fasterxml.jackson.databind.JsonNode;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.woorea.openstack.heat.model.CreateStackParam;
28 import java.net.MalformedURLException;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.Scanner;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.UriBuilder;
37 import javax.ws.rs.core.UriBuilderException;
38 import org.onap.so.adapters.vdu.CloudInfo;
39 import org.onap.so.adapters.vdu.PluginAction;
40 import org.onap.so.adapters.vdu.VduArtifact;
41 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
42 import org.onap.so.adapters.vdu.VduException;
43 import org.onap.so.adapters.vdu.VduInstance;
44 import org.onap.so.adapters.vdu.VduModelInfo;
45 import org.onap.so.adapters.vdu.VduPlugin;
46 import org.onap.so.adapters.vdu.VduStateType;
47 import org.onap.so.adapters.vdu.VduStatus;
48 import org.onap.so.client.HttpClientFactory;
49 import org.onap.so.client.RestClient;
50 import org.onap.so.logger.ErrorCode;
51 import org.onap.so.logger.MessageEnum;
52 import org.onap.so.openstack.beans.HeatStatus;
53 import org.onap.so.openstack.beans.StackInfo;
54 import org.onap.so.openstack.exceptions.MsoAdapterException;
55 import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
56 import org.onap.so.openstack.exceptions.MsoException;
57 import org.onap.so.openstack.exceptions.MsoOpenstackException;
58 import org.onap.so.utils.TargetEntity;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.core.env.Environment;
63 import org.springframework.stereotype.Component;
66 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{
68 public static final String OOF_DIRECTIVES = "oof_directives";
69 public static final String SDNC_DIRECTIVES = "sdnc_directives";
70 public static final String USER_DIRECTIVES = "user_directives";
71 public static final String VNF_ID = "vnf_id";
72 public static final String VF_MODULE_ID = "vf_module_id";
73 public static final String TEMPLATE_TYPE = "template_type";
74 public static final String MULTICLOUD_QUERY_BODY_NULL = "multicloudQueryBody is null";
75 public static final List<String> MULTICLOUD_INPUTS =
76 Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, USER_DIRECTIVES, TEMPLATE_TYPE);
78 private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class);
80 private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
81 private static final Integer DEFAULT_MSB_PORT = 80;
82 private static final String DEFAULT_MSB_IP = "127.0.0.1";
83 private static final String ONAP_IP = "ONAP_IP";
84 private final HttpClientFactory httpClientFactory = new HttpClientFactory();
87 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 cloudOwner the cloud owner of the cloud site 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 VduModelInfo vduModel,
144 Map <String, ?> stackInputs,
145 boolean pollForCompletion,
148 Map <String, Object> files,
149 Map <String, Object> heatFiles,
150 boolean backout) throws MsoException {
152 logger.trace("Started MsoMulticloudUtils.createStack");
154 // Get the directives, if present.
155 String oofDirectives = "{}";
156 String sdncDirectives = "{}";
157 String userDirectives = "{}";
158 String genericVnfId = "";
159 String vfModuleId = "";
160 String templateType = "";
162 for (String key: MULTICLOUD_INPUTS) {
163 if (!stackInputs.isEmpty() && stackInputs.containsKey(key)) {
164 if (key == OOF_DIRECTIVES) {
165 oofDirectives = (String) stackInputs.get(key);
167 if (key == SDNC_DIRECTIVES) {
168 sdncDirectives = (String) stackInputs.get(key);
170 if (key == USER_DIRECTIVES) {
171 sdncDirectives = (String) stackInputs.get(key);
173 if (key == TEMPLATE_TYPE) {
174 templateType = (String) stackInputs.get(key);
176 if (logger.isDebugEnabled()) {
177 logger.debug(String.format("Found %s: %s", key, stackInputs.get(key)));
179 stackInputs.remove(key);
183 if (!stackInputs.isEmpty() && stackInputs.containsKey(VF_MODULE_ID)){
184 vfModuleId = (String) stackInputs.get(VF_MODULE_ID);
186 if (!stackInputs.isEmpty() && stackInputs.containsKey(VNF_ID)){
187 genericVnfId = (String) stackInputs.get(VNF_ID);
190 // create the multicloud payload
191 CreateStackParam stack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles);
193 MulticloudRequest multicloudRequest= new MulticloudRequest();
195 multicloudRequest.setGenericVnfId(genericVnfId);
196 multicloudRequest.setVfModuleId(vfModuleId);
197 multicloudRequest.setVfModuleModelInvariantId(vduModel.getModelInvariantUUID());
198 multicloudRequest.setVfModuleModelVersionId(vduModel.getModelUUID());
199 multicloudRequest.setVfModuleModelCustomizationId(vduModel.getModelCustomizationUUID());
200 multicloudRequest.setTemplateType(templateType);
201 multicloudRequest.setTemplateData(stack);
202 multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives));
203 multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives));
204 multicloudRequest.setUserDirectives(getDirectiveNode(userDirectives));
205 if (logger.isDebugEnabled()) {
206 logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString()));
209 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, null);
210 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
212 if (multicloudClient == null) {
213 MsoOpenstackException me = new MsoOpenstackException(0, "", "Multicloud client could not be initialized");
214 me.addContext(CREATE_STACK);
218 Response response = multicloudClient.post(multicloudRequest);
220 MulticloudCreateResponse multicloudResponseBody = null;
221 if (response.hasEntity()) {
222 multicloudResponseBody = getCreateBody((java.io.InputStream) response.getEntity());
224 if (response.getStatus() == Response.Status.CREATED.getStatusCode() && response.hasEntity()) {
225 String canonicalName = stackName + "/";
226 if (multicloudResponseBody != null) {
227 canonicalName = canonicalName + multicloudResponseBody.getWorkloadId();
229 if (logger.isDebugEnabled()) {
230 logger.debug("Multicloud Create Response Body: {}", multicloudResponseBody);
232 return getStackStatus(cloudSiteId, cloudOwner, tenantId, canonicalName, pollForCompletion, timeoutMinutes, backout);
234 StringBuilder stackErrorStatusReason = new StringBuilder(response.getStatusInfo().getReasonPhrase());
235 if (null != multicloudResponseBody) {
236 stackErrorStatusReason.append(multicloudResponseBody.toString());
238 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
239 me.addContext(CREATE_STACK);
244 public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner,
245 String tenantId, String stackName) throws MsoException {
246 logger.debug("MsoHeatUtils.queryStackForOutputs)");
247 StackInfo heatStack = this.queryStack(cloudSiteId, cloudOwner, tenantId, stackName);
248 if (heatStack == null || heatStack.getStatus() == HeatStatus.NOTFOUND) {
251 return heatStack.getOutputs();
255 * Query for a single stack (by ID) in a tenant. This call will always return a
256 * StackInfo object. If the stack does not exist, an "empty" StackInfo will be
257 * returned - containing only the stack name and a status of NOTFOUND.
259 * @param tenantId The Openstack ID of the tenant in which to query
260 * @param cloudSiteId The cloud identifier (may be a region) in which to query
261 * @param cloudOwner cloud owner of the cloud site in which to query
262 * @param stackId The ID of the stack to query
263 * @return A StackInfo object
264 * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception.
267 public StackInfo queryStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
268 if (logger.isDebugEnabled()) {
269 logger.debug (String.format("Query multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
271 String stackName = null;
272 String stackId = null;
273 int offset = instanceId.indexOf('/');
274 if (offset > 0 && offset < (instanceId.length() - 1)) {
275 stackName = instanceId.substring(0, offset);
276 stackId = instanceId.substring(offset + 1);
278 stackName = instanceId;
279 stackId = instanceId;
282 StackInfo returnInfo = new StackInfo();
283 returnInfo.setName(stackName);
285 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
286 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
288 if (multicloudClient != null) {
289 Response response = multicloudClient.get();
290 if (logger.isDebugEnabled()) {
291 logger.debug (String.format("Mulicloud GET Response: %s", response.toString()));
294 MulticloudQueryResponse multicloudQueryBody = null;
295 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
296 returnInfo.setStatus(HeatStatus.NOTFOUND);
297 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
298 } else if (response.getStatus() == Response.Status.OK.getStatusCode() && response.hasEntity()) {
299 multicloudQueryBody = getQueryBody((java.io.InputStream)response.getEntity());
300 if (multicloudQueryBody != null) {
301 returnInfo.setCanonicalName(stackName + "/" + multicloudQueryBody.getWorkloadId());
302 returnInfo.setStatus(getHeatStatus(multicloudQueryBody.getWorkloadStatus()));
303 returnInfo.setStatusMessage(multicloudQueryBody.getWorkloadStatus());
304 if (logger.isDebugEnabled()) {
305 logger.debug("Multicloud Create Response Body: " + multicloudQueryBody.toString());
308 returnInfo.setStatus(HeatStatus.FAILED);
309 returnInfo.setStatusMessage(MULTICLOUD_QUERY_BODY_NULL);
312 returnInfo.setStatus(HeatStatus.FAILED);
313 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
320 public StackInfo deleteStack (String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
321 if (logger.isDebugEnabled()) {
322 logger.debug (String.format("Delete multicloud HEAT stack: %s in tenant %s", instanceId, tenantId));
324 String stackName = null;
325 String stackId = null;
326 int offset = instanceId.indexOf('/');
327 if (offset > 0 && offset < (instanceId.length() - 1)) {
328 stackName = instanceId.substring(0, offset);
329 stackId = instanceId.substring(offset + 1);
331 stackName = instanceId;
332 stackId = instanceId;
335 StackInfo returnInfo = new StackInfo();
336 returnInfo.setName(stackName);
337 Response response = null;
339 String multicloudEndpoint = getMulticloudEndpoint(cloudSiteId, cloudOwner, stackId);
340 RestClient multicloudClient = getMulticloudClient(multicloudEndpoint);
342 if (multicloudClient != null) {
343 response = multicloudClient.delete();
344 if (logger.isDebugEnabled()) {
345 logger.debug(String.format("Multicloud Delete response is: %s", response.getEntity().toString()));
348 if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
349 returnInfo.setStatus(HeatStatus.NOTFOUND);
350 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
351 } else if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode()) {
352 return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId);
354 returnInfo.setStatus(HeatStatus.FAILED);
355 returnInfo.setStatusMessage(response.getStatusInfo().getReasonPhrase());
359 returnInfo.setStatus(mapResponseToHeatStatus(response));
363 // ---------------------------------------------------------------
364 // PRIVATE FUNCTIONS FOR USE WITHIN THIS CLASS
366 private HeatStatus getHeatStatus(String workloadStatus) {
367 if (workloadStatus.length() == 0) return HeatStatus.INIT;
368 if ("CREATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.BUILDING;
369 if ("CREATE_COMPLETE".equals(workloadStatus)) return HeatStatus.CREATED;
370 if ("CREATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
371 if ("DELETE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.DELETING;
372 if ("DELETE_COMPLETE".equals(workloadStatus)) return HeatStatus.NOTFOUND;
373 if ("DELETE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
374 if ("UPDATE_IN_PROGRESS".equals(workloadStatus)) return HeatStatus.UPDATING;
375 if ("UPDATE_FAILED".equals(workloadStatus)) return HeatStatus.FAILED;
376 if ("UPDATE_COMPLETE".equals(workloadStatus)) return HeatStatus.UPDATED;
377 return HeatStatus.UNKNOWN;
380 private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId) throws MsoException {
381 return getStackStatus(cloudSiteId, cloudOwner, tenantId, instanceId, false, 0, false);
384 private StackInfo getStackStatus(String cloudSiteId, String cloudOwner, String tenantId, String instanceId, boolean pollForCompletion, int timeoutMinutes, boolean backout) throws MsoException {
385 StackInfo stackInfo = new StackInfo();
387 // If client has requested a final response, poll for stack completion
388 if (pollForCompletion) {
389 // Set a time limit on overall polling.
390 // Use the resource (template) timeout for Openstack (expressed in minutes)
391 // and add one poll interval to give Openstack a chance to fail on its own.s
393 int createPollInterval = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, createPollIntervalDefault));
394 int pollTimeout = (timeoutMinutes * 60) + createPollInterval;
395 // New 1610 - poll on delete if we rollback - use same values for now
396 int deletePollInterval = createPollInterval;
397 int deletePollTimeout = pollTimeout;
398 boolean createTimedOut = false;
399 StringBuilder stackErrorStatusReason = new StringBuilder("");
400 logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
404 stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
405 logger.debug (stackInfo.getStatus() + " (" + instanceId + ")");
407 if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
408 // Stack creation is still running.
409 // Sleep and try again unless timeout has been reached
410 if (pollTimeout <= 0) {
411 // Note that this should not occur, since there is a timeout specified
412 // in the Openstack (multicloud?) call.
413 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId, stackInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(), "Create stack timeout"));
414 createTimedOut = true;
418 sleep(createPollInterval * 1000L);
420 pollTimeout -= createPollInterval;
421 logger.debug("pollTimeout remaining: " + pollTimeout);
423 //save off the status & reason msg before we attempt delete
424 stackErrorStatusReason.append("Stack error (" + stackInfo.getStatus() + "): " + stackInfo.getStatusMessage());
427 } catch (MsoException me) {
428 // Cannot query the stack status. Something is wrong.
429 // Try to roll back the stack
431 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack, stack deletion suppressed"));
434 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");
435 StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
436 // this may be a waste of time - if we just got an exception trying to query the stack - we'll just
437 // get another one, n'est-ce pas?
438 boolean deleted = false;
441 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
442 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
443 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
444 if (deletePollTimeout <= 0) {
445 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
446 queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
447 "Rollback: DELETE stack timeout"));
450 sleep(deletePollInterval * 1000L);
451 deletePollTimeout -= deletePollInterval;
453 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
454 logger.debug("DELETE_COMPLETE for " + instanceId);
458 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
461 } catch (Exception e3) {
462 // Just log this one. We will report the original exception.
463 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e3, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack on error on query"));
466 } catch (Exception e2) {
467 // Just log this one. We will report the original exception.
468 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack: Nested exception rolling back stack"));
472 // Propagate the original exception from Stack Query.
473 me.addContext (CREATE_STACK);
478 if (!HeatStatus.CREATED.equals(stackInfo.getStatus())) {
479 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack error: Polling complete with non-success status: "
480 + stackInfo.getStatus () + ", " + stackInfo.getStatusMessage(), "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error"));
482 // Rollback the stack creation, since it is in an indeterminate state.
484 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion suppressed", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion suppressed"));
489 logger.debug("Create Stack errored - attempting to DELETE stack: " + instanceId);
490 logger.debug("deletePollInterval=" + deletePollInterval + ", deletePollTimeout=" + deletePollTimeout);
491 StackInfo deleteInfo = deleteStack(cloudSiteId, cloudOwner, tenantId, instanceId);
492 boolean deleted = false;
495 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
496 logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
497 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
498 if (deletePollTimeout <= 0) {
499 logger.error(String.format("%s %s %s %s %s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_TIMEOUT.toString(), cloudOwner, cloudSiteId, tenantId, instanceId,
500 queryInfo.getStatus(), "", "", ErrorCode.AvailabilityError.getValue(),
501 "Rollback: DELETE stack timeout"));
504 sleep(deletePollInterval * 1000L);
505 deletePollTimeout -= deletePollInterval;
507 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())){
508 logger.debug("DELETE_COMPLETE for " + instanceId);
512 //got a status other than DELETE_IN_PROGRESS or DELETE_COMPLETE - so break and evaluate
513 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, stack deletion FAILED", "", "", ErrorCode.BusinessProcesssError.getValue(), "Create Stack error, stack deletion FAILED"));
514 logger.debug("Stack deletion FAILED on a rollback of a create - " + instanceId + ", status=" + queryInfo.getStatus() + ", reason=" + queryInfo.getStatusMessage());
517 } catch (MsoException me2) {
518 // Just log this one. We will report the original exception.
519 logger.debug("Exception thrown trying to delete " + instanceId + " on a create->rollback: " + me2.getContextMessage(), me2);
520 logger.warn(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack errored, then stack deletion FAILED - exception thrown", "", "", ErrorCode.BusinessProcesssError.getValue(), me2.getContextMessage()));
523 StringBuilder errorContextMessage;
524 if (createTimedOut) {
525 errorContextMessage = new StringBuilder("Stack Creation Timeout");
527 errorContextMessage = stackErrorStatusReason;
530 errorContextMessage.append(" - stack successfully deleted");
532 errorContextMessage.append(" - encountered an error trying to delete the stack");
534 } catch (MsoException e2) {
535 // shouldn't happen - but handle
536 logger.error(String.format("%s %s %s %s %d %s", MessageEnum.RA_CREATE_STACK_ERR.toString(), "Create Stack: Nested exception rolling back stack: " + e2, "", "", ErrorCode.BusinessProcesssError.getValue(), "Exception in Create Stack: rolling back stack"));
539 MsoOpenstackException me = new MsoOpenstackException(0, "", stackErrorStatusReason.toString());
540 me.addContext(CREATE_STACK);
544 // Get initial status, since it will have been null after the create.
545 stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
546 logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
551 private HeatStatus mapResponseToHeatStatus(Response response) {
552 if (response == null) {
553 return HeatStatus.FAILED;
554 } else if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
555 return HeatStatus.CREATED;
556 } else if (response.getStatusInfo().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
557 return HeatStatus.CREATED;
558 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NO_CONTENT.getStatusCode()) {
559 return HeatStatus.CREATED;
560 } else if (response.getStatusInfo().getStatusCode() == Response.Status.BAD_REQUEST.getStatusCode()) {
561 return HeatStatus.FAILED;
562 } else if (response.getStatusInfo().getStatusCode() == Response.Status.UNAUTHORIZED.getStatusCode()) {
563 return HeatStatus.FAILED;
564 } else if (response.getStatusInfo().getStatusCode() == Response.Status.NOT_FOUND.getStatusCode()) {
565 return HeatStatus.NOTFOUND;
566 } else if (response.getStatusInfo().getStatusCode() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
567 return HeatStatus.FAILED;
569 return HeatStatus.UNKNOWN;
573 private MulticloudCreateResponse getCreateBody(java.io.InputStream in) {
574 Scanner scanner = new Scanner(in);
575 scanner.useDelimiter("\\Z");
577 if (scanner.hasNext()) {
578 body = scanner.next();
583 return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
584 } catch (Exception e) {
585 logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
590 private MulticloudQueryResponse getQueryBody(java.io.InputStream in) {
591 Scanner scanner = new Scanner(in);
592 scanner.useDelimiter("\\Z");
594 if (scanner.hasNext()) {
595 body = scanner.next();
600 return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
601 } catch (Exception e) {
602 logger.debug("Exception retrieving multicloud workload query response body " + e);
607 private String getMulticloudEndpoint(String cloudSiteId, String cloudOwner, String workloadId) throws MsoCloudSiteNotFound {
608 String msbIp = System.getenv().get(ONAP_IP);
609 if (null == msbIp || msbIp.isEmpty()) {
610 msbIp = environment.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
612 Integer msbPort = environment.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
614 String path = "/api/multicloud/v1/" + cloudOwner + "/" + cloudSiteId + "/infra_workload";
616 String endpoint = UriBuilder.fromPath(path).host(msbIp).port(msbPort).scheme("http").build().toString();
617 if (workloadId != null) {
618 if (logger.isDebugEnabled()) {
619 logger.debug(String.format("Multicloud Endpoint is: %s/%s", endpoint, workloadId));
621 return String.format("%s/%s", endpoint, workloadId);
623 if (logger.isDebugEnabled()) {
624 logger.debug(String.format("Multicloud Endpoint is: %s", endpoint));
630 private RestClient getMulticloudClient(String endpoint) {
631 RestClient client = null;
633 client = httpClientFactory.newJsonClient(
635 TargetEntity.MULTICLOUD);
636 } catch (MalformedURLException e) {
637 logger.debug(String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
638 } catch (IllegalArgumentException e) {
639 logger.debug(String.format("Encountered illegal argument getting multicloud rest client %s",e.getMessage()));
640 } catch (UriBuilderException e) {
641 logger.debug(String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
646 private JsonNode getDirectiveNode(String directives) throws MsoException {
648 return JSON_MAPPER.readTree(directives);
649 } catch (Exception e) {
650 logger.error(String.format("%s %s %s %s %d %s",
651 MessageEnum.RA_CREATE_STACK_ERR.toString(),
652 "Create Stack: " + e, "", "",
653 ErrorCode.BusinessProcesssError.getValue(),
654 "Exception in Create Stack: Invalid JSON format of directives" + directives));
655 MsoException me = new MsoAdapterException("Invalid JSON format of directives parameter: " + directives);
656 me.addContext(CREATE_STACK);
662 * VduPlugin interface for instantiate function.
664 * Translate the VduPlugin parameters to the corresponding 'createStack' parameters,
665 * and then invoke the existing function.
668 public VduInstance instantiateVdu (
671 Map<String,Object> inputs,
672 VduModelInfo vduModel,
673 boolean rollbackOnFailure)
676 String cloudSiteId = cloudInfo.getCloudSiteId();
677 String cloudOwner = cloudInfo.getCloudOwner();
678 String tenantId = cloudInfo.getTenantId();
680 // Translate the VDU ModelInformation structure to that which is needed for
681 // creating the Heat stack. Loop through the artifacts, looking specifically
682 // for MAIN_TEMPLATE and ENVIRONMENT. Any other artifact will
683 // be attached as a FILE.
684 String heatTemplate = null;
685 Map<String,Object> nestedTemplates = new HashMap<>();
686 Map<String,Object> files = new HashMap<>();
687 String heatEnvironment = null;
689 for (VduArtifact vduArtifact: vduModel.getArtifacts()) {
690 if (vduArtifact.getType() == ArtifactType.MAIN_TEMPLATE) {
691 heatTemplate = new String(vduArtifact.getContent());
693 else if (vduArtifact.getType() == ArtifactType.NESTED_TEMPLATE) {
694 nestedTemplates.put(vduArtifact.getName(), new String(vduArtifact.getContent()));
696 else if (vduArtifact.getType() == ArtifactType.ENVIRONMENT) {
697 heatEnvironment = new String(vduArtifact.getContent());
702 StackInfo stackInfo = createStack (cloudSiteId,
709 true, // poll for completion
710 vduModel.getTimeoutMinutes(),
715 // Populate a vduInstance from the StackInfo
716 return stackInfoToVduInstance(stackInfo);
718 catch (Exception e) {
719 throw new VduException ("MsoMulticloudUtils (instantiateVDU): createStack Exception", e);
725 * VduPlugin interface for query function.
728 public VduInstance queryVdu (CloudInfo cloudInfo, String instanceId)
731 String cloudSiteId = cloudInfo.getCloudSiteId();
732 String cloudOwner = cloudInfo.getCloudOwner();
733 String tenantId = cloudInfo.getTenantId();
736 // Query the Cloudify Deployment object and populate a VduInstance
737 StackInfo stackInfo = queryStack (cloudSiteId, cloudOwner, tenantId, instanceId);
739 return stackInfoToVduInstance(stackInfo);
741 catch (Exception e) {
742 throw new VduException ("MsoMulticloudUtils (queryVdu): queryStack Exception ", e);
748 * VduPlugin interface for delete function.
751 public VduInstance deleteVdu (CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
754 String cloudSiteId = cloudInfo.getCloudSiteId();
755 String cloudOwner = cloudInfo.getCloudOwner();
756 String tenantId = cloudInfo.getTenantId();
759 // Delete the Multicloud stack
760 StackInfo stackInfo = deleteStack (cloudSiteId, cloudOwner, tenantId, instanceId);
762 // Populate a VduInstance based on the deleted Cloudify Deployment object
763 VduInstance vduInstance = stackInfoToVduInstance(stackInfo);
765 // Override return state to DELETED (MulticloudUtils sets to NOTFOUND)
766 vduInstance.getStatus().setState(VduStateType.DELETED);
770 catch (Exception e) {
771 throw new VduException ("Delete VDU Exception", e);
777 * VduPlugin interface for update function.
779 * Update is currently not supported in the MsoMulticloudUtils implementation of VduPlugin.
780 * Just return a VduException.
784 public VduInstance updateVdu (
787 Map<String,Object> inputs,
788 VduModelInfo vduModel,
789 boolean rollbackOnFailure)
792 throw new VduException ("MsoMulticloudUtils: updateVdu interface not supported");
797 * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object
799 protected VduInstance stackInfoToVduInstance (StackInfo stackInfo)
801 VduInstance vduInstance = new VduInstance();
803 if (logger.isDebugEnabled()) {
804 logger.debug(String.format("StackInfo to convert: %s", stackInfo.getParameters().toString()));
806 // The full canonical name as the instance UUID
807 vduInstance.setVduInstanceId(stackInfo.getCanonicalName());
808 vduInstance.setVduInstanceName(stackInfo.getName());
810 // Copy inputs and outputs
811 vduInstance.setInputs(stackInfo.getParameters());
812 vduInstance.setOutputs(stackInfo.getOutputs());
814 // Translate the status elements
815 vduInstance.setStatus(stackStatusToVduStatus (stackInfo));
820 private VduStatus stackStatusToVduStatus (StackInfo stackInfo)
822 VduStatus vduStatus = new VduStatus();
824 // Map the status fields to more generic VduStatus.
825 // There are lots of HeatStatus values, so this is a bit long...
826 HeatStatus heatStatus = stackInfo.getStatus();
827 String statusMessage = stackInfo.getStatusMessage();
828 logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
830 if (logger.isDebugEnabled()) {
831 logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
832 logger.debug(String.format("Stack Status Message: %s", statusMessage));
835 if (heatStatus == HeatStatus.INIT || heatStatus == HeatStatus.BUILDING) {
836 vduStatus.setState(VduStateType.INSTANTIATING);
837 vduStatus.setLastAction((new PluginAction ("create", "in_progress", statusMessage)));
839 else if (heatStatus == HeatStatus.NOTFOUND) {
840 vduStatus.setState(VduStateType.NOTFOUND);
842 else if (heatStatus == HeatStatus.CREATED) {
843 vduStatus.setState(VduStateType.INSTANTIATED);
844 vduStatus.setLastAction((new PluginAction ("create", "complete", statusMessage)));
846 else if (heatStatus == HeatStatus.UPDATED) {
847 vduStatus.setState(VduStateType.INSTANTIATED);
848 vduStatus.setLastAction((new PluginAction ("update", "complete", statusMessage)));
850 else if (heatStatus == HeatStatus.UPDATING) {
851 vduStatus.setState(VduStateType.UPDATING);
852 vduStatus.setLastAction((new PluginAction ("update", "in_progress", statusMessage)));
854 else if (heatStatus == HeatStatus.DELETING) {
855 vduStatus.setState(VduStateType.DELETING);
856 vduStatus.setLastAction((new PluginAction ("delete", "in_progress", statusMessage)));
858 else if (heatStatus == HeatStatus.FAILED) {
859 vduStatus.setState(VduStateType.FAILED);
860 vduStatus.setErrorMessage(stackInfo.getStatusMessage());
862 vduStatus.setState(VduStateType.UNKNOWN);