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