Include response in OperationOutcome
[policy/models.git] / models-interactions / model-actors / actor.sdnr / src / main / java / org / onap / policy / controlloop / actor / sdnr / SdnrOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SdnrOperation
4  * ================================================================================
5  * Copyright (C) 2020 AT&T 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 java.util.List;
24 import java.util.concurrent.CompletableFuture;
25 import org.onap.policy.controlloop.ControlLoopResponse;
26 import org.onap.policy.controlloop.VirtualControlLoopEvent;
27 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
28 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
29 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
30 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
31 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
32 import org.onap.policy.controlloop.policy.PolicyResult;
33 import org.onap.policy.sdnr.PciBody;
34 import org.onap.policy.sdnr.PciCommonHeader;
35 import org.onap.policy.sdnr.PciMessage;
36 import org.onap.policy.sdnr.PciRequest;
37 import org.onap.policy.sdnr.PciResponse;
38 import org.onap.policy.sdnr.util.StatusCodeEnum;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class SdnrOperation extends BidirectionalTopicOperation<PciMessage, PciMessage> {
43     private static final Logger logger = LoggerFactory.getLogger(SdnrOperation.class);
44
45     /**
46      * Operation name as it should appear within config files.
47      */
48     public static final String NAME = "any";
49
50     /**
51      * Keys used to match the response with the request listener. The sub request ID is a
52      * UUID, so it can be used to uniquely identify the response.
53      * <p/>
54      * Note: if these change, then {@link #getExpectedKeyValues(int, PciMessage)} must be
55      * updated accordingly.
56      */
57     public static final List<SelectorKey> SELECTOR_KEYS =
58                     List.of(new SelectorKey("body", "output", "CommonHeader", "SubRequestID"));
59
60     public SdnrOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
61         super(params, config, PciMessage.class);
62     }
63
64     /**
65      * Note: these values must be in correspondence with {@link #SELECTOR_KEYS}.
66      */
67     @Override
68     protected List<String> getExpectedKeyValues(int attempt, PciMessage request) {
69         return List.of(getSubRequestId());
70     }
71
72     @Override
73     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
74         return startGuardAsync();
75     }
76
77     /*
78      * NOTE: This should avoid throwing exceptions, so that a ControlLoopResponse can be
79      * added to the outcome. Consequently, it returns FAILURE if a required field is
80      * missing from the response.
81      */
82     @Override
83     protected Status detmStatus(String rawResponse, PciMessage responseWrapper) {
84         PciResponse response = responseWrapper.getBody().getOutput();
85
86         if (response.getStatus() == null) {
87             logger.warn("SDNR response is missing the response status");
88             return Status.FAILURE;
89         }
90
91         StatusCodeEnum code = StatusCodeEnum.fromStatusCode(response.getStatus().getCode());
92
93         if (code == null) {
94             logger.warn("unknown SDNR response status code: {}", response.getStatus().getCode());
95             return Status.FAILURE;
96         }
97
98         switch (code) {
99             case SUCCESS:
100             case PARTIAL_SUCCESS:
101                 return Status.SUCCESS;
102             case FAILURE:
103             case PARTIAL_FAILURE:
104                 return Status.FAILURE;
105             case ERROR:
106             case REJECT:
107                 logger.warn("SDNR request was not accepted, code={}", code);
108                 return Status.FAILURE;
109             case ACCEPTED:
110             default:
111                 // awaiting a "final" response
112                 return Status.STILL_WAITING;
113         }
114     }
115
116     /**
117      * Sets the message to the status description, if available.
118      */
119     @Override
120     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, PciMessage responseWrapper) {
121         outcome.setResponse(responseWrapper);
122
123         if (responseWrapper.getBody() == null || responseWrapper.getBody().getOutput() == null) {
124             outcome.setControlLoopResponse(makeControlLoopResponse(null));
125             return setOutcome(outcome, result);
126         }
127
128         PciResponse pciResponse = responseWrapper.getBody().getOutput();
129         if (pciResponse.getStatus() == null || pciResponse.getStatus().getValue() == null) {
130             outcome.setControlLoopResponse(makeControlLoopResponse(pciResponse.getPayload()));
131             return setOutcome(outcome, result);
132         }
133
134         outcome.setResult(result);
135         outcome.setMessage(pciResponse.getStatus().getValue());
136         outcome.setControlLoopResponse(makeControlLoopResponse(pciResponse.getPayload()));
137         return outcome;
138     }
139
140     /**
141      * Converts the SDNR response to a ControlLoopResponse.
142      *
143      * @param responsePayload payload from the response
144      *
145      * @return a new ControlLoopResponse
146      */
147     private ControlLoopResponse makeControlLoopResponse(String responsePayload) {
148         VirtualControlLoopEvent event = params.getContext().getEvent();
149
150         ControlLoopResponse clRsp = new ControlLoopResponse();
151         clRsp.setPayload(responsePayload);
152         clRsp.setFrom(params.getActor());
153         clRsp.setTarget("DCAE");
154         clRsp.setClosedLoopControlName(event.getClosedLoopControlName());
155         clRsp.setPolicyName(event.getPolicyName());
156         clRsp.setPolicyVersion(event.getPolicyVersion());
157         clRsp.setRequestId(event.getRequestId());
158         clRsp.setVersion(event.getVersion());
159
160         return clRsp;
161     }
162
163     @Override
164     protected PciMessage makeRequest(int attempt) {
165         VirtualControlLoopEvent onset = params.getContext().getEvent();
166         String subRequestId = getSubRequestId();
167
168         /* Construct an SDNR request using pci Model */
169
170         PciMessage dmaapRequest = new PciMessage();
171         dmaapRequest.setVersion("1.0");
172         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + subRequestId);
173         dmaapRequest.setType("request");
174         dmaapRequest.setRpcName(params.getOperation().toLowerCase());
175
176         /* This is the actual request that is placed in the dmaap wrapper. */
177         final PciRequest sdnrRequest = new PciRequest();
178
179         /* The common header is a required field for all SDNR requests. */
180         PciCommonHeader requestCommonHeader = new PciCommonHeader();
181         requestCommonHeader.setRequestId(onset.getRequestId());
182         requestCommonHeader.setSubRequestId(subRequestId);
183
184         sdnrRequest.setCommonHeader(requestCommonHeader);
185         sdnrRequest.setPayload(onset.getPayload());
186         sdnrRequest.setAction(params.getOperation());
187
188         /*
189          * Once the pci request is constructed, add it into the body of the dmaap wrapper.
190          */
191         PciBody body = new PciBody();
192         body.setInput(sdnrRequest);
193         dmaapRequest.setBody(body);
194
195         /* Return the request to be sent through dmaap. */
196         return dmaapRequest;
197     }
198 }