-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
GCloudSessionDataStore.java
1057 lines (946 loc) · 32.3 KB
/
GCloudSessionDataStore.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// 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.gcloud.session;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.cloud.datastore.Blob;
import com.google.cloud.datastore.BlobValue;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreException;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;
import com.google.cloud.datastore.KeyFactory;
import com.google.cloud.datastore.ProjectionEntity;
import com.google.cloud.datastore.Query;
import com.google.cloud.datastore.QueryResults;
import com.google.cloud.datastore.StructuredQuery.CompositeFilter;
import com.google.cloud.datastore.StructuredQuery.PropertyFilter;
import org.eclipse.jetty.server.session.AbstractSessionDataStore;
import org.eclipse.jetty.server.session.SessionContext;
import org.eclipse.jetty.server.session.SessionData;
import org.eclipse.jetty.server.session.UnreadableSessionDataException;
import org.eclipse.jetty.server.session.UnwriteableSessionDataException;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* GCloudSessionDataStore
*/
@ManagedObject
public class GCloudSessionDataStore extends AbstractSessionDataStore
{
private static final Logger LOG = LoggerFactory.getLogger(GCloudSessionDataStore.class);
public static final int DEFAULT_MAX_QUERY_RESULTS = 100;
public static final int DEFAULT_MAX_RETRIES = 5;
public static final int DEFAULT_BACKOFF_MS = 1000;
public static final String DEFAULT_NAMESPACE = "";
protected Datastore _datastore;
protected KeyFactory _keyFactory;
protected int _maxResults = DEFAULT_MAX_QUERY_RESULTS;
protected int _maxRetries = DEFAULT_MAX_RETRIES;
protected int _backoff = DEFAULT_BACKOFF_MS;
protected boolean _dsProvided = false;
protected boolean _indexesPresent = false;
protected EntityDataModel _model;
protected boolean _modelProvided;
private String _namespace = DEFAULT_NAMESPACE;
/**
* EntityDataModel
*
* Names of type of Entity and Entity properties for sessions.
*/
public static class EntityDataModel
{
public static final String ID = "id";
public static final String CONTEXTPATH = "contextPath";
public static final String VHOST = "vhost";
public static final String ACCESSED = "accessed";
public static final String LASTACCESSED = "lastAccessed";
public static final String CREATETIME = "createTime";
public static final String COOKIESETTIME = "cookieSetTime";
public static final String LASTNODE = "lastNode";
public static final String EXPIRY = "expiry";
public static final String MAXINACTIVE = "maxInactive";
public static final String ATTRIBUTES = "attributes";
public static final String LASTSAVED = "lastSaved";
public static final String KIND = "GCloudSession";
protected String _kind = KIND;
protected String _id = ID;
protected String _contextPath = CONTEXTPATH;
protected String _vhost = VHOST;
protected String _accessed = ACCESSED;
protected String _lastAccessed = LASTACCESSED;
protected String _lastNode = LASTNODE;
protected String _lastSaved = LASTSAVED;
protected String _createTime = CREATETIME;
protected String _cookieSetTime = COOKIESETTIME;
protected String _expiry = EXPIRY;
protected String _maxInactive = MAXINACTIVE;
protected String _attributes = ATTRIBUTES;
private void checkNotNull(String s)
{
if (s == null)
throw new IllegalArgumentException(s);
}
/**
* @return the lastNode
*/
public String getLastNode()
{
return _lastNode;
}
/**
* @param lastNode the lastNode to set
*/
public void setLastNode(String lastNode)
{
_lastNode = lastNode;
}
/**
* @return the kind
*/
public String getKind()
{
return _kind;
}
/**
* @param kind the kind to set
*/
public void setKind(String kind)
{
checkNotNull(kind);
_kind = kind;
}
/**
* @return the id
*/
public String getId()
{
return _id;
}
/**
* @param id the id to set
*/
public void setId(String id)
{
checkNotNull(id);
_id = id;
}
/**
* @return the contextPath
*/
public String getContextPath()
{
return _contextPath;
}
/**
* @param contextPath the contextPath to set
*/
public void setContextPath(String contextPath)
{
checkNotNull(contextPath);
_contextPath = contextPath;
}
/**
* @return the vhost
*/
public String getVhost()
{
return _vhost;
}
/**
* @param vhost the vhost to set
*/
public void setVhost(String vhost)
{
checkNotNull(vhost);
_vhost = vhost;
}
/**
* @return the accessed
*/
public String getAccessed()
{
return _accessed;
}
/**
* @param accessed the accessed to set
*/
public void setAccessed(String accessed)
{
checkNotNull(accessed);
_accessed = accessed;
}
/**
* @return the lastAccessed
*/
public String getLastAccessed()
{
return _lastAccessed;
}
/**
* @param lastAccessed the lastAccessed to set
*/
public void setLastAccessed(String lastAccessed)
{
checkNotNull(lastAccessed);
_lastAccessed = lastAccessed;
}
/**
* @return the createTime
*/
public String getCreateTime()
{
return _createTime;
}
/**
* @param createTime the createTime to set
*/
public void setCreateTime(String createTime)
{
checkNotNull(createTime);
_createTime = createTime;
}
/**
* @return the cookieSetTime
*/
public String getCookieSetTime()
{
return _cookieSetTime;
}
/**
* @param cookieSetTime the cookieSetTime to set
*/
public void setCookieSetTime(String cookieSetTime)
{
checkNotNull(cookieSetTime);
_cookieSetTime = cookieSetTime;
}
/**
* @return the expiry
*/
public String getExpiry()
{
return _expiry;
}
/**
* @param expiry the expiry to set
*/
public void setExpiry(String expiry)
{
checkNotNull(expiry);
_expiry = expiry;
}
/**
* @return the maxInactive
*/
public String getMaxInactive()
{
return _maxInactive;
}
/**
* @param maxInactive the maxInactive to set
*/
public void setMaxInactive(String maxInactive)
{
checkNotNull(maxInactive);
_maxInactive = maxInactive;
}
/**
* @return the attributes
*/
public String getAttributes()
{
return _attributes;
}
/**
* @param attributes the attributes to set
*/
public void setAttributes(String attributes)
{
checkNotNull(attributes);
_attributes = attributes;
}
/**
* @return the lastSaved
*/
public String getLastSaved()
{
return _lastSaved;
}
/**
* @param lastSaved the lastSaved to set
*/
public void setLastSaved(String lastSaved)
{
checkNotNull(lastSaved);
_lastSaved = lastSaved;
}
@Override
public String toString()
{
return String.format("%s==%s:%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", this.getClass().getName(),
_kind, _accessed, _attributes, _contextPath, _cookieSetTime, _createTime, _expiry, _id, _lastAccessed, _lastNode, _maxInactive, _vhost);
}
}
/**
* ExpiryInfo
*
* Information related to session expiry
*/
public static class ExpiryInfo
{
String _id;
String _lastNode;
String _contextPath;
String _vhost;
long _expiry;
/**
* @param id session id
* @param lastNode last node id to manage the session
* @param expiry timestamp of expiry
* @param contextPath context path for session
* @param vhost vhost of context for session
*/
public ExpiryInfo(String id, String lastNode, long expiry, String contextPath, String vhost)
{
_id = id;
_lastNode = lastNode;
_expiry = expiry;
_contextPath = contextPath;
_vhost = vhost;
}
/**
* @return the id
*/
public String getId()
{
return _id;
}
/**
* @return the lastNode
*/
public String getLastNode()
{
return _lastNode;
}
/**
* @return the expiry time
*/
public long getExpiry()
{
return _expiry;
}
public String getContextPath()
{
return _contextPath;
}
public void setContextPath(String contextPath)
{
_contextPath = contextPath;
}
public String getVhost()
{
return _vhost;
}
public void setVhost(String vhost)
{
_vhost = vhost;
}
}
public void setEntityDataModel(EntityDataModel model)
{
updateBean(_model, model);
_model = model;
_modelProvided = true;
}
public EntityDataModel getEntityDataModel()
{
return _model;
}
public void setBackoffMs(int ms)
{
_backoff = ms;
}
public void setNamespace(String namespace)
{
_namespace = namespace;
}
@ManagedAttribute(value = "gcloud namespace", readonly = true)
public String getNamespace()
{
return _namespace;
}
@ManagedAttribute(value = "unit in ms of exponential backoff")
public int getBackoffMs()
{
return _backoff;
}
public void setMaxRetries(int retries)
{
_maxRetries = retries;
}
@ManagedAttribute(value = "max number of retries for failed writes")
public int getMaxRetries()
{
return _maxRetries;
}
@Override
protected void doStart() throws Exception
{
if (!_dsProvided)
{
if (!StringUtil.isBlank(getNamespace()))
_datastore = DatastoreOptions.newBuilder().setNamespace(getNamespace()).build().getService();
else
_datastore = DatastoreOptions.getDefaultInstance().getService();
}
if (_model == null)
{
_model = new EntityDataModel();
addBean(_model, true);
}
_keyFactory = _datastore.newKeyFactory().setKind(_model.getKind());
_indexesPresent = checkIndexes();
if (!_indexesPresent)
LOG.warn("Session indexes not uploaded, falling back to less efficient queries");
super.doStart();
}
@Override
protected void doStop() throws Exception
{
super.doStop();
if (!_dsProvided)
_datastore = null;
if (!_modelProvided)
_model = null;
}
public void setDatastore(Datastore datastore)
{
_datastore = datastore;
_dsProvided = true;
}
@ManagedAttribute(value = "max number of results to return from gcloud searches")
public int getMaxResults()
{
return _maxResults;
}
public void setMaxResults(int maxResults)
{
if (_maxResults <= 0)
_maxResults = DEFAULT_MAX_QUERY_RESULTS;
else
_maxResults = maxResults;
}
@Override
public SessionData doLoad(String id) throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Loading session {} from DataStore", id);
try
{
Entity entity = _datastore.get(makeKey(id, _context));
if (entity == null)
{
if (LOG.isDebugEnabled())
LOG.debug("No session {} in DataStore ", id);
return null;
}
else
{
return sessionFromEntity(entity);
}
}
catch (Exception e)
{
throw new UnreadableSessionDataException(id, _context, e);
}
}
@Override
public boolean delete(String id) throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Removing session {} from DataStore", id);
_datastore.delete(makeKey(id, _context));
return true;
}
@Override
public Set<String> doCheckExpired(Set<String> candidates, long time)
{
Set<String> expired = new HashSet<String>();
try
{
Set<ExpiryInfo> info = null;
if (_indexesPresent)
info = queryExpiryByIndex(time);
else
info = queryExpiryByEntity(time);
for (ExpiryInfo item : info)
{
if (StringUtil.isBlank(item.getLastNode()) || !(_context.getWorkerName().equals(item.getLastNode())))
continue; //we're not its manager so skip it
if (StringUtil.isBlank(item.getContextPath()) || !(_context.getCanonicalContextPath().equals(item.getContextPath())))
continue; // session is not for this context
expired.add(item.getId());
}
//reconcile against ids that the SessionCache thinks are expired
Set<String> tmp = new HashSet<String>(candidates);
tmp.removeAll(expired);
if (!tmp.isEmpty())
{
//sessioncache thinks these are expired, but they are either no
//longer in the db or not expired in the db, or we exceeded the
//number of records retrieved by the expiry query, so check them
//individually
for (String s : tmp)
{
try
{
Query<Key> q = Query.newKeyQueryBuilder()
.setKind(_model.getKind())
.setFilter(PropertyFilter.eq(_model.getId(), s))
.build();
QueryResults<Key> res = _datastore.run(q);
if (!res.hasNext())
expired.add(s); //not in db, can be expired
}
catch (Exception e)
{
LOG.warn("Unable to expire candidate sessions individually", e);
}
}
}
return expired;
}
catch (Exception e)
{
LOG.warn("Unable to get expired", e);
return expired; //return what we got
}
}
@Override
public Set<String> doGetExpired(long time)
{
// Get sessions managed by any node that expired at or before the given
// time limit
Set<String> expired = new HashSet<String>();
try
{
Set<ExpiryInfo> info = null;
if (_indexesPresent)
info = queryExpiryByIndex(time);
else
info = queryExpiryByEntity(time);
for (ExpiryInfo item:info)
{
expired.add(item.getId());
}
return expired;
}
catch (Exception e)
{
LOG.warn("Error querying expired sessions", e);
return expired; //return what we got
}
}
@Override
public void doCleanOrphans(long timeLimit)
{
// Gcloud datastore does not support DELETE statements with query params.
// Therefore need to do a query, and then a separate operation to delete keys
//returned.
try
{
Set<ExpiryInfo> info = null;
if (_indexesPresent)
info = queryExpiryByIndex(timeLimit);
else
info = queryExpiryByEntity(timeLimit);
//iterate over each of the returned infos,
//make a key for each, then do the delete
Set<Key> keys = info.stream().map(i ->
{
return makeKey(i.getId(), i.getContextPath(), i.getVhost());
}).collect(Collectors.toSet());
_datastore.delete(keys.toArray(new Key[keys.size()]));
}
catch (Exception e)
{
LOG.warn("Error deleting orphaned sessions", e);
}
}
/**
* A less efficient query to find sessions whose expiry time has passed:
* retrieves the whole Entity.
*
* @return set of ExpiryInfo representing the id, lastNode and expiry time of
* sessions that are expired
* @throws Exception if datastore experiences a problem
*/
protected Set<ExpiryInfo> queryExpiryByEntity() throws Exception
{
return queryExpiryByEntity(System.currentTimeMillis());
}
/**
* A less efficient query to find sessions whose expiry time is before the
* given timeLimit.
*
* @param timeLimit time since the epoch
*
* @return set of ExpiryInfo representing the id,lastNode and expiry time
* @throws Exception
*/
protected Set<ExpiryInfo> queryExpiryByEntity(long timeLimit) throws Exception
{
Set<ExpiryInfo> infos = new HashSet<>();
//get up to maxResult number of sessions that have expired
Query<Entity> query = Query.newEntityQueryBuilder()
.setKind(_model.getKind())
.setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), timeLimit)))
.setLimit(_maxResults)
.build();
QueryResults<Entity> results;
if (LOG.isDebugEnabled())
{
long start = System.currentTimeMillis();
results = _datastore.run(query);
LOG.debug("Expiry query no index in {}ms", System.currentTimeMillis() - start);
}
else
results = _datastore.run(query);
while (results.hasNext())
{
Entity entity = results.next();
ExpiryInfo info = new ExpiryInfo(entity.getString(_model.getId()),
entity.getString(_model.getLastNode()),
entity.getLong(_model.getExpiry()),
entity.getString(_model.getContextPath()),
entity.getString(_model.getVhost()));
infos.add(info);
}
return infos;
}
/**
* An efficient query to find sessions whose expiry time has passed:
* uses a projection query, which requires indexes to be uploaded.
*
* @return id, lastnode and expiry time of sessions that have expired
* @throws Exception if datastore experiences a problem
*/
protected Set<ExpiryInfo> queryExpiryByIndex() throws Exception
{
return queryExpiryByIndex(System.currentTimeMillis());
}
/**
* An efficient query to find sessions whose expiry time is before the given timeLimit:
* uses a projection query, which requires indexes to be uploaded.
*
* @param timeLimit the upper limit of expiry time to check
* @return id,lastnode and expiry time of sessions that have expired
* @throws Exception
*/
protected Set<ExpiryInfo> queryExpiryByIndex(long timeLimit) throws Exception
{
Set<ExpiryInfo> infos = new HashSet<>();
Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
.setKind(_model.getKind())
.setProjection(_model.getId(), _model.getLastNode(), _model.getExpiry(), _model.getContextPath(), _model.getVhost())
.setFilter(CompositeFilter.and(PropertyFilter.gt(_model.getExpiry(), 0), PropertyFilter.le(_model.getExpiry(), timeLimit)))
.setLimit(_maxResults)
.build();
QueryResults<ProjectionEntity> presults;
if (LOG.isDebugEnabled())
{
long start = System.currentTimeMillis();
presults = _datastore.run(query);
LOG.debug("Expiry query by index in {}ms", System.currentTimeMillis() - start);
}
else
presults = _datastore.run(query);
while (presults.hasNext())
{
ProjectionEntity pe = presults.next();
ExpiryInfo info = new ExpiryInfo(pe.getString(_model.getId()),
pe.getString(_model.getLastNode()),
pe.getLong(_model.getExpiry()),
pe.getString(_model.getContextPath()),
pe.getString(_model.getVhost()));
infos.add(info);
}
return infos;
}
@Override
public boolean doExists(String id) throws Exception
{
if (_indexesPresent)
{
Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
.setKind(_model.getKind())
.setProjection(_model.getExpiry())
.setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id),
PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()),
PropertyFilter.eq(_model.getVhost(), _context.getVhost())))
//.setFilter(PropertyFilter.eq(_model.getId(), id))
.build();
QueryResults<ProjectionEntity> presults;
if (LOG.isDebugEnabled())
{
long start = System.currentTimeMillis();
presults = _datastore.run(query);
LOG.debug("Exists query by index in {}ms", System.currentTimeMillis() - start);
}
else
presults = _datastore.run(query);
if (presults.hasNext())
{
ProjectionEntity pe = presults.next();
return !isExpired(pe.getLong(_model.getExpiry()));
}
else
return false;
}
else
{
Query<Entity> query = Query.newEntityQueryBuilder()
.setKind(_model.getKind())
.setFilter(CompositeFilter.and(PropertyFilter.eq(_model.getId(), id),
PropertyFilter.eq(_model.getContextPath(), _context.getCanonicalContextPath()),
PropertyFilter.eq(_model.getVhost(), _context.getVhost())))
//.setFilter(PropertyFilter.eq(_model.getId(), id))
.build();
QueryResults<Entity> results;
if (LOG.isDebugEnabled())
{
long start = System.currentTimeMillis();
results = _datastore.run(query);
LOG.debug("Exists query no index in {}ms", System.currentTimeMillis() - start);
}
else
results = _datastore.run(query);
if (results.hasNext())
{
Entity entity = results.next();
return !isExpired(entity.getLong(_model.getExpiry()));
}
else
return false;
}
}
/**
* Check to see if the given time is in the past.
*
* @param timestamp the time to check
* @return false if the timestamp is 0 or less, true if it is in the past
*/
protected boolean isExpired(long timestamp)
{
if (timestamp <= 0)
return false;
else
return timestamp < System.currentTimeMillis();
}
@Override
public void doStore(String id, SessionData data, long lastSaveTime) throws Exception
{
if (LOG.isDebugEnabled())
LOG.debug("Writing session {} to DataStore", data.getId());
Entity entity = entityFromSession(data, makeKey(id, _context));
//attempt the update with exponential back-off
int backoff = getBackoffMs();
int attempts;
for (attempts = 0; attempts < getMaxRetries(); attempts++)
{
try
{
_datastore.put(entity);
return;
}
catch (DatastoreException e)
{
if (e.isRetryable())
{
if (LOG.isDebugEnabled())
LOG.debug(String.format("Datastore put retry=%s backoff=%s", attempts, backoff), e);
try
{
Thread.currentThread().sleep(backoff);
}
catch (InterruptedException ignored)
{
}
backoff *= 2;
}
else
{
throw e;
}
}
}
//retries have been exceeded
throw new UnwriteableSessionDataException(id, _context, null);
}
/**
* Make a unique key for this session.
* As the same session id can be used across multiple contexts, to
* make it unique, the key must be composed of:
* <ol>
* <li>the id</li>
* <li>the context path</li>
* <li>the virtual hosts</li>
* </ol>
*
* @param id the id
* @param context the session context
* @return the key
*/
protected Key makeKey(String id, SessionContext context)
{
return makeKey(id, context.getCanonicalContextPath(), context.getVhost());
}
protected Key makeKey(String id, String canonicalContextPath, String canonicalVHost)
{
String key = canonicalContextPath + "_" + canonicalVHost + "_" + id;
return _keyFactory.newKey(key);
}
/**
* Check to see if indexes are available, in which case
* we can do more performant queries.
*
* @return <code>true</code> if indexes are available
*/
protected boolean checkIndexes()
{
try
{
Query<ProjectionEntity> query = Query.newProjectionEntityQueryBuilder()
.setKind(_model.getKind())
.setProjection(_model.getExpiry())
.setFilter(PropertyFilter.eq(_model.getId(), "-"))
.build();
_datastore.run(query);
return true;
}
catch (DatastoreException e)
{
//need to assume that the problem is the index doesn't exist, because there
//is no specific code for that
if (LOG.isDebugEnabled())
LOG.debug("Check for indexes", e);
return false;
}
}
/**
* Generate a gcloud datastore Entity from SessionData
*
* @param session the session data
* @param key the key
* @return the entity
* @throws Exception if there is a deserialization error
*/
protected Entity entityFromSession(SessionData session, Key key) throws Exception
{
if (session == null)
return null;
Entity entity = null;
//serialize the attribute map
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos))
{
SessionData.serializeAttributes(session, oos);
//turn a session into an entity
entity = Entity.newBuilder(key)
.set(_model.getId(), session.getId())
.set(_model.getContextPath(), session.getContextPath())
.set(_model.getVhost(), session.getVhost())
.set(_model.getAccessed(), session.getAccessed())
.set(_model.getLastAccessed(), session.getLastAccessed())
.set(_model.getCreateTime(), session.getCreated())
.set(_model.getCookieSetTime(), session.getCookieSet())
.set(_model.getLastNode(), session.getLastNode())
.set(_model.getExpiry(), session.getExpiry())
.set(_model.getMaxInactive(), session.getMaxInactiveMs())
.set(_model.getLastSaved(), session.getLastSaved())
.set(_model.getAttributes(), BlobValue.newBuilder(Blob.copyFrom(baos.toByteArray())).setExcludeFromIndexes(true).build()).build();
return entity;
}
}
/**
* Generate SessionData from an Entity retrieved from gcloud datastore.
*
* @param entity the entity
* @return the session data
* @throws Exception if unable to get the entity
*/
protected SessionData sessionFromEntity(Entity entity) throws Exception
{
if (entity == null)
return null;