Fix legacy APPC handling of Request
[policy/models.git] / models-interactions / model-actors / actor.appc / src / main / java / org / onap / policy / controlloop / actor / appc / AppcOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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.appc;
22
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.UUID;
27 import java.util.concurrent.CompletableFuture;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.onap.policy.appc.CommonHeader;
30 import org.onap.policy.appc.Request;
31 import org.onap.policy.appc.Response;
32 import org.onap.policy.appc.ResponseCode;
33 import org.onap.policy.common.utils.coder.Coder;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.common.utils.coder.StandardCoder;
36 import org.onap.policy.common.utils.coder.StandardCoderInstantAsMillis;
37 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
38 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
41 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
42 import org.onap.policy.controlloop.policy.PolicyResult;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * Superclass for APPC Operations.
48  */
49 public abstract class AppcOperation extends BidirectionalTopicOperation<Request, Response> {
50     private static final Logger logger = LoggerFactory.getLogger(AppcOperation.class);
51     private static final StandardCoder coder = new StandardCoderInstantAsMillis();
52     public static final String VNF_ID_KEY = "generic-vnf.vnf-id";
53
54     /**
55      * Keys used to match the response with the request listener. The sub request ID is a
56      * UUID, so it can be used to uniquely identify the response.
57      * <p/>
58      * Note: if these change, then {@link #getExpectedKeyValues(int, Request)} must be
59      * updated accordingly.
60      */
61     public static final List<SelectorKey> SELECTOR_KEYS = List.of(new SelectorKey("CommonHeader", "SubRequestID"));
62
63     /**
64      * Constructs the object.
65      *
66      * @param params operation parameters
67      * @param config configuration for this operation
68      */
69     public AppcOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
70         super(params, config, Response.class);
71     }
72
73     /**
74      * Starts the GUARD.
75      */
76     @Override
77     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
78         return startGuardAsync();
79     }
80
81     /**
82      * Makes a request, given the target VNF. This is a support function for
83      * {@link #makeRequest(int)}.
84      *
85      * @param attempt attempt number
86      * @param targetVnf target VNF
87      * @return a new request
88      */
89     protected Pair<String, Request> makeRequest(int attempt, String targetVnf) {
90         Request request = new Request();
91         request.setCommonHeader(new CommonHeader());
92         request.getCommonHeader().setRequestId(params.getRequestId());
93
94         // TODO ok to use UUID, or does it have to be the "attempt"?
95         final String subreq = UUID.randomUUID().toString();
96         request.getCommonHeader().setSubRequestId(subreq);
97
98         request.setAction(getName());
99
100         // convert payload strings to objects
101         if (params.getPayload() == null) {
102             logger.info("{}: no payload specified for {}", getFullName(), params.getRequestId());
103         } else {
104             convertPayload(params.getPayload(), request.getPayload());
105         }
106
107         // add/replace specific values
108         request.getPayload().put(VNF_ID_KEY, targetVnf);
109
110         return Pair.of(subreq, request);
111     }
112
113     /**
114      * Converts a payload. The original value is assumed to be a JSON string, which is
115      * decoded into an object.
116      *
117      * @param source source from which to get the values
118      * @param target where to place the decoded values
119      */
120     private static void convertPayload(Map<String, Object> source, Map<String, Object> target) {
121         for (Entry<String, Object> ent : source.entrySet()) {
122             Object value = ent.getValue();
123             if (value == null) {
124                 target.put(ent.getKey(), null);
125                 continue;
126             }
127
128             try {
129                 target.put(ent.getKey(), coder.decode(value.toString(), Object.class));
130
131             } catch (CoderException e) {
132                 logger.warn("cannot decode JSON value {}: {}", ent.getKey(), ent.getValue(), e);
133             }
134         }
135     }
136
137     /**
138      * Note: these values must match {@link #SELECTOR_KEYS}.
139      */
140     @Override
141     protected List<String> getExpectedKeyValues(int attempt, Request request) {
142         return List.of(request.getCommonHeader().getSubRequestId());
143     }
144
145     @Override
146     protected Status detmStatus(String rawResponse, Response response) {
147         if (response.getStatus() == null) {
148             // no status - this must be a request, not a response - just ignore it
149             logger.info("{}: ignoring request message for {}", getFullName(), params.getRequestId());
150             return Status.STILL_WAITING;
151         }
152
153         ResponseCode code = ResponseCode.toResponseCode(response.getStatus().getCode());
154         if (code == null) {
155             throw new IllegalArgumentException(
156                             "unknown APPC-C response status code: " + response.getStatus().getCode());
157         }
158
159         switch (code) {
160             case SUCCESS:
161                 return Status.SUCCESS;
162             case FAILURE:
163                 return Status.FAILURE;
164             case ERROR:
165             case REJECT:
166                 throw new IllegalArgumentException("APP-C request was not accepted, code=" + code);
167             case ACCEPT:
168             default:
169                 // awaiting a "final" response
170                 return Status.STILL_WAITING;
171         }
172     }
173
174     /**
175      * Sets the message to the status description, if available.
176      */
177     @Override
178     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response response) {
179         if (response.getStatus() == null || response.getStatus().getDescription() == null) {
180             return setOutcome(outcome, result);
181         }
182
183         outcome.setResult(result);
184         outcome.setMessage(response.getStatus().getDescription());
185         return outcome;
186     }
187
188     @Override
189     protected Coder makeCoder() {
190         return coder;
191     }
192 }