-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
InfinispanSessionDataStore.java
279 lines (248 loc) · 9.06 KB
/
InfinispanSessionDataStore.java
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.session.infinispan;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.server.session.AbstractSessionDataStore;
import org.eclipse.jetty.server.session.SessionData;
import org.eclipse.jetty.server.session.UnreadableSessionDataException;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.infinispan.commons.api.BasicCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* InfinispanSessionDataStore
*
*
*/
@ManagedObject
public class InfinispanSessionDataStore extends AbstractSessionDataStore
{
private static final Logger LOG = LoggerFactory.getLogger(InfinispanSessionDataStore.class);
/**
* Clustered cache of sessions
*/
private BasicCache<String, InfinispanSessionData> _cache;
private int _infinispanIdleTimeoutSec;
private QueryManager _queryManager;
private boolean _passivating;
/**
* Get the clustered cache instance.
*
* @return the cache
*/
public BasicCache<String, InfinispanSessionData> getCache()
{
return _cache;
}
/**
* Set the clustered cache instance.
*
* @param cache the cache
*/
public void setCache(BasicCache<String, InfinispanSessionData> cache)
{
this._cache = cache;
}
@Override
protected void doStart() throws Exception
{
super.doStart();
if (_cache == null)
throw new IllegalStateException("No cache");
try
{
_passivating = false;
Class<?> remoteClass = InfinispanSessionDataStore.class.getClassLoader().loadClass("org.infinispan.client.hotrod.RemoteCache");
if (remoteClass.isAssignableFrom(_cache.getClass()))
_passivating = true;
}
catch (ClassNotFoundException e)
{
//expected if not running with remote cache
LOG.info("Hotrod classes not found, assuming infinispan in embedded mode");
}
}
public QueryManager getQueryManager()
{
return _queryManager;
}
public void setQueryManager(QueryManager queryManager)
{
_queryManager = queryManager;
}
@Override
public SessionData doLoad(String id) throws Exception
{
try
{
if (LOG.isDebugEnabled())
LOG.debug("Loading session {} from infinispan", id);
InfinispanSessionData sd = _cache.get(getCacheKey(id));
if (isPassivating() && sd != null)
{
if (LOG.isDebugEnabled())
LOG.debug("Deserializing session attributes for {}", id);
sd.deserializeAttributes();
}
return sd;
}
catch (Exception e)
{
throw new UnreadableSessionDataException(id, _context, e);
}
}
@Override
public boolean delete(String id) throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Deleting session with id {} from infinispan", id);
return (_cache.remove(getCacheKey(id)) != null);
}
@Override
public Set<String> doCheckExpired(Set<String> candidates, long time)
{
if (candidates == null || candidates.isEmpty())
return candidates;
Set<String> expired = new HashSet<>();
for (String candidate:candidates)
{
if (LOG.isDebugEnabled())
LOG.debug("Checking expiry for candidate {}", candidate);
try
{
SessionData sd = load(candidate);
//if the session no longer exists
if (sd == null)
{
expired.add(candidate);
if (LOG.isDebugEnabled())
LOG.debug("Session {} does not exist in infinispan", candidate);
}
else
{
if (_context.getWorkerName().equals(sd.getLastNode()))
{
//we are its manager, add it to the expired set if it is expired now
if ((sd.getExpiry() > 0) && sd.getExpiry() <= time)
{
expired.add(candidate);
if (LOG.isDebugEnabled())
LOG.debug("Session {} managed by {} is expired", candidate, _context.getWorkerName());
}
}
}
}
catch (Exception e)
{
LOG.warn("Error checking if candidate {} is expired", candidate, e);
}
}
return expired;
}
@Override
public Set<String> doGetExpired(long time)
{
//If there is a query manager, find the sessions for our context that expired before the time limit
if (_queryManager != null)
{
Set<String> expired = new HashSet<>();
for (String sessionId : _queryManager.queryExpiredSessions(_context, time))
{
expired.add(sessionId);
if (LOG.isDebugEnabled())
LOG.debug("{}- Found expired sessionId={}", _context.getWorkerName(), sessionId);
}
return expired;
}
return Collections.emptySet();
}
@Override
public void doCleanOrphans(long timeLimit)
{
//if there is a query manager, find the sessions for any context that expired before the time limit and delete
if (_queryManager != null)
_queryManager.deleteOrphanSessions(timeLimit);
else
if (LOG.isDebugEnabled())
LOG.debug("Unable to clean orphans, no QueryManager");
}
@Override
public void doStore(String id, SessionData data, long lastSaveTime) throws Exception
{
//Put an idle timeout on the cache entry if the session is not immortal -
//if no requests arrive at any node before this timeout occurs, or no node
//scavenges the session before this timeout occurs, the session will be removed.
//NOTE: that no session listeners can be called for this.
if (data.getMaxInactiveMs() > 0 && getInfinispanIdleTimeoutSec() > 0)
_cache.put(getCacheKey(id), (InfinispanSessionData)data, -1, TimeUnit.MILLISECONDS, getInfinispanIdleTimeoutSec(), TimeUnit.SECONDS);
else
_cache.put(getCacheKey(id), (InfinispanSessionData)data);
if (LOG.isDebugEnabled())
LOG.debug("Session {} saved to infinispan, expires {} ", id, data.getExpiry());
}
public String getCacheKey(String id)
{
return InfinispanKeyBuilder.build(_context.getCanonicalContextPath(), _context.getVhost(), id);
}
@ManagedAttribute(value = "does store serialize sessions", readonly = true)
@Override
public boolean isPassivating()
{
return _passivating;
}
@Override
public boolean doExists(String id) throws Exception
{
//if we have a query manager we can do a query with a projection to check
//if there is an unexpired session with the given id
if (_queryManager != null)
return _queryManager.exists(_context, id);
else
{
//no query manager, load the entire session data object
SessionData sd = doLoad(id);
if (sd == null)
return false;
if (sd.getExpiry() <= 0)
return true;
else
return (sd.getExpiry() > System.currentTimeMillis()); //not expired yet
}
}
@Override
public SessionData newSessionData(String id, long created, long accessed, long lastAccessed, long maxInactiveMs)
{
return new InfinispanSessionData(id, _context.getCanonicalContextPath(), _context.getVhost(), created, accessed, lastAccessed, maxInactiveMs);
}
/**
* @param sec the infinispan-specific idle timeout in sec or 0 if not set
*/
public void setInfinispanIdleTimeoutSec(int sec)
{
_infinispanIdleTimeoutSec = sec;
}
@ManagedAttribute(value = "infinispan idle timeout sec", readonly = true)
public int getInfinispanIdleTimeoutSec()
{
return _infinispanIdleTimeoutSec;
}
@Override
public String toString()
{
return String.format("%s[cache=%s,idleTimeoutSec=%d]", super.toString(), (_cache == null ? "" : _cache.getName()), _infinispanIdleTimeoutSec);
}
}