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