Set sub request ID before start callback
[policy/models.git] / models-interactions / model-actors / actor.guard / src / main / java / org / onap / policy / controlloop / actor / guard / GuardOperation.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.guard;
22
23 import java.util.Map;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.Executor;
26 import javax.ws.rs.client.Entity;
27 import javax.ws.rs.core.MediaType;
28 import javax.ws.rs.core.Response;
29 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
30 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
31 import org.onap.policy.controlloop.actorserviceprovider.CallbackManager;
32 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
33 import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation;
34 import org.onap.policy.controlloop.actorserviceprovider.impl.OperationPartial;
35 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
36 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
37 import org.onap.policy.controlloop.policy.PolicyResult;
38 import org.onap.policy.models.decisions.concepts.DecisionRequest;
39 import org.onap.policy.models.decisions.concepts.DecisionResponse;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Guard Operation. The outcome message is set to the guard response. If the guard is
45  * permitted or indeterminate, then the outcome is set to SUCCESS.
46  * <p/>
47  * The input to the request is taken from the payload, where properties are mapped to the
48  * field names in the {@link DecisionRequest} object. Properties whose names begin with
49  * "resource." are placed into the "resource" field of the {@link DecisionRequest}. The
50  * following will be provided, if not specified in the payload:
51  * <dl>
52  * <dt>action</dt>
53  * <dd>"guard"</dd>
54  * <dt>request ID</dt>
55  * <dd>generated</dd>
56  * </dl>
57  */
58 public class GuardOperation extends HttpOperation<DecisionResponse> {
59     private static final Logger logger = LoggerFactory.getLogger(GuardOperation.class);
60
61     // operation name
62     public static final String NAME = OperationPartial.GUARD_OPERATION_NAME;
63
64     public static final String PERMIT = "Permit";
65     public static final String DENY = "Deny";
66     public static final String INDETERMINATE = "Indeterminate";
67
68     /**
69      * Prefix for properties in the payload that should be copied to the "resource" field
70      * of the request.
71      */
72     public static final String RESOURCE_PREFIX = "resource.";
73
74     private final GuardConfig config;
75
76
77     /**
78      * Constructs the object.
79      *
80      * @param params operation parameters
81      * @param config configuration for this operation
82      */
83     public GuardOperation(ControlLoopOperationParams params, HttpConfig config) {
84         super(params, config, DecisionResponse.class);
85         this.config = (GuardConfig) config;
86     }
87
88     @Override
89     public CompletableFuture<OperationOutcome> start() {
90         if (!config.isDisabled()) {
91             // enabled - do full guard operation
92             return super.start();
93         }
94
95         // guard is disabled, thus it is always treated as a success
96         logger.info("{}: guard disabled, always succeeds for {}", getFullName(), params.getRequestId());
97
98         final Executor executor = params.getExecutor();
99         final CallbackManager callbacks = new CallbackManager();
100
101         return CompletableFuture.completedFuture(params.makeOutcome())
102                         .whenCompleteAsync(callbackStarted(callbacks), executor)
103                         .whenCompleteAsync(callbackCompleted(callbacks), executor);
104     }
105
106     @Override
107     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
108         DecisionRequest request = makeRequest();
109         Entity<DecisionRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
110
111         Map<String, Object> headers = makeHeaders();
112
113         headers.put("Accept", MediaType.APPLICATION_JSON);
114         String url = getUrl();
115
116         logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
117
118         // @formatter:off
119         return handleResponse(outcome, url,
120             callback -> getClient().post(callback, getPath(), entity, headers));
121         // @formatter:on
122     }
123
124     /**
125      * Makes a request from the payload.
126      *
127      * @return a new request
128      */
129     protected DecisionRequest makeRequest() {
130         if (params.getPayload() == null) {
131             throw new IllegalArgumentException("missing payload");
132         }
133
134         DecisionRequest req = config.makeRequest();
135         req.setRequestId(getSubRequestId());
136         req.setResource(Map.of("guard", params.getPayload()));
137
138         return req;
139     }
140
141     @Override
142     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
143                     Response rawResponse, DecisionResponse response) {
144
145         // determine the result
146         String status = response.getStatus();
147         if (status == null) {
148             outcome.setResult(PolicyResult.FAILURE);
149             outcome.setMessage("response contains no status");
150             return CompletableFuture.completedFuture(outcome);
151         }
152
153         if (PERMIT.equalsIgnoreCase(status) || INDETERMINATE.equalsIgnoreCase(status)) {
154             outcome.setResult(PolicyResult.SUCCESS);
155         } else {
156             outcome.setResult(PolicyResult.FAILURE);
157         }
158
159         // set the message
160         outcome.setMessage(response.getStatus());
161
162         return CompletableFuture.completedFuture(outcome);
163     }
164 }