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