5605d6535a77e3779dca55b941a92cd26abd9d70
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / Cached.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modification Copyright (c) 2019 IBM
8  * ===========================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END====================================================
21  *
22  */
23
24 package org.onap.aaf.auth.dao;
25
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Timer;
30 import java.util.TimerTask;
31
32 import org.onap.aaf.auth.cache.Cache;
33 import org.onap.aaf.auth.dao.cass.Status;
34 import org.onap.aaf.auth.env.AuthzEnv;
35 import org.onap.aaf.auth.env.AuthzTrans;
36 import org.onap.aaf.auth.layer.Result;
37 import org.onap.aaf.misc.env.Env;
38 import org.onap.aaf.misc.env.Trans;
39
40 public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<TRANS,DATA> {
41     // Java does not allow creation of Arrays with Generics in them...
42     protected final CIDAO<TRANS> info;
43     
44     private static Timer infoTimer;
45     private Object cache[];
46     public final int segSize;
47
48     protected final String name;
49
50     private final long expireIn;
51
52
53     public Cached(CIDAO<TRANS> info, String name, int segSize, long expireIn) {
54         this.name =name;
55         this.segSize = segSize;
56         this.info = info;
57         this.expireIn = expireIn;
58         cache = new Object[segSize];
59         // Create a new Map for each Segment, and store locally
60         for (int i=0;i<segSize;++i) {
61             cache[i]=obtain(name+i);
62         }
63     }
64
65     // Taken from String Hash, but coded, to ensure consistent across Java versions.  Also covers negative case;
66     public int cacheIdx(String key) {
67         int h = 0;
68         for (int i = 0; i < key.length(); i++) {
69             h = 31*h + key.charAt(i);
70         }
71         if (h<0) {
72             h*=-1;
73         }
74         return h%segSize;
75     }
76     
77     public void add(String key, List<DATA> data) {
78         @SuppressWarnings("unchecked")
79         Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx(key)]);
80         map.put(key, new Dated(data, expireIn));
81     }
82
83
84     public int invalidate(String key)  {
85         int cacheIdx = cacheIdx(key);
86         @SuppressWarnings("unchecked")
87         Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
88         if (map!=null)map.clear();
89         return cacheIdx;
90     }
91
92     public Result<Void> invalidate(int segment)  {
93         if (segment<0 || segment>=cache.length) {
94             return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment));
95         }
96         @SuppressWarnings("unchecked")
97         Map<String,Dated> map = ((Map<String,Dated>)cache[segment]);
98         if (map!=null) {
99             map.clear();
100         }
101         return Result.ok();
102     }
103
104     @FunctionalInterface
105     public interface Getter<D> {
106         public abstract Result<List<D>> get();
107     };
108     
109     // TODO utilize Segmented Caches, and fold "get" into "reads"
110     @SuppressWarnings("unchecked")
111     public Result<List<DATA>> get(TRANS trans, String key, Getter<DATA> getter) {
112         List<DATA> ld = null;
113         Result<List<DATA>> rld = null;
114         
115         int cacheIdx = cacheIdx(key);
116         Map<String, Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
117         
118         // Check for saved element in cache
119         Dated cached = map.get(key);
120         // Note: These Segment Timestamps are kept up to date with DB
121         Date dbStamp = info.get(trans, name,cacheIdx);
122         
123         // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax)
124         if (cached!=null && dbStamp!=null && dbStamp.before(cached.timestamp)) {
125             ld = (List<DATA>)cached.data;
126             rld = Result.ok(ld);
127         } else {
128             rld = getter.get();
129             if (rld.isOK()) { // only store valid lists
130                 map.put(key, new Dated(rld.value,expireIn));  // successful item found gets put in cache
131             }
132         }
133         return rld;
134     }
135
136     /**
137      * Each Cached object has multiple Segments that need cleaning.  Derive each, and add to Cleansing Thread
138      * @param env
139      * @param dao
140      */
141     public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) {
142         for (CachedDAO<?,?,?> d : dao) {  
143             for (int i=0;i<d.segSize;++i) {
144                 startCleansing(env, d.table()+i);
145             }
146         }
147     }
148
149
150     public static<T extends Trans> void startRefresh(AuthzEnv env, CIDAO<AuthzTrans> cidao) {
151         if (infoTimer==null) {
152             infoTimer = new Timer("CachedDAO Info Refresh Timer");
153             int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh 
154             infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately
155         }
156     }
157     
158     public static void stopTimer() {
159         Cache.stopTimer();
160         if (infoTimer!=null) {
161             infoTimer.cancel();
162             infoTimer = null;
163         }
164     }
165     
166     private static final class Refresh extends TimerTask {
167         private static final int MAXREFRESH = 2*60*10000; // 20 mins
168         private AuthzEnv env;
169         private CIDAO<AuthzTrans> cidao;
170         private int minRefresh;
171         private long lastRun;
172         
173         public Refresh(AuthzEnv env, CIDAO<AuthzTrans> cidao, int minRefresh) {
174             this.env = env;
175             this.cidao = cidao;
176             this.minRefresh = minRefresh;
177             lastRun = System.currentTimeMillis()-MAXREFRESH-1000;
178         }
179         
180         @Override
181         public void run() {
182             // Evaluate whether to refresh based on transaction rate
183             long now = System.currentTimeMillis();
184             long interval = now-lastRun;
185
186             if (interval < minRefresh || interval < Math.min(env.transRate(),MAXREFRESH)) {
187                 return;
188             }
189             lastRun = now;
190             AuthzTrans trans = env.newTransNoAvg();
191             Result<Void> rv = cidao.check(trans);
192             if (rv.status!=Result.OK) {
193                 env.error().log("Error in CacheInfo Refresh",rv.details);
194             }
195             if (env.debug().isLoggable()) {
196                 StringBuilder sb = new StringBuilder("Cache Info Refresh: ");
197                 trans.auditTrail(0, sb, Env.REMOTE);
198                 env.debug().log(sb);
199             }
200         }
201     }
202 }