summaryrefslogtreecommitdiffstats
path: root/authz-cass/src/main/java/com/att/dao/Cached.java
blob: 2cdd2b21017419b2fab1e6707c5de8ca8feb14fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*******************************************************************************
 * ============LICENSE_START====================================================
 * * org.onap.aai
 * * ===========================================================================
 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * * Copyright © 2017 Amdocs
 * * ===========================================================================
 * * Licensed under the Apache License, Version 2.0 (the "License");
 * * you may not use this file except in compliance with the License.
 * * You may obtain a copy of the License at
 * * 
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 * * 
 *  * Unless required by applicable law or agreed to in writing, software
 * * distributed under the License is distributed on an "AS IS" BASIS,
 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * * See the License for the specific language governing permissions and
 * * limitations under the License.
 * * ============LICENSE_END====================================================
 * *
 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * *
 ******************************************************************************/
package com.att.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.att.authz.env.AuthzEnv;
import com.att.authz.env.AuthzTrans;
import com.att.authz.layer.Result;
import com.att.cache.Cache;
import com.att.dao.aaf.cass.Status;
import com.att.inno.env.Env;
import com.att.inno.env.Trans;

public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<TRANS,DATA> {
	// Java does not allow creation of Arrays with Generics in them...
	// private Map<String,Dated> cache[];
	protected final CIDAO<TRANS> info;
	
	private static Timer infoTimer;
	private Object cache[];
	public final int segSize;

	protected final String name;
	


	// Taken from String Hash, but coded, to ensure consistent across Java versions.  Also covers negative case;
	public int cacheIdx(String key) {
		int h = 0;
		for (int i = 0; i < key.length(); i++) {
		    h = 31*h + key.charAt(i);
		}
		if(h<0)h*=-1;
		return h%segSize;
	}
	
	public Cached(CIDAO<TRANS> info, String name, int segSize) {
		this.name =name;
		this.segSize = segSize;
		this.info = info;
		cache = new Object[segSize];
		// Create a new Map for each Segment, and store locally
		for(int i=0;i<segSize;++i) {
			cache[i]=obtain(name+i);
		}
	}
	
	public void add(String key, List<DATA> data) {
		@SuppressWarnings("unchecked")
		Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx(key)]);
		map.put(key, new Dated(data));
	}


	public int invalidate(String key)  {
		int cacheIdx = cacheIdx(key);
		@SuppressWarnings("unchecked")
		Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
//		if(map.remove(key)!=null) // Not seeming to remove all the time
		if(map!=null)map.clear();
//			System.err.println("Remove " + name + " " + key);
		return cacheIdx;
	}

	public Result<Void> invalidate(int segment)  {
		if(segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment));
		@SuppressWarnings("unchecked")
		Map<String,Dated> map = ((Map<String,Dated>)cache[segment]);
		if(map!=null) {
			map.clear();
		}
		return Result.ok();
	}

	protected interface Getter<D> {
		public abstract Result<List<D>> get();
	};
	
	// TODO utilize Segmented Caches, and fold "get" into "reads"
	@SuppressWarnings("unchecked")
	public Result<List<DATA>> get(TRANS trans, String key, Getter<DATA> getter) {
		List<DATA> ld = null;
		Result<List<DATA>> rld = null;
		
		int cacheIdx = cacheIdx(key);
		Map<String, Dated> map = ((Map<String,Dated>)cache[cacheIdx]);
		
		// Check for saved element in cache
		Dated cached = map.get(key);
		// Note: These Segment Timestamps are kept up to date with DB
		Date dbStamp = info.get(trans, name,cacheIdx);
		
		// Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax)
		if(cached!=null && dbStamp.before(cached.timestamp)) {
			ld = (List<DATA>)cached.data;
			rld = Result.ok(ld);
		} else {
			rld = getter.get();
			if(rld.isOK()) { // only store valid lists
				map.put(key, new Dated(rld.value));  // successful item found gets put in cache
//			} else if(rld.status == Result.ERR_Backend){
//				map.remove(key);
			}
		}
		return rld;
	}

	/**
	 * Each Cached object has multiple Segments that need cleaning.  Derive each, and add to Cleansing Thread
	 * @param env
	 * @param dao
	 */
	public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) {
		for(CachedDAO<?,?,?> d : dao) {  
			for(int i=0;i<d.segSize;++i) {
				startCleansing(env, d.table()+i);
			}
		}
	}


	public static<T extends Trans> void startRefresh(AuthzEnv env, CIDAO<AuthzTrans> cidao) {
		if(infoTimer==null) {
			infoTimer = new Timer("CachedDAO Info Refresh Timer");
			int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh 
			infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately
		}
	}
	
	public static void stopTimer() {
		Cache.stopTimer();
		if(infoTimer!=null) {
			infoTimer.cancel();
			infoTimer = null;
		}
	}
	
	private final static class Refresh extends TimerTask {
		private static final int maxRefresh = 2*60*10000; // 20 mins
		private AuthzEnv env;
		private CIDAO<AuthzTrans> cidao;
		private int minRefresh;
		private long lastRun;
		
		public Refresh(AuthzEnv env, CIDAO<AuthzTrans> cidao, int minRefresh) {
			this.env = env;
			this.cidao = cidao;
			this.minRefresh = minRefresh;
			lastRun = System.currentTimeMillis()-maxRefresh-1000;
		}
		
		@Override
		public void run() {
			// Evaluate whether to refresh based on transaction rate
			long now = System.currentTimeMillis();
			long interval = now-lastRun;

			if(interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return;
			lastRun = now;
			AuthzTrans trans = env.newTransNoAvg();
			Result<Void> rv = cidao.check(trans);
			if(rv.status!=Result.OK) {
				env.error().log("Error in CacheInfo Refresh",rv.details);
			}
			if(env.debug().isLoggable()) {
				StringBuilder sb = new StringBuilder("Cache Info Refresh: ");
				trans.auditTrail(0, sb, Env.REMOTE);
				env.debug().log(sb);
			}
		}
	}
}