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