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