Removing Named Query.
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / main / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmActorServiceProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * AppcLcmActorServiceProvider
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications copyright (c) 2018 Nokia
7  * Modifications Copyright (C) 2019 Nordix Foundation.
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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=========================================================
21  */
22
23 package org.onap.policy.controlloop.actor.appclcm;
24
25 import com.google.common.collect.ImmutableList;
26 import com.google.common.collect.ImmutableMap;
27 import java.util.AbstractMap;
28 import java.util.AbstractMap.SimpleEntry;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import org.onap.policy.appclcm.AppcLcmBody;
34 import org.onap.policy.appclcm.AppcLcmCommonHeader;
35 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
36 import org.onap.policy.appclcm.AppcLcmInput;
37 import org.onap.policy.appclcm.AppcLcmOutput;
38 import org.onap.policy.appclcm.AppcLcmResponseCode;
39 import org.onap.policy.controlloop.ControlLoopOperation;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
42 import org.onap.policy.controlloop.policy.Policy;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class AppcLcmActorServiceProvider implements Actor {
48
49     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
50
51     /* To be used in future releases to restart a single vm */
52     private static final String APPC_VM_ID = "vm-id";
53
54     // Strings for targets
55     private static final String TARGET_VM = "VM";
56     private static final String TARGET_VNF = "VNF";
57
58     // Strings for recipes
59     private static final String RECIPE_RESTART = "Restart";
60     private static final String RECIPE_REBUILD = "Rebuild";
61     private static final String RECIPE_MIGRATE = "Migrate";
62     private static final String RECIPE_MODIFY = "ConfigModify";
63
64     /* To be used in future releases when LCM ConfigModify is used */
65     private static final String APPC_REQUEST_PARAMS = "request-parameters";
66     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
67
68     private static final ImmutableList<String> recipes =
69             ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
70     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
71             .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
72             .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
73     private static final ImmutableMap<String, List<String>> payloads =
74             new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
75                     .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
76
77     @Override
78     public String actor() {
79         return "APPC";
80     }
81
82     @Override
83     public List<String> recipes() {
84         return ImmutableList.copyOf(recipes);
85     }
86
87     @Override
88     public List<String> recipeTargets(String recipe) {
89         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
90     }
91
92     @Override
93     public List<String> recipePayloads(String recipe) {
94         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
95     }
96
97
98     /**
99      * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
100      * then placed in a wrapper object used to send through DMAAP.
101      *
102      * @param onset the event that is reporting the alert for policy to perform an action
103      * @param operation the control loop operation specifying the actor, operation, target, etc.
104      * @param policy the policy the was specified from the yaml generated by CLAMP or through the
105      *        Policy GUI/API
106      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
107      */
108     public static AppcLcmDmaapWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
109             Policy policy, String targetVnf) {
110
111         /* Construct an APPC request using LCM Model */
112
113         /*
114          * The actual LCM request is placed in a wrapper used to send through dmaap. The current
115          * version is 2.0 as of R1.
116          */
117         AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
118
119         AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
120         dmaapRequest.setVersion("2.0");
121         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
122         dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
123         dmaapRequest.setType("request");
124
125         /* This is the actual request that is placed in the dmaap wrapper. */
126         final AppcLcmInput appcRequest = new AppcLcmInput();
127
128         /* The common header is a required field for all APPC requests. */
129         AppcLcmCommonHeader requestCommonHeader = new AppcLcmCommonHeader();
130         requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
131         requestCommonHeader.setRequestId(onset.getRequestId());
132         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
133
134         appcRequest.setCommonHeader(requestCommonHeader);
135
136         /*
137          * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
138          * Policy only require a vnf-id.
139          */
140         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
141         requestActionIdentifiers.put("vnf-id", targetVnf);
142
143         appcRequest.setActionIdentifiers(requestActionIdentifiers);
144
145         /*
146          * An action is required for all APPC requests, this will be the recipe specified in the
147          * policy.
148          */
149         appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
150
151         /*
152          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes.
153          * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action
154          * identifiers.
155          */
156         if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
157             appcRequest.setPayload(parsePayload(policy.getPayload()));
158         } else {
159             appcRequest.setPayload(null);
160         }
161
162         /*
163          * The APPC request must be wrapped in an input object.
164          */
165         AppcLcmBody body = new AppcLcmBody();
166         body.setInput(appcRequest);
167
168         /*
169          * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
170          */
171         dmaapRequest.setBody(body);
172
173         /* Return the request to be sent through dmaap. */
174         return dmaapRequest;
175     }
176
177     private static boolean payloadSupplied(Map<String, String> payload) {
178         return payload != null && !payload.isEmpty();
179     }
180
181     private static boolean recipeSupportsPayload(String recipe) {
182         return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
183                 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
184     }
185
186     private static String parsePayload(Map<String, String> payload) {
187         StringBuilder payloadString = new StringBuilder("{");
188         payload
189             .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
190         return payloadString.substring(0, payloadString.length() - 1) + "}";
191     }
192
193     /**
194      * Parses the operation attempt using the subRequestId of APPC response.
195      *
196      * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
197      *        attempt
198      *
199      * @return the current operation attempt
200      */
201     public static Integer parseOperationAttempt(String subRequestId) {
202         Integer operationAttempt;
203         try {
204             operationAttempt = Integer.parseInt(subRequestId);
205         } catch (NumberFormatException e) {
206             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
207             return null;
208         }
209         return operationAttempt;
210     }
211
212     /**
213      * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
214      * successful/unsuccessful and maps this to the corresponding Policy result.
215      *
216      * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
217      *        the body field
218      *
219      * @return an key-value pair that contains the Policy result and APPC response message
220      */
221     public static SimpleEntry<PolicyResult, String> processResponse(AppcLcmDmaapWrapper dmaapResponse) {
222         AppcLcmBody appcBody = dmaapResponse.getBody();
223         if (appcBody == null) {
224             throw new NullPointerException("APPC Body is null");
225         }
226
227         /* The actual APPC response is inside the dmaap wrapper's body.input field. */
228         AppcLcmOutput appcResponse = appcBody.getOutput();
229         if (appcResponse == null) {
230             throw new NullPointerException("APPC Response is null");
231         }
232
233         /* The message returned in the APPC response. */
234         String message;
235
236         /* The Policy result determined from the APPC Response. */
237         PolicyResult result;
238
239         /* If there is no status, Policy cannot determine if the request was successful. */
240         if (appcResponse.getStatus() == null) {
241             message = "Policy was unable to parse APP-C response status field (it was null).";
242             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
243         }
244
245         /* If there is no code, Policy cannot determine if the request was successful. */
246         String responseValue = AppcLcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
247         if (responseValue == null) {
248             message = "Policy was unable to parse APP-C response status code field.";
249             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
250         }
251
252         /* Save the APPC response's message for Policy notification message. */
253         message = appcResponse.getStatus().getMessage();
254
255         /* Maps the APPC response result to a Policy result. */
256         switch (responseValue) {
257             case AppcLcmResponseCode.ACCEPTED:
258                 /* Nothing to do if code is accept, continue processing */
259                 result = null;
260                 break;
261             case AppcLcmResponseCode.SUCCESS:
262                 result = PolicyResult.SUCCESS;
263                 break;
264             case AppcLcmResponseCode.FAILURE:
265                 result = PolicyResult.FAILURE;
266                 break;
267             case AppcLcmResponseCode.REJECT:
268             case AppcLcmResponseCode.ERROR:
269             default:
270                 result = PolicyResult.FAILURE_EXCEPTION;
271         }
272         return new AbstractMap.SimpleEntry<>(result, message);
273     }
274 }