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