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