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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdp.xacml.application.common.operationshistory;
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;
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;
39 import javax.persistence.Persistence;
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;
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);
51 public CountRecentOperationsPip() {
56 public Collection<PIPRequest> attributesRequired() {
57 return Arrays.asList(PIP_REQUEST_ACTOR, PIP_REQUEST_RECIPE, PIP_REQUEST_TARGET);
61 public void configure(String id, Properties properties) throws PIPException {
62 super.configure(id, properties);
64 // Create our entity manager
69 // In case there are any overloaded properties for the JPA
71 Properties emProperties = new Properties();
72 emProperties.putAll(properties);
74 // Create the entity manager factory
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);
87 * @param pipRequest the request
88 * @param pipFinder the pip finder
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());
96 // Determine if the issuer is correct
98 if (Strings.isNullOrEmpty(pipRequest.getIssuer())) {
99 logger.debug("issuer is null - returning empty response");
101 // We only respond to ourself as the issuer
103 return StdPIPResponse.PIP_RESPONSE_EMPTY;
105 if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) {
106 logger.debug("Issuer does not start with guard");
108 // We only respond to ourself as the issuer
110 return StdPIPResponse.PIP_RESPONSE_EMPTY;
113 // Parse out the issuer which denotes the time window
114 // Eg: any-prefix:tw:10:minute
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];
121 // Grab other attribute values
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);
132 if (actor == null || operation == null || target == null) {
134 // See if we have all the values
136 logger.error("missing attributes return empty");
137 return StdPIPResponse.PIP_RESPONSE_EMPTY;
140 // Ok do the database query
142 long operationCount = doDatabaseQuery(actor, operation, target, timeWindowVal, timeWindowScale);
144 // Create and return PipResponse
146 StdMutablePIPResponse pipResponse = new StdMutablePIPResponse();
147 this.addLongAttribute(pipResponse,
148 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
149 ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT,
152 return new StdPIPResponse(pipResponse);
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);
160 // Only can query if we have an EntityManager
163 logger.error("No EntityManager available");
171 // We are expecting a single result
173 return em.createQuery("select count(e) from Dbao e"
174 + " where e.outcome<>'Failure_Guard'"
176 + " and e.operation= ?2"
177 + " and e.target= ?3"
178 + " and e.endtime between"
179 + " ?4 and CURRENT_TIMESTAMP",
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))))
188 } catch (Exception e) {
189 logger.error("Typed query failed ", e);
194 private ChronoUnit stringToChronoUnit(String scale) {
196 // Compute the time window
198 switch (scale.toLowerCase()) {
200 return ChronoUnit.SECONDS;
202 return ChronoUnit.MINUTES;
204 return ChronoUnit.HOURS;
206 return ChronoUnit.DAYS;
208 return ChronoUnit.WEEKS;
210 return ChronoUnit.MONTHS;
212 return ChronoUnit.YEARS;
217 logger.error("Unsupported time window scale value {}", scale);