00f7680b08c77eefded8f2fe132f457ac1e6fa42
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / operationshistory / CountRecentOperationsPip.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdp.xacml.application.common.operationshistory;
22
23 import com.att.research.xacml.api.XACML3;
24 import com.att.research.xacml.api.pip.PIPException;
25 import com.att.research.xacml.api.pip.PIPFinder;
26 import com.att.research.xacml.api.pip.PIPRequest;
27 import com.att.research.xacml.api.pip.PIPResponse;
28 import com.att.research.xacml.std.pip.StdMutablePIPResponse;
29 import com.att.research.xacml.std.pip.StdPIPResponse;
30 import com.google.common.base.Strings;
31
32 import java.sql.Timestamp;
33 import java.time.Instant;
34 import java.time.temporal.ChronoUnit;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Properties;
38
39 import javax.persistence.Persistence;
40
41 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
42 import org.onap.policy.pdp.xacml.application.common.std.StdOnapPip;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46
47 public class CountRecentOperationsPip extends StdOnapPip {
48     public static final String ISSUER_NAME = "count-recent-operations";
49     private static Logger logger = LoggerFactory.getLogger(CountRecentOperationsPip.class);
50
51     public CountRecentOperationsPip() {
52         super();
53     }
54
55     @Override
56     public Collection<PIPRequest> attributesRequired() {
57         return Arrays.asList(PIP_REQUEST_ACTOR, PIP_REQUEST_RECIPE, PIP_REQUEST_TARGET);
58     }
59
60     @Override
61     public void configure(String id, Properties properties) throws PIPException {
62         super.configure(id, properties);
63         //
64         // Create our entity manager
65         //
66         em = null;
67         try {
68             //
69             // In case there are any overloaded properties for the JPA
70             //
71             Properties emProperties = new Properties();
72             emProperties.putAll(properties);
73             //
74             // Create the entity manager factory
75             //
76             em = Persistence.createEntityManagerFactory(
77                     properties.getProperty(ISSUER_NAME + ".persistenceunit"),
78                     emProperties).createEntityManager();
79         } catch (Exception e) {
80             logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e);
81         }
82     }
83
84     /**
85      * getAttributes.
86      *
87      * @param pipRequest the request
88      * @param pipFinder the pip finder
89      * @return PIPResponse
90      */
91     @Override
92     public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
93         logger.debug("getAttributes requesting attribute {} of type {} for issuer {}",
94                 pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer());
95         //
96         // Determine if the issuer is correct
97         //
98         if (Strings.isNullOrEmpty(pipRequest.getIssuer())) {
99             logger.debug("issuer is null - returning empty response");
100             //
101             // We only respond to ourself as the issuer
102             //
103             return StdPIPResponse.PIP_RESPONSE_EMPTY;
104         }
105         if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) {
106             logger.debug("Issuer does not start with guard");
107             //
108             // We only respond to ourself as the issuer
109             //
110             return StdPIPResponse.PIP_RESPONSE_EMPTY;
111         }
112         //
113         // Parse out the issuer which denotes the time window
114         // Eg: any-prefix:tw:10:minute
115         //
116         String[] s1 = pipRequest.getIssuer().split("tw:");
117         String[] s2 = s1[1].split(":");
118         int timeWindowVal = Integer.parseInt(s2[0]);
119         String timeWindowScale = s2[1];
120         //
121         // Grab other attribute values
122         //
123         String actor = getAttribute(pipFinder, PIP_REQUEST_ACTOR);
124         String operation = getAttribute(pipFinder, PIP_REQUEST_RECIPE);
125         String target = getAttribute(pipFinder, PIP_REQUEST_TARGET);
126         String timeWindow = timeWindowVal + " " + timeWindowScale;
127         logger.info("Going to query DB about: actor {} operation {} target {} time window {}",
128                 actor, operation, target, timeWindow);
129         //
130         // Sanity check
131         //
132         if (actor == null || operation == null || target == null) {
133             //
134             // See if we have all the values
135             //
136             logger.error("missing attributes return empty");
137             return StdPIPResponse.PIP_RESPONSE_EMPTY;
138         }
139         //
140         // Ok do the database query
141         //
142         long operationCount = doDatabaseQuery(actor, operation, target, timeWindowVal, timeWindowScale);
143         //
144         // Create and return PipResponse
145         //
146         StdMutablePIPResponse pipResponse    = new StdMutablePIPResponse();
147         this.addLongAttribute(pipResponse,
148                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
149                 ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT,
150                 operationCount,
151                 pipRequest);
152         return new StdPIPResponse(pipResponse);
153     }
154
155     private long doDatabaseQuery(String actor, String operation, String target, int timeWindowVal,
156             String timeWindowScale) {
157         logger.info("Querying operations history for {} {} {} {} {}",
158                 actor, operation, target, timeWindowVal, timeWindowScale);
159         //
160         // Only can query if we have an EntityManager
161         //
162         if (em == null) {
163             logger.error("No EntityManager available");
164             return -1;
165         }
166         //
167         // Do the query
168         //
169         try {
170             //
171             // We are expecting a single result
172             //
173             return em.createQuery("select count(e) from Dbao e"
174                                   + " where e.outcome<>'Failure_Guard'"
175                                   + " and e.actor= ?1"
176                                   + " and e.operation= ?2"
177                                   + " and e.target= ?3"
178                                   + " and e.endtime between"
179                                   + " ?4 and CURRENT_TIMESTAMP",
180                                   Long.class)
181                 .setParameter(1, actor)
182                 .setParameter(2, operation)
183                 .setParameter(3, target)
184                 .setParameter(4, Timestamp.from(Instant.now()
185                                                 .minus(timeWindowVal,
186                                                        stringToChronoUnit(timeWindowScale))))
187                 .getSingleResult();
188         } catch (Exception e) {
189             logger.error("Typed query failed ", e);
190             return -1;
191         }
192     }
193
194     private ChronoUnit stringToChronoUnit(String scale) {
195         //
196         // Compute the time window
197         //
198         switch (scale.toLowerCase()) {
199             case "second":
200                 return ChronoUnit.SECONDS;
201             case "minute":
202                 return ChronoUnit.MINUTES;
203             case "hour":
204                 return ChronoUnit.HOURS;
205             case "day":
206                 return ChronoUnit.DAYS;
207             case "week":
208                 return ChronoUnit.WEEKS;
209             case "month":
210                 return ChronoUnit.MONTHS;
211             case "year":
212                 return ChronoUnit.YEARS;
213             default:
214                 //
215                 // Unsupported
216                 //
217                 logger.error("Unsupported time window scale value {}", scale);
218         }
219         return null;
220     }
221
222 }