c18ad5fac435f862715f2e206680b2f22b647703
[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(properties);
72             //
73             // Create the entity manager factory
74             //
75             em = Persistence.createEntityManagerFactory(
76                     properties.getProperty(ISSUER_NAME + ".persistenceunit"),
77                     emProperties).createEntityManager();
78         } catch (Exception e) {
79             logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e);
80         }
81     }
82
83     /**
84      * getAttributes.
85      *
86      * @param pipRequest the request
87      * @param pipFinder the pip finder
88      * @return PIPResponse
89      */
90     @Override
91     public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException {
92         logger.debug("getAttributes requesting attribute {} of type {} for issuer {}",
93                 pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer());
94         //
95         // Determine if the issuer is correct
96         //
97         if (Strings.isNullOrEmpty(pipRequest.getIssuer())) {
98             logger.debug("issuer is null - returning empty response");
99             //
100             // We only respond to ourself as the issuer
101             //
102             return StdPIPResponse.PIP_RESPONSE_EMPTY;
103         }
104         if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) {
105             logger.debug("Issuer does not start with guard");
106             //
107             // We only respond to ourself as the issuer
108             //
109             return StdPIPResponse.PIP_RESPONSE_EMPTY;
110         }
111         //
112         // Parse out the issuer which denotes the time window
113         // Eg: any-prefix:tw:10:minute
114         //
115         String[] s1 = pipRequest.getIssuer().split("tw:");
116         String[] s2 = s1[1].split(":");
117         int timeWindowVal = Integer.parseInt(s2[0]);
118         String timeWindowScale = s2[1];
119         //
120         // Grab other attribute values
121         //
122         String actor = getAttribute(pipFinder, PIP_REQUEST_ACTOR);
123         String operation = getAttribute(pipFinder, PIP_REQUEST_RECIPE);
124         String target = getAttribute(pipFinder, PIP_REQUEST_TARGET);
125         String timeWindow = timeWindowVal + " " + timeWindowScale;
126         logger.info("Going to query DB about: actor {} operation {} target {} time window {}",
127                 actor, operation, target, timeWindow);
128         //
129         // Sanity check
130         //
131         if (actor == null || operation == null || target == null) {
132             //
133             // See if we have all the values
134             //
135             logger.error("missing attributes return empty");
136             return StdPIPResponse.PIP_RESPONSE_EMPTY;
137         }
138         //
139         // Ok do the database query
140         //
141         long operationCount = doDatabaseQuery(actor, operation, target, timeWindowVal, timeWindowScale);
142         //
143         // Create and return PipResponse
144         //
145         StdMutablePIPResponse pipResponse    = new StdMutablePIPResponse();
146         this.addLongAttribute(pipResponse,
147                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE,
148                 ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT,
149                 operationCount,
150                 pipRequest);
151         return new StdPIPResponse(pipResponse);
152     }
153
154     private long doDatabaseQuery(String actor, String operation, String target, int timeWindowVal,
155             String timeWindowScale) {
156         logger.info("Querying operations history for {} {} {} {} {}",
157                 actor, operation, target, timeWindowVal, timeWindowScale);
158         //
159         // Only can query if we have an EntityManager
160         //
161         if (em == null) {
162             logger.error("No EntityManager available");
163             return -1;
164         }
165         //
166         // Do the query
167         //
168         try {
169             //
170             // We are expecting a single result
171             //
172             return em.createQuery("select count(e) from Dbao e"
173                                   + " where e.outcome<>'Failure_Guard'"
174                                   + " and e.actor= ?1"
175                                   + " and e.operation= ?2"
176                                   + " and e.target= ?3"
177                                   + " and e.endtime between"
178                                   + " ?4 and CURRENT_TIMESTAMP",
179                                   Long.class)
180                 .setParameter(1, actor)
181                 .setParameter(2, operation)
182                 .setParameter(3, target)
183                 .setParameter(4, Timestamp.from(Instant.now()
184                                                 .minus(timeWindowVal,
185                                                        stringToChronoUnit(timeWindowScale))))
186                 .getSingleResult();
187         } catch (Exception e) {
188             logger.error("Typed query failed ", e);
189             return -1;
190         }
191     }
192
193     private ChronoUnit stringToChronoUnit(String scale) {
194         //
195         // Compute the time window
196         //
197         switch (scale.toLowerCase()) {
198             case "second":
199                 return ChronoUnit.SECONDS;
200             case "minute":
201                 return ChronoUnit.MINUTES;
202             case "hour":
203                 return ChronoUnit.HOURS;
204             case "day":
205                 return ChronoUnit.DAYS;
206             case "week":
207                 return ChronoUnit.WEEKS;
208             case "month":
209                 return ChronoUnit.MONTHS;
210             case "year":
211                 return ChronoUnit.YEARS;
212             default:
213                 //
214                 // Unsupported
215                 //
216                 logger.error("Unsupported time window scale value {}", scale);
217         }
218         return null;
219     }
220
221 }