b9f477d300974ba5e57f46c1ad9e253f25b45c24
[policy/models.git] / models-interactions / model-actors / actor.sdnr / src / main / java / org / onap / policy / controlloop / actor / sdnr / SdnrActor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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.apache.commons.lang3.tuple.Pair;
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.Operator;
33 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicActor;
34 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator;
35 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicActorParams;
36 import org.onap.policy.controlloop.policy.Policy;
37 import org.onap.policy.controlloop.policy.PolicyResult;
38 import org.onap.policy.sdnr.PciCommonHeader;
39 import org.onap.policy.sdnr.PciRequest;
40 import org.onap.policy.sdnr.PciRequestWrapper;
41 import org.onap.policy.sdnr.PciResponse;
42 import org.onap.policy.sdnr.PciResponseCode;
43 import org.onap.policy.sdnr.PciResponseWrapper;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * SDNR is an unusual actor in that it uses a single, generic operator to initiate all
49  * operation types. The action taken is always the same, only the operation name changes.
50  */
51 public class SdnrActor extends BidirectionalTopicActor<BidirectionalTopicActorParams>  {
52
53     public static final String NAME = "SDNR";
54
55     // TODO old code: remove lines down to **HERE**
56
57     private static final Logger logger = LoggerFactory.getLogger(SdnrActor.class);
58
59     // Strings for targets
60     private static final String TARGET_VNF = "VNF";
61
62     // Strings for recipes
63     private static final String RECIPE_MODIFY = "ModifyConfig";
64
65     /* To be used in future releases when pci ModifyConfig is used */
66     private static final String SDNR_REQUEST_PARAMS = "request-parameters";
67     private static final String SDNR_CONFIG_PARAMS = "configuration-parameters";
68
69     private static final ImmutableList<String> recipes = ImmutableList.of(RECIPE_MODIFY);
70     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
71             .put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
72     private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
73             .put(RECIPE_MODIFY, ImmutableList.of(SDNR_REQUEST_PARAMS, SDNR_CONFIG_PARAMS)).build();
74
75     // **HERE**
76
77     /**
78      * Constructor.
79      */
80     public SdnrActor() {
81         super(NAME, BidirectionalTopicActorParams.class);
82
83         addOperator(new BidirectionalTopicOperator(NAME, SdnrOperation.NAME, this, SdnrOperation.SELECTOR_KEYS,
84                         SdnrOperation::new));
85     }
86
87     @Override
88     public Operator getOperator(String name) {
89         /*
90          * All operations are managed by the same operator, regardless of the name.
91          */
92         return super.getOperator(SdnrOperation.NAME);
93     }
94
95     // TODO old code: remove lines down to **HERE**
96
97     @Override
98     public String actor() {
99         return NAME;
100     }
101
102     @Override
103     public List<String> recipes() {
104         return ImmutableList.copyOf(recipes);
105     }
106
107     @Override
108     public List<String> recipeTargets(String recipe) {
109         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
110     }
111
112     @Override
113     public List<String> recipePayloads(String recipe) {
114         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
115     }
116
117     /**
118      * Constructs an SDNR request conforming to the pci API. The actual request is
119      * constructed and then placed in a wrapper object used to send through DMAAP.
120      *
121      * @param onset
122      *            the event that is reporting the alert for policy to perform an
123      *            action
124      * @param operation
125      *            the control loop operation specifying the actor, operation,
126      *            target, etc.
127      * @param policy
128      *            the policy the was specified from the yaml generated by CLAMP or
129      *            through the Policy GUI/API
130      * @return an SDNR request conforming to the pci API using the DMAAP wrapper
131      */
132
133     public static PciRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
134             Policy policy) {
135
136         /* Construct an SDNR request using pci Model */
137
138         /*
139          * The actual pci request is placed in a wrapper used to send through dmaap. The
140          * current version is 2.0 as of R1.
141          */
142         PciRequestWrapper dmaapRequest = new PciRequestWrapper();
143         dmaapRequest.setVersion("1.0");
144         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
145         dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
146         dmaapRequest.setType("request");
147
148         /* This is the actual request that is placed in the dmaap wrapper. */
149         final PciRequest sdnrRequest = new PciRequest();
150
151         /* The common header is a required field for all SDNR requests. */
152         PciCommonHeader requestCommonHeader = new PciCommonHeader();
153         requestCommonHeader.setRequestId(onset.getRequestId());
154         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
155
156         sdnrRequest.setCommonHeader(requestCommonHeader);
157         sdnrRequest.setPayload(onset.getPayload());
158
159         /*
160          * An action is required for all SDNR requests, this will be the recipe
161          * specified in the policy.
162          */
163         sdnrRequest.setAction(policy.getRecipe());
164
165         /*
166          * Once the pci request is constructed, add it into the body of the dmaap
167          * wrapper.
168          */
169         dmaapRequest.setBody(sdnrRequest);
170         logger.info("SDNR Request to be sent is {}", dmaapRequest);
171
172         /* Return the request to be sent through dmaap. */
173         return dmaapRequest;
174     }
175
176     /**
177      * Parses the operation attempt using the subRequestId of SDNR response.
178      *
179      * @param subRequestId
180      *            the sub id used to send to SDNR, Policy sets this using the
181      *            operation attempt
182      *
183      * @return the current operation attempt
184      */
185     public static Integer parseOperationAttempt(String subRequestId) {
186         Integer operationAttempt;
187         try {
188             operationAttempt = Integer.parseInt(subRequestId);
189         } catch (NumberFormatException e) {
190             logger.debug("A NumberFormatException was thrown in parsing the operation attempt {}", subRequestId);
191             return null;
192         }
193         return operationAttempt;
194     }
195
196     /**
197      * Processes the SDNR pci response sent from SDNR. Determines if the SDNR
198      * operation was successful/unsuccessful and maps this to the corresponding
199      * Policy result.
200      *
201      * @param dmaapResponse
202      *            the dmaap wrapper message that contains the actual SDNR reponse
203      *            inside the body field
204      *
205      * @return an key-value pair that contains the Policy result and SDNR response
206      *         message
207      */
208     public static Pair<PolicyResult, String> processResponse(
209             PciResponseWrapper dmaapResponse) {
210
211         logger.info("SDNR processResponse called : {}", dmaapResponse);
212
213         /* The actual SDNR response is inside the wrapper's body field. */
214         PciResponse sdnrResponse = dmaapResponse.getBody();
215
216         /* The message returned in the SDNR response. */
217         String message;
218
219         /* The Policy result determined from the SDNR Response. */
220         PolicyResult result;
221
222         /*
223          * If there is no status, Policy cannot determine if the request was successful.
224          */
225         if (sdnrResponse.getStatus() == null) {
226             message = "Policy was unable to parse SDN-R response status field (it was null).";
227             return Pair.of(PolicyResult.FAILURE_EXCEPTION, message);
228         }
229
230         /*
231          * If there is no code, Policy cannot determine if the request was successful.
232          */
233         String responseValue = PciResponseCode.toResponseValue(sdnrResponse.getStatus().getCode());
234         if (responseValue == null) {
235             message = "Policy was unable to parse SDN-R response status code field.";
236             return Pair.of(PolicyResult.FAILURE_EXCEPTION, message);
237         }
238         logger.info("SDNR Response Code is {}", responseValue);
239
240         /* Save the SDNR response's message for Policy notification message. */
241         message = sdnrResponse.getStatus().getValue();
242         logger.info("SDNR Response Message is {}", message);
243
244         /*
245          * Response and Payload are just printed and no further action needed in
246          * casablanca release
247          */
248         String rspPayload = sdnrResponse.getPayload();
249         logger.info("SDNR Response Payload is {}", rspPayload);
250
251         /* Maps the SDNR response result to a Policy result. */
252         switch (responseValue) {
253             case PciResponseCode.ACCEPTED:
254                 /* Nothing to do if code is accept, continue processing */
255                 result = null;
256                 break;
257             case PciResponseCode.SUCCESS:
258                 result = PolicyResult.SUCCESS;
259                 break;
260             case PciResponseCode.FAILURE:
261                 result = PolicyResult.FAILURE;
262                 break;
263             case PciResponseCode.REJECT:
264             case PciResponseCode.ERROR:
265             default:
266                 result = PolicyResult.FAILURE_EXCEPTION;
267         }
268         return Pair.of(result, message);
269     }
270
271     /**
272      * Converts the SDNR response to ControlLoopResponse object.
273      *
274      * @param dmaapResponse
275      *            the dmaap wrapper message that contains the actual SDNR reponse
276      *            inside the body field
277      *
278      * @return a ControlLoopResponse object to send to DCAE_CL_RSP topic
279      */
280     public static ControlLoopResponse getControlLoopResponse(PciResponseWrapper dmaapResponse,
281             VirtualControlLoopEvent event) {
282
283         logger.info("SDNR getClosedLoopResponse called : {} {}", dmaapResponse, event);
284
285         /* The actual SDNR response is inside the wrapper's body field. */
286         PciResponse sdnrResponse = dmaapResponse.getBody();
287
288         /* The ControlLoop response determined from the SDNR Response and input event. */
289         ControlLoopResponse clRsp = new ControlLoopResponse();
290         clRsp.setPayload(sdnrResponse.getPayload());
291         clRsp.setFrom(NAME);
292         clRsp.setTarget("DCAE");
293         clRsp.setClosedLoopControlName(event.getClosedLoopControlName());
294         clRsp.setPolicyName(event.getPolicyName());
295         clRsp.setPolicyVersion(event.getPolicyVersion());
296         clRsp.setRequestId(event.getRequestId());
297         clRsp.setVersion(event.getVersion());
298         logger.info("SDNR getClosedLoopResponse clRsp : {}", clRsp);
299
300         return clRsp;
301     }
302
303     // **HERE**
304 }