Update new SDNR actor with v2.0 structures
[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.UUID;
25 import java.util.concurrent.CompletableFuture;
26 import org.apache.commons.lang3.tuple.Pair;
27 import org.onap.policy.controlloop.VirtualControlLoopEvent;
28 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
29 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
30 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
31 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
32 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
33 import org.onap.policy.controlloop.policy.PolicyResult;
34 import org.onap.policy.sdnr.PciBody;
35 import org.onap.policy.sdnr.PciCommonHeader;
36 import org.onap.policy.sdnr.PciMessage;
37 import org.onap.policy.sdnr.PciRequest;
38 import org.onap.policy.sdnr.PciResponse;
39 import org.onap.policy.sdnr.util.StatusCodeEnum;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public abstract class SdnrOperation extends BidirectionalTopicOperation<PciMessage, PciMessage> {
44     private static final Logger logger = LoggerFactory.getLogger(SdnrOperation.class);
45
46     /**
47      * Keys used to match the response with the request listener. The sub request ID is a
48      * UUID, so it can be used to uniquely identify the response.
49      * <p/>
50      * Note: if these change, then {@link #getExpectedKeyValues(int, PciMessage)} must be
51      * updated accordingly.
52      */
53     public static final List<SelectorKey> SELECTOR_KEYS =
54                     List.of(new SelectorKey("body", "output", "CommonHeader", "SubRequestID"));
55
56     public SdnrOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
57         super(params, config, PciMessage.class);
58     }
59
60     /**
61      * Note: these values must be in correspondence with {@link #SELECTOR_KEYS}.
62      */
63     @Override
64     protected List<String> getExpectedKeyValues(int attempt, PciMessage request) {
65         return List.of(request.getBody().getInput().getCommonHeader().getSubRequestId());
66     }
67
68     @Override
69     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
70         return startGuardAsync();
71     }
72
73     @Override
74     protected Status detmStatus(String rawResponse, PciMessage responseWrapper) {
75         PciResponse response = responseWrapper.getBody().getOutput();
76
77         if (response.getStatus() == null) {
78             throw new IllegalArgumentException("SDNR response is missing the response status");
79         }
80
81         StatusCodeEnum code = StatusCodeEnum.fromStatusCode(response.getStatus().getCode());
82
83         if (code == null) {
84             throw new IllegalArgumentException("unknown SDNR response status code: " + response.getStatus().getCode());
85         }
86
87         /*
88          * Response and Payload are just printed and no further action needed since
89          * casablanca release
90          */
91         logger.info("SDNR Response Code {} Message is {}", code, response.getStatus().getValue());
92         logger.info("SDNR Response Payload is {}", response.getPayload());
93
94         switch (code) {
95             case SUCCESS:
96             case PARTIAL_SUCCESS:
97                 return Status.SUCCESS;
98             case FAILURE:
99             case PARTIAL_FAILURE:
100                 return Status.FAILURE;
101             case ERROR:
102             case REJECT:
103                 throw new IllegalArgumentException("SDNR request was not accepted, code=" + code);
104             case ACCEPTED:
105             default:
106                 // awaiting a "final" response
107                 return Status.STILL_WAITING;
108         }
109     }
110
111     /**
112      * Sets the message to the status description, if available.
113      */
114     @Override
115     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, PciMessage responseWrapper) {
116         if (responseWrapper.getBody() == null || responseWrapper.getBody().getOutput() == null) {
117             return setOutcome(outcome, result);
118         }
119
120         PciResponse response = responseWrapper.getBody().getOutput();
121         if (response.getStatus() == null || response.getStatus().getValue() == null) {
122             return setOutcome(outcome, result);
123         }
124
125         outcome.setResult(result);
126         outcome.setMessage(response.getStatus().getValue());
127         return outcome;
128     }
129
130     @Override
131     protected Pair<String, PciMessage> makeRequest(int attempt) {
132         VirtualControlLoopEvent onset = params.getContext().getEvent();
133         String subRequestId = UUID.randomUUID().toString();
134
135         /* Construct an SDNR request using pci Model */
136
137         PciMessage dmaapRequest = new PciMessage();
138         dmaapRequest.setVersion("1.0");
139         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + subRequestId);
140         dmaapRequest.setType("request");
141
142         /* This is the actual request that is placed in the dmaap wrapper. */
143         final PciRequest sdnrRequest = new PciRequest();
144
145         /* The common header is a required field for all SDNR requests. */
146         PciCommonHeader requestCommonHeader = new PciCommonHeader();
147         requestCommonHeader.setRequestId(onset.getRequestId());
148         requestCommonHeader.setSubRequestId(subRequestId);
149
150         sdnrRequest.setCommonHeader(requestCommonHeader);
151         sdnrRequest.setPayload(onset.getPayload());
152
153         /*
154          * Once the pci request is constructed, add it into the body of the dmaap wrapper.
155          */
156         PciBody body = new PciBody();
157         body.setInput(sdnrRequest);
158         dmaapRequest.setBody(body);
159         logger.info("SDNR Request to be sent is {}", dmaapRequest);
160
161         /* Return the request to be sent through dmaap. */
162         return Pair.of(subRequestId, dmaapRequest);
163     }
164 }