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