This repository has been archived by the owner on Jan 5, 2022. It is now read-only.
/
CpRelationManager.java
2434 lines (1844 loc) · 97.2 KB
/
CpRelationManager.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 2014 The Apache Software Foundation.
*
* 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.
*/
package org.apache.usergrid.corepersistence;
import java.nio.ByteBuffer;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.usergrid.persistence.core.future.BetterFuture;
import org.apache.usergrid.persistence.index.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.apache.usergrid.corepersistence.results.ResultsLoader;
import org.apache.usergrid.corepersistence.results.ResultsLoaderFactory;
import org.apache.usergrid.corepersistence.results.ResultsLoaderFactoryImpl;
import org.apache.usergrid.corepersistence.util.CpEntityMapUtils;
import org.apache.usergrid.corepersistence.util.CpNamingUtils;
import org.apache.usergrid.persistence.ConnectedEntityRef;
import org.apache.usergrid.persistence.ConnectionRef;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityManager;
import org.apache.usergrid.persistence.EntityRef;
import org.apache.usergrid.persistence.IndexBucketLocator;
import org.apache.usergrid.persistence.PagingResultsIterator;
import org.apache.usergrid.persistence.RelationManager;
import org.apache.usergrid.persistence.Results;
import org.apache.usergrid.persistence.RoleRef;
import org.apache.usergrid.persistence.Schema;
import org.apache.usergrid.persistence.SimpleEntityRef;
import org.apache.usergrid.persistence.SimpleRoleRef;
import org.apache.usergrid.persistence.cassandra.CassandraService;
import org.apache.usergrid.persistence.cassandra.ConnectionRefImpl;
import org.apache.usergrid.persistence.cassandra.IndexUpdate;
import org.apache.usergrid.persistence.cassandra.QueryProcessorImpl;
import org.apache.usergrid.persistence.cassandra.index.ConnectedIndexScanner;
import org.apache.usergrid.persistence.cassandra.index.IndexBucketScanner;
import org.apache.usergrid.persistence.cassandra.index.IndexScanner;
import org.apache.usergrid.persistence.cassandra.index.NoOpIndexScanner;
import org.apache.usergrid.persistence.collection.CollectionScope;
import org.apache.usergrid.persistence.core.metrics.MetricsFactory;
import org.apache.usergrid.persistence.core.scope.ApplicationScope;
import org.apache.usergrid.persistence.entities.Group;
import org.apache.usergrid.persistence.entities.User;
import org.apache.usergrid.persistence.geo.ConnectionGeoSearch;
import org.apache.usergrid.persistence.geo.EntityLocationRef;
import org.apache.usergrid.persistence.geo.model.Point;
import org.apache.usergrid.persistence.graph.Edge;
import org.apache.usergrid.persistence.graph.GraphManager;
import org.apache.usergrid.persistence.graph.SearchByEdgeType;
import org.apache.usergrid.persistence.graph.impl.SimpleEdge;
import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdge;
import org.apache.usergrid.persistence.graph.impl.SimpleSearchByEdgeType;
import org.apache.usergrid.persistence.graph.impl.SimpleSearchEdgeType;
import org.apache.usergrid.persistence.index.impl.IndexScopeImpl;
import org.apache.usergrid.persistence.index.query.CandidateResult;
import org.apache.usergrid.persistence.index.query.CandidateResults;
import org.apache.usergrid.persistence.index.query.Identifier;
import org.apache.usergrid.persistence.index.query.Query;
import org.apache.usergrid.persistence.index.query.Query.Level;
import org.apache.usergrid.persistence.model.entity.Id;
import org.apache.usergrid.persistence.model.entity.SimpleId;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import org.apache.usergrid.persistence.query.ir.AllNode;
import org.apache.usergrid.persistence.query.ir.NameIdentifierNode;
import org.apache.usergrid.persistence.query.ir.QueryNode;
import org.apache.usergrid.persistence.query.ir.QuerySlice;
import org.apache.usergrid.persistence.query.ir.SearchVisitor;
import org.apache.usergrid.persistence.query.ir.WithinNode;
import org.apache.usergrid.persistence.query.ir.result.ConnectionIndexSliceParser;
import org.apache.usergrid.persistence.query.ir.result.ConnectionResultsLoaderFactory;
import org.apache.usergrid.persistence.query.ir.result.ConnectionTypesIterator;
import org.apache.usergrid.persistence.query.ir.result.EmptyIterator;
import org.apache.usergrid.persistence.query.ir.result.GeoIterator;
import org.apache.usergrid.persistence.query.ir.result.SliceIterator;
import org.apache.usergrid.persistence.query.ir.result.StaticIdIterator;
import org.apache.usergrid.persistence.schema.CollectionInfo;
import org.apache.usergrid.utils.IndexUtils;
import org.apache.usergrid.utils.MapUtils;
import org.apache.usergrid.utils.UUIDUtils;
import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.DynamicComposite;
import me.prettyprint.hector.api.beans.HColumn;
import me.prettyprint.hector.api.mutation.Mutator;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import static java.util.Arrays.asList;
import static me.prettyprint.hector.api.factory.HFactory.createMutator;
import static org.apache.usergrid.corepersistence.util.CpNamingUtils.getCollectionScopeNameFromEntityType;
import static org.apache.usergrid.persistence.Schema.COLLECTION_ROLES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_CONNECTED_ENTITIES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_CONNECTED_TYPES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_CONNECTING_ENTITIES;
import static org.apache.usergrid.persistence.Schema.DICTIONARY_CONNECTING_TYPES;
import static org.apache.usergrid.persistence.Schema.INDEX_CONNECTIONS;
import static org.apache.usergrid.persistence.Schema.PROPERTY_CREATED;
import static org.apache.usergrid.persistence.Schema.PROPERTY_INACTIVITY;
import static org.apache.usergrid.persistence.Schema.PROPERTY_NAME;
import static org.apache.usergrid.persistence.Schema.PROPERTY_TITLE;
import static org.apache.usergrid.persistence.Schema.TYPE_APPLICATION;
import static org.apache.usergrid.persistence.Schema.TYPE_ENTITY;
import static org.apache.usergrid.persistence.Schema.TYPE_ROLE;
import static org.apache.usergrid.persistence.Schema.getDefaultSchema;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_COMPOSITE_DICTIONARIES;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_DICTIONARIES;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_INDEX;
import static org.apache.usergrid.persistence.cassandra.ApplicationCF.ENTITY_INDEX_ENTRIES;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addDeleteToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.addInsertToMutator;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.batchExecute;
import static org.apache.usergrid.persistence.cassandra.CassandraPersistenceUtils.key;
import static org.apache.usergrid.persistence.cassandra.CassandraService.INDEX_ENTRY_LIST_COUNT;
import static org.apache.usergrid.persistence.cassandra.GeoIndexManager.batchDeleteLocationInConnectionsIndex;
import static org.apache.usergrid.persistence.cassandra.GeoIndexManager.batchRemoveLocationFromCollectionIndex;
import static org.apache.usergrid.persistence.cassandra.GeoIndexManager.batchStoreLocationInCollectionIndex;
import static org.apache.usergrid.persistence.cassandra.GeoIndexManager.batchStoreLocationInConnectionsIndex;
import static org.apache.usergrid.persistence.cassandra.IndexUpdate.indexValueCode;
import static org.apache.usergrid.persistence.cassandra.IndexUpdate.toIndexableValue;
import static org.apache.usergrid.persistence.cassandra.IndexUpdate.validIndexableValue;
import static org.apache.usergrid.persistence.cassandra.Serializers.be;
import static org.apache.usergrid.utils.ClassUtils.cast;
import static org.apache.usergrid.utils.CompositeUtils.setGreaterThanEqualityFlag;
import static org.apache.usergrid.utils.InflectionUtils.singularize;
import static org.apache.usergrid.utils.MapUtils.addMapSet;
import static org.apache.usergrid.utils.UUIDUtils.getTimestampInMicros;
/**
* Implement good-old Usergrid RelationManager with the new-fangled Core Persistence API.
*/
public class CpRelationManager implements RelationManager {
private static final Logger logger = LoggerFactory.getLogger( CpRelationManager.class );
private CpEntityManagerFactory emf;
private ManagerCache managerCache;
private EntityManager em;
private UUID applicationId;
private EntityRef headEntity;
private org.apache.usergrid.persistence.model.entity.Entity cpHeadEntity;
private ApplicationScope applicationScope;
private CollectionScope headEntityScope;
private CassandraService cass;
private IndexBucketLocator indexBucketLocator;
private ResultsLoaderFactory resultsLoaderFactory;
private MetricsFactory metricsFactory;
private Timer updateCollectionTimer;
private Timer createConnectionTimer;
private Timer cassConnectionDelete;
private Timer esDeleteConnectionTimer;
public CpRelationManager() {}
public CpRelationManager init(
EntityManager em,
CpEntityManagerFactory emf,
UUID applicationId,
EntityRef headEntity,
IndexBucketLocator indexBucketLocator,
MetricsFactory metricsFactory) {
Assert.notNull( em, "Entity manager cannot be null" );
Assert.notNull( emf, "Entity manager factory cannot be null" );
Assert.notNull( applicationId, "Application Id cannot be null" );
Assert.notNull( headEntity, "Head entity cannot be null" );
Assert.notNull( headEntity.getUuid(), "Head entity uuid cannot be null" );
// TODO: this assert should not be failing
//Assert.notNull( indexBucketLocator, "indexBucketLocator cannot be null" );
this.em = em;
this.emf = emf;
this.applicationId = applicationId;
this.headEntity = headEntity;
this.managerCache = emf.getManagerCache();
this.applicationScope = CpNamingUtils.getApplicationScope( applicationId );
this.cass = em.getCass(); // TODO: eliminate need for this via Core Persistence
this.indexBucketLocator = indexBucketLocator; // TODO: this also
this.metricsFactory = metricsFactory;
this.updateCollectionTimer = metricsFactory
.getTimer( CpRelationManager.class, "relation.manager.es.update.collection" );
this.createConnectionTimer = metricsFactory
.getTimer( CpRelationManager.class, "relation.manager.es.create.connection.timer" );
this.cassConnectionDelete = metricsFactory
.getTimer( CpRelationManager.class, "relation.manager.cassandra.delete.connection.batch.timer" );
this.esDeleteConnectionTimer = metricsFactory.getTimer(CpRelationManager.class, "relation.manager.es.delete.connection.batch.timer" );
// load the Core Persistence version of the head entity as well
this.headEntityScope = getCollectionScopeNameFromEntityType(
applicationScope.getApplication(), headEntity.getType());
if ( logger.isDebugEnabled() ) {
logger.debug( "Loading head entity {}:{} from scope\n app {}\n owner {}\n name {}",
new Object[] {
headEntity.getType(),
headEntity.getUuid(),
headEntityScope.getApplication(),
headEntityScope.getOwner(),
headEntityScope.getName()
} );
}
Id entityId = new SimpleId( headEntity.getUuid(), headEntity.getType() );
// if(headEntity instanceof Entity){
// cpHeadEntity = entityToCpEntity( (Entity)headEntity, headEntity.getUuid() );
// }else {
this.cpHeadEntity =
( ( CpEntityManager ) em ).load( new CpEntityManager.EntityScope( headEntityScope, entityId ) );
// }
// commented out because it is possible that CP entity has not been created yet
Assert.notNull( cpHeadEntity, "cpHeadEntity cannot be null" );
this.resultsLoaderFactory = new ResultsLoaderFactoryImpl( managerCache );
return this;
}
@Override
public Set<String> getCollectionIndexes( String collectionName ) throws Exception {
final Set<String> indexes = new HashSet<String>();
GraphManager gm = managerCache.getGraphManager(applicationScope);
String edgeTypePrefix = CpNamingUtils.getEdgeTypeFromCollectionName( collectionName );
logger.debug("getCollectionIndexes(): Searching for edge type prefix {} to target {}:{}",
new Object[] {
edgeTypePrefix, cpHeadEntity.getId().getType(), cpHeadEntity.getId().getUuid()
});
Observable<String> types= gm.getEdgeTypesFromSource(
new SimpleSearchEdgeType( cpHeadEntity.getId(), edgeTypePrefix, null ));
Iterator<String> iter = types.toBlockingObservable().getIterator();
while ( iter.hasNext() ) {
indexes.add( iter.next() );
}
return indexes;
}
@Override
public Map<String, Map<UUID, Set<String>>> getOwners() throws Exception {
// TODO: do we need to restrict this to edges prefixed with owns?
//Map<EntityRef, Set<String>> containerEntities = getContainers(-1, "owns", null);
Map<EntityRef, Set<String>> containerEntities = getContainers();
Map<String, Map<UUID, Set<String>>> owners =
new LinkedHashMap<String, Map<UUID, Set<String>>>();
for ( EntityRef owner : containerEntities.keySet() ) {
Set<String> collections = containerEntities.get( owner );
for ( String collection : collections ) {
MapUtils.addMapMapSet( owners, owner.getType(), owner.getUuid(), collection );
}
}
return owners;
}
private Map<EntityRef, Set<String>> getContainers() {
return getContainers( -1, null, null );
}
/**
* Gets containing collections and/or connections depending on the edge type you pass in
* @param limit Max number to return
* @param edgeType Edge type, edge type prefix or null to allow any edge type
* @param fromEntityType Only consider edges from entities of this type
*/
Map<EntityRef, Set<String>> getContainers( int limit, String edgeType, String fromEntityType ) {
Map<EntityRef, Set<String>> results = new LinkedHashMap<EntityRef, Set<String>>();
GraphManager gm = managerCache.getGraphManager(applicationScope);
Iterator<String> edgeTypes = gm.getEdgeTypesToTarget( new SimpleSearchEdgeType(
cpHeadEntity.getId(), edgeType, null) ).toBlocking().getIterator();
logger.debug("getContainers(): "
+ "Searched for edges of type {}\n to target {}:{}\n in scope {}\n found: {}",
new Object[] {
edgeType,
cpHeadEntity.getId().getType(),
cpHeadEntity.getId().getUuid(),
applicationScope.getApplication(),
edgeTypes.hasNext()
});
while ( edgeTypes.hasNext() ) {
String etype = edgeTypes.next();
Observable<Edge> edges = gm.loadEdgesToTarget( new SimpleSearchByEdgeType(
cpHeadEntity.getId(), etype, Long.MAX_VALUE, SearchByEdgeType.Order.DESCENDING, null ));
Iterator<Edge> iter = edges.toBlockingObservable().getIterator();
while ( iter.hasNext() ) {
Edge edge = iter.next();
if ( fromEntityType != null && !fromEntityType.equals( edge.getSourceNode().getType() )) {
logger.debug("Ignoring edge from entity type {}", edge.getSourceNode().getType());
continue;
}
EntityRef eref = new SimpleEntityRef(
edge.getSourceNode().getType(), edge.getSourceNode().getUuid() );
String name = null;
if ( CpNamingUtils.isConnectionEdgeType( edge.getType() )) {
name = CpNamingUtils.getConnectionType( edge.getType() );
} else {
name = CpNamingUtils.getCollectionName( edge.getType() );
}
addMapSet( results, eref, name );
}
if ( limit > 0 && results.keySet().size() >= limit ) {
break;
}
}
return results;
}
public void updateContainingCollectionAndCollectionIndexes(
final org.apache.usergrid.persistence.model.entity.Entity cpEntity ) {
final GraphManager gm = managerCache.getGraphManager( applicationScope );
Iterator<String> edgeTypesToTarget = gm.getEdgeTypesToTarget( new SimpleSearchEdgeType(
cpHeadEntity.getId(), null, null) ).toBlockingObservable().getIterator();
logger.debug("updateContainingCollectionsAndCollections(): "
+ "Searched for edges to target {}:{}\n in scope {}\n found: {}",
new Object[] {
cpHeadEntity.getId().getType(),
cpHeadEntity.getId().getUuid(),
applicationScope.getApplication(),
edgeTypesToTarget.hasNext()
});
// loop through all types of edge to target
final ApplicationEntityIndex ei = managerCache.getEntityIndex(applicationScope);
final EntityIndexBatch entityIndexBatch = ei.createBatch();
final int count = gm.getEdgeTypesToTarget(
new SimpleSearchEdgeType( cpHeadEntity.getId(), null, null ) )
// for each edge type, emit all the edges of that type
.flatMap( new Func1<String, Observable<Edge>>() {
@Override
public Observable<Edge> call( final String etype ) {
return gm.loadEdgesToTarget( new SimpleSearchByEdgeType(
cpHeadEntity.getId(), etype, Long.MAX_VALUE,
SearchByEdgeType.Order.DESCENDING, null ) );
}
} )
//for each edge we receive index and add to the batch
.doOnNext( new Action1<Edge>() {
@Override
public void call( final Edge edge ) {
EntityRef sourceEntity =
new SimpleEntityRef( edge.getSourceNode().getType(), edge.getSourceNode().getUuid() );
// reindex the entity in the source entity's collection or connection index
IndexScope indexScope;
if ( CpNamingUtils.isCollectionEdgeType( edge.getType() ) ) {
String collName = CpNamingUtils.getCollectionName( edge.getType() );
indexScope = new IndexScopeImpl(
new SimpleId( sourceEntity.getUuid(), sourceEntity.getType()),
CpNamingUtils.getCollectionScopeNameFromCollectionName( collName ));
}
else {
String connName = CpNamingUtils.getConnectionType( edge.getType() );
indexScope = new IndexScopeImpl(
new SimpleId( sourceEntity.getUuid(), sourceEntity.getType() ),
CpNamingUtils.getConnectionScopeName( connName ) );
}
entityIndexBatch.index( indexScope, cpEntity );
// reindex the entity in the source entity's all-types index
//TODO REMOVE INDEX CODE
// indexScope = new IndexScopeImpl( new SimpleId(
// sourceEntity.getUuid(), sourceEntity.getType() ), CpNamingUtils
// .ALL_TYPES, entityType );
//
// entityIndexBatch.index( indexScope, cpEntity );
}
} ).count().toBlocking().lastOrDefault( 0 );
//Adding graphite metrics
Timer.Context timeElasticIndexBatch = updateCollectionTimer.time();
entityIndexBatch.execute();
timeElasticIndexBatch.stop();
logger.debug( "updateContainingCollectionsAndCollections() updated {} indexes", count );
}
@Override
public boolean isConnectionMember( String connectionType, EntityRef entity ) throws Exception {
Id entityId = new SimpleId( entity.getUuid(), entity.getType() );
String edgeType = CpNamingUtils.getEdgeTypeFromConnectionType( connectionType );
logger.debug("isConnectionMember(): Checking for edge type {} from {}:{} to {}:{}",
new Object[] {
edgeType,
headEntity.getType(), headEntity.getUuid(),
entity.getType(), entity.getUuid() });
GraphManager gm = managerCache.getGraphManager( applicationScope );
Observable<Edge> edges = gm.loadEdgeVersions( new SimpleSearchByEdge(
new SimpleId( headEntity.getUuid(), headEntity.getType() ),
edgeType,
entityId,
Long.MAX_VALUE,
SearchByEdgeType.Order.DESCENDING,
null ) );
return edges.toBlockingObservable().firstOrDefault( null ) != null;
}
@SuppressWarnings( "unchecked" )
@Override
public boolean isCollectionMember( String collName, EntityRef entity ) throws Exception {
Id entityId = new SimpleId( entity.getUuid(), entity.getType() );
String edgeType = CpNamingUtils.getEdgeTypeFromCollectionName( collName );
logger.debug("isCollectionMember(): Checking for edge type {} from {}:{} to {}:{}",
new Object[] {
edgeType,
headEntity.getType(), headEntity.getUuid(),
entity.getType(), entity.getUuid() });
GraphManager gm = managerCache.getGraphManager( applicationScope );
Observable<Edge> edges = gm.loadEdgeVersions( new SimpleSearchByEdge(
new SimpleId( headEntity.getUuid(), headEntity.getType() ),
edgeType,
entityId,
Long.MAX_VALUE,
SearchByEdgeType.Order.DESCENDING,
null ) );
return edges.toBlockingObservable().firstOrDefault( null ) != null;
}
private boolean moreThanOneInboundConnection( EntityRef target, String connectionType ) {
Id targetId = new SimpleId( target.getUuid(), target.getType() );
GraphManager gm = managerCache.getGraphManager( applicationScope );
Observable<Edge> edgesToTarget = gm.loadEdgesToTarget( new SimpleSearchByEdgeType(
targetId,
CpNamingUtils.getEdgeTypeFromConnectionType( connectionType ),
System.currentTimeMillis(),
SearchByEdgeType.Order.DESCENDING,
null ) ); // last
Iterator<Edge> iterator = edgesToTarget.toBlockingObservable().getIterator();
int count = 0;
while ( iterator.hasNext() ) {
iterator.next();
if ( count++ > 1 ) {
return true;
}
}
return false;
}
private boolean moreThanOneOutboundConnection( EntityRef source, String connectionType ) {
Id sourceId = new SimpleId( source.getUuid(), source.getType() );
GraphManager gm = managerCache.getGraphManager( applicationScope );
Observable<Edge> edgesFromSource = gm.loadEdgesFromSource( new SimpleSearchByEdgeType(
sourceId,
CpNamingUtils.getEdgeTypeFromConnectionType( connectionType ),
System.currentTimeMillis(),
SearchByEdgeType.Order.DESCENDING,
null ) ); // last
int count = edgesFromSource.take( 2 ).count().toBlocking().last();
return count > 1;
}
@Override
public Set<String> getCollections() throws Exception {
final Set<String> indexes = new HashSet<String>();
GraphManager gm = managerCache.getGraphManager( applicationScope );
Observable<String> str = gm.getEdgeTypesFromSource(
new SimpleSearchEdgeType( cpHeadEntity.getId(), null, null ) );
Iterator<String> iter = str.toBlockingObservable().getIterator();
while ( iter.hasNext() ) {
String edgeType = iter.next();
indexes.add( CpNamingUtils.getCollectionName( edgeType ) );
}
return indexes;
}
@Override
public Results getCollection( String collectionName,
UUID startResult,
int count,
Level resultsLevel,
boolean reversed ) throws Exception {
Query query = Query.fromQL( "select *" );
query.setLimit( count );
query.setReversed( reversed );
if ( startResult != null ) {
query.addGreaterThanEqualFilter( "created", startResult.timestamp() );
}
return searchCollection( collectionName, query );
}
@Override
public Results getCollection( String collName, Query query, Level level ) throws Exception {
return searchCollection( collName, query );
}
// add to a named collection of the head entity
@Override
public Entity addToCollection( String collName, EntityRef itemRef ) throws Exception {
CollectionInfo collection =
getDefaultSchema().getCollection( headEntity.getType(), collName );
if ( ( collection != null ) && !collection.getType().equals( itemRef.getType() ) ) {
return null;
}
return addToCollection( collName, itemRef,
( collection != null && collection.getLinkedCollection() != null ) );
}
public Entity addToCollection( String collName, EntityRef itemRef, boolean connectBack )
throws Exception {
CollectionScope memberScope = getCollectionScopeNameFromEntityType(
applicationScope.getApplication(), itemRef.getType());
Id entityId = new SimpleId( itemRef.getUuid(), itemRef.getType() );
org.apache.usergrid.persistence.model.entity.Entity memberEntity =
((CpEntityManager)em).load( new CpEntityManager.EntityScope( memberScope, entityId));
return addToCollection(collName, itemRef, memberEntity, connectBack);
}
public Entity addToCollection(final String collName, final EntityRef itemRef,
final org.apache.usergrid.persistence.model.entity.Entity memberEntity, final boolean connectBack )
throws Exception {
// don't fetch entity if we've already got one
final Entity itemEntity;
if ( itemRef instanceof Entity ) {
itemEntity = ( Entity ) itemRef;
}
else {
itemEntity = em.get( itemRef );
}
if ( itemEntity == null ) {
return null;
}
CollectionInfo collection = getDefaultSchema().getCollection( headEntity.getType(), collName );
if ( ( collection != null ) && !collection.getType().equals( itemRef.getType() ) ) {
return null;
}
// load the new member entity to be added to the collection from its default scope
CollectionScope memberScope = getCollectionScopeNameFromEntityType(
applicationScope.getApplication(), itemRef.getType());
//TODO, this double load should disappear once events are in
Id entityId = new SimpleId( itemRef.getUuid(), itemRef.getType() );
if ( memberEntity == null ) {
throw new RuntimeException(
"Unable to load entity uuid=" + itemRef.getUuid() + " type=" + itemRef.getType() );
}
if ( logger.isDebugEnabled() ) {
logger.debug( "Loaded member entity {}:{} from scope\n app {}\n "
+ "owner {}\n name {} data {}",
new Object[] {
itemRef.getType(),
itemRef.getUuid(),
memberScope.getApplication(),
memberScope.getOwner(),
memberScope.getName(),
CpEntityMapUtils.toMap( memberEntity )
} );
}
String edgeType = CpNamingUtils.getEdgeTypeFromCollectionName( collName );
UUID timeStampUuid = memberEntity.getId().getUuid() != null
&& UUIDUtils.isTimeBased( memberEntity.getId().getUuid() )
? memberEntity.getId().getUuid() : UUIDUtils.newTimeUUID();
long uuidHash = UUIDUtils.getUUIDLong( timeStampUuid );
// create graph edge connection from head entity to member entity
Edge edge = new SimpleEdge( cpHeadEntity.getId(), edgeType, memberEntity.getId(), uuidHash );
GraphManager gm = managerCache.getGraphManager( applicationScope );
gm.writeEdge( edge ).toBlockingObservable().last();
logger.debug( "Wrote edgeType {}\n from {}:{}\n to {}:{}\n scope {}:{}",
new Object[] {
edgeType,
cpHeadEntity.getId().getType(),
cpHeadEntity.getId().getUuid(),
memberEntity.getId().getType(),
memberEntity.getId().getUuid(),
applicationScope.getApplication().getType(),
applicationScope.getApplication().getUuid()
} );
( ( CpEntityManager ) em ).indexEntityIntoCollection( cpHeadEntity, memberEntity, collName );
logger.debug( "Added entity {}:{} to collection {}", new Object[] {
itemRef.getUuid().toString(), itemRef.getType(), collName
} );
// logger.debug("With head entity scope is {}:{}:{}", new Object[] {
// headEntityScope.getApplication().toString(),
// headEntityScope.getOwner().toString(),
// headEntityScope.getName()});
if ( connectBack && collection != null && collection.getLinkedCollection() != null ) {
getRelationManager( itemEntity ).addToCollection(
collection.getLinkedCollection(), headEntity, cpHeadEntity, false );
getRelationManager( itemEntity ).addToCollection(
collection.getLinkedCollection(), headEntity, false );
}
return itemEntity;
}
@Override
public Entity addToCollections( List<EntityRef> owners, String collName ) throws Exception {
// TODO: this addToCollections() implementation seems wrong.
for ( EntityRef eref : owners ) {
addToCollection( collName, eref );
}
return null;
}
@Override
public Entity createItemInCollection(
String collName, String itemType, Map<String, Object> properties) throws Exception {
if ( headEntity.getUuid().equals( applicationId ) ) {
if ( itemType.equals( TYPE_ENTITY ) ) {
itemType = singularize( collName );
}
if ( itemType.equals( TYPE_ROLE ) ) {
Long inactivity = ( Long ) properties.get( PROPERTY_INACTIVITY );
if ( inactivity == null ) {
inactivity = 0L;
}
return em.createRole( ( String ) properties.get( PROPERTY_NAME ),
( String ) properties.get( PROPERTY_TITLE ), inactivity );
}
return em.create( itemType, properties );
}
else if ( headEntity.getType().equals( Group.ENTITY_TYPE )
&& ( collName.equals( COLLECTION_ROLES ) ) ) {
UUID groupId = headEntity.getUuid();
String roleName = ( String ) properties.get( PROPERTY_NAME );
return em.createGroupRole( groupId, roleName, ( Long ) properties.get( PROPERTY_INACTIVITY ) );
}
CollectionInfo collection = getDefaultSchema().getCollection( headEntity.getType(), collName );
if ( ( collection != null ) && !collection.getType().equals( itemType ) ) {
return null;
}
properties = getDefaultSchema().cleanUpdatedProperties( itemType, properties, true );
Entity itemEntity = em.create( itemType, properties );
if ( itemEntity != null ) {
addToCollection( collName, itemEntity );
if ( collection != null && collection.getLinkedCollection() != null ) {
getRelationManager( getHeadEntity() )
.addToCollection( collection.getLinkedCollection(), itemEntity );
}
}
return itemEntity;
}
@Override
public void removeFromCollection( String collName, EntityRef itemRef ) throws Exception {
// special handling for roles collection of the application
if ( headEntity.getUuid().equals( applicationId ) ) {
if ( collName.equals( COLLECTION_ROLES ) ) {
Entity itemEntity = em.get( itemRef );
if ( itemEntity != null ) {
RoleRef roleRef = SimpleRoleRef.forRoleEntity( itemEntity );
em.deleteRole( roleRef.getApplicationRoleName() );
return;
}
em.delete( itemEntity );
return;
}
em.delete( itemRef );
return;
}
// load the entity to be removed to the collection
CollectionScope memberScope = getCollectionScopeNameFromEntityType(
applicationScope.getApplication(), itemRef.getType());
if ( logger.isDebugEnabled() ) {
logger.debug( "Loading entity to remove from collection "
+ "{}:{} from scope\n app {}\n owner {}\n name {}",
new Object[] {
itemRef.getType(),
itemRef.getUuid(),
memberScope.getApplication(),
memberScope.getOwner(),
memberScope.getName()
});
}
Id entityId = new SimpleId( itemRef.getUuid(), itemRef.getType() );
org.apache.usergrid.persistence.model.entity.Entity memberEntity =
((CpEntityManager)em).load( new CpEntityManager.EntityScope( memberScope, entityId));
final ApplicationEntityIndex ei = managerCache.getEntityIndex( applicationScope );
final EntityIndexBatch batch = ei.createBatch();
// remove item from collection index
IndexScope indexScope = new IndexScopeImpl(
cpHeadEntity.getId(),
CpNamingUtils.getCollectionScopeNameFromCollectionName( collName ) );
batch.deindex( indexScope, memberEntity );
// remove collection from item index
IndexScope itemScope = new IndexScopeImpl(
memberEntity.getId(),
CpNamingUtils.getCollectionScopeNameFromCollectionName(
Schema.defaultCollectionName( cpHeadEntity.getId().getType() ) ) );
batch.deindex( itemScope, cpHeadEntity );
BetterFuture future = batch.execute();
// remove edge from collection to item
GraphManager gm = managerCache.getGraphManager( applicationScope );
Edge collectionToItemEdge = new SimpleEdge(
cpHeadEntity.getId(),
CpNamingUtils.getEdgeTypeFromCollectionName( collName ),
memberEntity.getId(), UUIDUtils.getUUIDLong( memberEntity.getId().getUuid() ) );
gm.deleteEdge( collectionToItemEdge ).toBlockingObservable().last();
// remove edge from item to collection
Edge itemToCollectionEdge = new SimpleEdge(
memberEntity.getId(),
CpNamingUtils.getEdgeTypeFromCollectionName(
Schema.defaultCollectionName( cpHeadEntity.getId().getType() ) ),
cpHeadEntity.getId(),
UUIDUtils.getUUIDLong( cpHeadEntity.getId().getUuid() ) );
gm.deleteEdge( itemToCollectionEdge ).toBlockingObservable().last();
// special handling for roles collection of a group
if ( headEntity.getType().equals( Group.ENTITY_TYPE ) ) {
if ( collName.equals( COLLECTION_ROLES ) ) {
String path = ( String ) ( ( Entity ) itemRef ).getMetadata( "path" );
if ( path.startsWith( "/roles/" ) ) {
Entity itemEntity = em.get( new SimpleEntityRef( memberEntity.getId().getType(),
memberEntity.getId().getUuid() ) );
RoleRef roleRef = SimpleRoleRef.forRoleEntity( itemEntity );
em.deleteRole( roleRef.getApplicationRoleName() );
}
}
}
}
@Override
public void copyRelationships(String srcRelationName, EntityRef dstEntityRef,
String dstRelationName) throws Exception {
headEntity = em.validate( headEntity );
dstEntityRef = em.validate( dstEntityRef );
CollectionInfo srcCollection =
getDefaultSchema().getCollection( headEntity.getType(), srcRelationName );
CollectionInfo dstCollection =
getDefaultSchema().getCollection( dstEntityRef.getType(), dstRelationName );
Results results = null;
do {
if ( srcCollection != null ) {
results = em.getCollection( headEntity, srcRelationName, null, 5000, Level.REFS, false );
}
else {
results = em.getConnectedEntities( headEntity, srcRelationName, null, Level.REFS );
}
if ( ( results != null ) && ( results.size() > 0 ) ) {
List<EntityRef> refs = results.getRefs();
for ( EntityRef ref : refs ) {
if ( dstCollection != null ) {
em.addToCollection( dstEntityRef, dstRelationName, ref );
}
else {
em.createConnection( dstEntityRef, dstRelationName, ref );
}
}
}
}
while ( ( results != null ) && ( results.hasMoreResults() ) );
}
@Override
public Results searchCollection( String collName, Query query ) throws Exception {
if ( query == null ) {
query = new Query();
query.setCollection( collName );
}
headEntity = em.validate( headEntity );
CollectionInfo collection =
getDefaultSchema().getCollection( headEntity.getType(), collName );
if ( collection == null ) {
throw new RuntimeException( "Cannot find collection-info for '" + collName
+ "' of " + headEntity.getType() + ":" + headEntity .getUuid() );
}
final IndexScope indexScope = new IndexScopeImpl(
cpHeadEntity.getId(),
CpNamingUtils.getCollectionScopeNameFromCollectionName( collName ) );
final ApplicationEntityIndex ei = managerCache.getEntityIndex( applicationScope );
final SearchTypes types = SearchTypes.fromTypes( collection.getType() );
logger.debug( "Searching scope {}:{}",
indexScope.getOwner().toString(), indexScope.getName() );
query.setEntityType( collection.getType() );
query = adjustQuery( query );
// Because of possible stale entities, which are filtered out by buildResults(),
// we loop until the we've got enough results to satisfy the query limit.
int maxQueries = 10; // max re-queries to satisfy query limit
final int originalLimit = query.getLimit();
Results results = null;
int queryCount = 0;
boolean satisfied = false;
while ( !satisfied && queryCount++ < maxQueries ) {
CandidateResults crs = ei.search( indexScope, types, query );
if ( results == null ) {
logger.debug( "Calling build results 1" );
results = buildResults( indexScope, query, crs, collName );
}
else {
logger.debug( "Calling build results 2" );
Results newResults = buildResults(indexScope, query, crs, collName );
results.merge( newResults );
}
if ( crs.isEmpty() || !crs.hasCursor() ) { // no results, no cursor, can't get more
satisfied = true;
}
/**
* In an edge case where we delete stale entities, we could potentially get more results than expected. This will only occur once during the repair phase.
* We need to ensure that we short circuit if we overflow the requested limit during a repair.
*/
else if ( results.size() >= originalLimit ) { // got what we need
satisfied = true;
}
else if ( crs.hasCursor() ) {
satisfied = false;
// need to query for more
// ask for just what we need to satisfy, don't want to exceed limit
query.setCursor( results.getCursor() );