d6ec1d21990e8969237781e0ea4810c44849b0ba
[policy/drools-applications.git] / controlloop / common / actors / actor.sdnr / src / main / java / org / onap / policy / controlloop / actor / sdnr / SdnrActorServiceProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SdnrActorServiceProvider
4  * ================================================================================
5  * Copyright (C) 2018 Wipro Limited Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.sdnr;
22
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
25
26 import java.util.Collections;
27 import java.util.List;
28
29 import org.onap.policy.controlloop.ControlLoopOperation;
30 import org.onap.policy.controlloop.ControlLoopResponse;
31 import org.onap.policy.controlloop.VirtualControlLoopEvent;
32 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
33 import org.onap.policy.controlloop.policy.Policy;
34 import org.onap.policy.controlloop.policy.PolicyResult;
35 import org.onap.policy.sdnr.PciCommonHeader;
36 import org.onap.policy.sdnr.PciRequest;
37 import org.onap.policy.sdnr.PciRequestWrapper;
38 import org.onap.policy.sdnr.PciResponse;
39 import org.onap.policy.sdnr.PciResponseCode;
40 import org.onap.policy.sdnr.PciResponseWrapper;
41
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 public class SdnrActorServiceProvider implements Actor {
46
47     public static class Pair<A, B> {
48         public final A result;
49         public final B message;
50
51         public Pair(A result, B message) {
52             this.result = result;
53             this.message = message;
54         }
55
56         public A getResult() {
57             return this.result;
58         }
59
60         public B getMessage() {
61             return this.message;
62         }
63     }
64
65     private static final Logger logger = LoggerFactory.getLogger(SdnrActorServiceProvider.class);
66
67     // Strings for targets
68     private static final String TARGET_VNF = "VNF";
69
70     // Strings for recipes
71     private static final String RECIPE_MODIFY = "ModifyConfig";
72     private static final String RECIPE_MODIFY_ANR = "ModifyConfigANR";
73
74     /* To be used in future releases when pci ModifyConfig is used */
75     private static final String SDNR_REQUEST_PARAMS = "request-parameters";
76     private static final String SDNR_CONFIG_PARAMS = "configuration-parameters";
77
78     private static final ImmutableList<String> recipes = ImmutableList.of(RECIPE_MODIFY);
79     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
80             .put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
81     private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
82             .put(RECIPE_MODIFY, ImmutableList.of(SDNR_REQUEST_PARAMS, SDNR_CONFIG_PARAMS)).build();
83
84     @Override
85     public String actor() {
86         return "SDNR";
87     }
88
89     @Override
90     public List<String> recipes() {
91         return ImmutableList.copyOf(recipes);
92     }
93
94     @Override
95     public List<String> recipeTargets(String recipe) {
96         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
97     }
98
99     @Override
100     public List<String> recipePayloads(String recipe) {
101         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
102     }
103
104     /**
105      * Constructs an SDNR request conforming to the pci API. The actual request is
106      * constructed and then placed in a wrapper object used to send through DMAAP.
107      *
108      * @param onset
109      *            the event that is reporting the alert for policy to perform an
110      *            action
111      * @param operation
112      *            the control loop operation specifying the actor, operation,
113      *            target, etc.
114      * @param policy
115      *            the policy the was specified from the yaml generated by CLAMP or
116      *            through the Policy GUI/API
117      * @return an SDNR request conforming to the pci API using the DMAAP wrapper
118      */
119
120     public static PciRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
121             Policy policy) {
122
123         /* Construct an SDNR request using pci Model */
124
125         /*
126          * The actual pci request is placed in a wrapper used to send through dmaap. The
127          * current version is 2.0 as of R1.
128          */
129         PciRequestWrapper dmaapRequest = new PciRequestWrapper();
130         dmaapRequest.setVersion("1.0");
131         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
132         dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
133         dmaapRequest.setType("request");
134
135         /* This is the actual request that is placed in the dmaap wrapper. */
136         final PciRequest sdnrRequest = new PciRequest();
137
138         /* The common header is a required field for all SDNR requests. */
139         PciCommonHeader requestCommonHeader = new PciCommonHeader();
140         requestCommonHeader.setRequestId(onset.getRequestId());
141         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
142
143         sdnrRequest.setCommonHeader(requestCommonHeader);
144         sdnrRequest.setPayload(onset.getPayload());
145
146         /*
147          * An action is required for all SDNR requests, this will be the recipe
148          * specified in the policy.
149          */
150         sdnrRequest.setAction(policy.getRecipe());
151
152         /*
153          * Once the pci request is constructed, add it into the body of the dmaap
154          * wrapper.
155          */
156         dmaapRequest.setBody(sdnrRequest);
157         logger.info("SDNR Request to be sent is {}", dmaapRequest);
158
159         /* Return the request to be sent through dmaap. */
160         return dmaapRequest;
161     }
162
163     /**
164      * Parses the operation attempt using the subRequestId of SDNR response.
165      *
166      * @param subRequestId
167      *            the sub id used to send to SDNR, Policy sets this using the
168      *            operation attempt
169      *
170      * @return the current operation attempt
171      */
172     public static Integer parseOperationAttempt(String subRequestId) {
173         Integer operationAttempt;
174         try {
175             operationAttempt = Integer.parseInt(subRequestId);
176         } catch (NumberFormatException e) {
177             logger.debug("A NumberFormatException was thrown in parsing the operation attempt {}", subRequestId);
178             return null;
179         }
180         return operationAttempt;
181     }
182
183     /**
184      * Processes the SDNR pci response sent from SDNR. Determines if the SDNR
185      * operation was successful/unsuccessful and maps this to the corresponding
186      * Policy result.
187      *
188      * @param dmaapResponse
189      *            the dmaap wrapper message that contains the actual SDNR reponse
190      *            inside the body field
191      *
192      * @return an key-value pair that contains the Policy result and SDNR response
193      *         message
194      */
195     public static SdnrActorServiceProvider.Pair<PolicyResult, String> processResponse(
196             PciResponseWrapper dmaapResponse) {
197
198         logger.info("SDNR processResponse called : {}", dmaapResponse);
199
200         /* The actual SDNR response is inside the wrapper's body field. */
201         PciResponse sdnrResponse = dmaapResponse.getBody();
202
203         /* The message returned in the SDNR response. */
204         String message;
205
206         /* The Policy result determined from the SDNR Response. */
207         PolicyResult result;
208
209         /*
210          * If there is no status, Policy cannot determine if the request was successful.
211          */
212         if (sdnrResponse.getStatus() == null) {
213             message = "Policy was unable to parse SDN-R response status field (it was null).";
214             return new SdnrActorServiceProvider.Pair<>(PolicyResult.FAILURE_EXCEPTION, message);
215         }
216
217         /*
218          * If there is no code, Policy cannot determine if the request was successful.
219          */
220         String responseValue = PciResponseCode.toResponseValue(sdnrResponse.getStatus().getCode());
221         if (responseValue == null) {
222             message = "Policy was unable to parse SDN-R response status code field.";
223             return new SdnrActorServiceProvider.Pair<>(PolicyResult.FAILURE_EXCEPTION, message);
224         }
225         logger.info("SDNR Response Code is {}", responseValue);
226
227         /* Save the SDNR response's message for Policy notification message. */
228         message = sdnrResponse.getStatus().getValue();
229         logger.info("SDNR Response Message is {}", message);
230
231         /*
232          * Response and Payload are just printed and no further action needed in
233          * casablanca release
234          */
235         String rspPayload = sdnrResponse.getPayload();
236         logger.info("SDNR Response Payload is {}", rspPayload);
237
238         /* Maps the SDNR response result to a Policy result. */
239         switch (responseValue) {
240             case PciResponseCode.ACCEPTED:
241                 /* Nothing to do if code is accept, continue processing */
242                 result = null;
243                 break;
244             case PciResponseCode.SUCCESS:
245                 result = PolicyResult.SUCCESS;
246                 break;
247             case PciResponseCode.FAILURE:
248                 result = PolicyResult.FAILURE;
249                 break;
250             case PciResponseCode.REJECT:
251             case PciResponseCode.ERROR:
252             default:
253                 result = PolicyResult.FAILURE_EXCEPTION;
254         }
255         return new SdnrActorServiceProvider.Pair<>(result, message);
256     }
257
258     /**
259      * Converts the SDNR response to ControlLoopResponse object.
260      *
261      * @param dmaapResponse
262      *            the dmaap wrapper message that contains the actual SDNR reponse
263      *            inside the body field
264      *
265      * @return a ControlLoopResponse object to send to DCAE_CL_RSP topic
266      */
267     public static ControlLoopResponse getControlLoopResponse(PciResponseWrapper dmaapResponse,
268             VirtualControlLoopEvent event) {
269
270         logger.info("SDNR getClosedLoopResponse called : {} {}", dmaapResponse, event);
271
272         /* The actual SDNR response is inside the wrapper's body field. */
273         PciResponse sdnrResponse = dmaapResponse.getBody();
274
275         /* The ControlLoop response determined from the SDNR Response and input event. */
276         ControlLoopResponse clRsp = new ControlLoopResponse();
277         clRsp.setPayload(sdnrResponse.getPayload());
278         clRsp.setFrom("SDNR");
279         clRsp.setTarget("DCAE");
280         clRsp.setClosedLoopControlName(event.getClosedLoopControlName());
281         clRsp.setPolicyName(event.getPolicyName());
282         clRsp.setPolicyVersion(event.getPolicyVersion());
283         clRsp.setRequestId(event.getRequestId());
284         clRsp.setVersion(event.getVersion());
285         logger.info("SDNR getClosedLoopResponse clRsp : {}", clRsp);
286
287         return clRsp;
288     }
289
290 }