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