/
EntityRepository.java
2651 lines (2366 loc) · 110 KB
/
EntityRepository.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 2021 Collate
* 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.openmetadata.service.jdbi3;
import static org.openmetadata.common.utils.CommonUtil.listOrEmpty;
import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;
import static org.openmetadata.schema.type.Include.ALL;
import static org.openmetadata.schema.type.Include.DELETED;
import static org.openmetadata.schema.type.Include.NON_DELETED;
import static org.openmetadata.schema.utils.EntityInterfaceUtil.quoteName;
import static org.openmetadata.service.Entity.ADMIN_USER_NAME;
import static org.openmetadata.service.Entity.DATA_PRODUCT;
import static org.openmetadata.service.Entity.DOMAIN;
import static org.openmetadata.service.Entity.FIELD_CHILDREN;
import static org.openmetadata.service.Entity.FIELD_DATA_PRODUCTS;
import static org.openmetadata.service.Entity.FIELD_DELETED;
import static org.openmetadata.service.Entity.FIELD_DESCRIPTION;
import static org.openmetadata.service.Entity.FIELD_DISPLAY_NAME;
import static org.openmetadata.service.Entity.FIELD_DOMAIN;
import static org.openmetadata.service.Entity.FIELD_EXPERTS;
import static org.openmetadata.service.Entity.FIELD_EXTENSION;
import static org.openmetadata.service.Entity.FIELD_FOLLOWERS;
import static org.openmetadata.service.Entity.FIELD_LIFE_CYCLE;
import static org.openmetadata.service.Entity.FIELD_OWNER;
import static org.openmetadata.service.Entity.FIELD_REVIEWERS;
import static org.openmetadata.service.Entity.FIELD_STYLE;
import static org.openmetadata.service.Entity.FIELD_TAGS;
import static org.openmetadata.service.Entity.FIELD_VOTES;
import static org.openmetadata.service.Entity.USER;
import static org.openmetadata.service.Entity.getEntityByName;
import static org.openmetadata.service.Entity.getEntityFields;
import static org.openmetadata.service.exception.CatalogExceptionMessage.csvNotSupported;
import static org.openmetadata.service.exception.CatalogExceptionMessage.entityNotFound;
import static org.openmetadata.service.util.EntityUtil.compareTagLabel;
import static org.openmetadata.service.util.EntityUtil.entityReferenceMatch;
import static org.openmetadata.service.util.EntityUtil.fieldAdded;
import static org.openmetadata.service.util.EntityUtil.fieldDeleted;
import static org.openmetadata.service.util.EntityUtil.fieldUpdated;
import static org.openmetadata.service.util.EntityUtil.getColumnField;
import static org.openmetadata.service.util.EntityUtil.getEntityReferences;
import static org.openmetadata.service.util.EntityUtil.getExtensionField;
import static org.openmetadata.service.util.EntityUtil.getId;
import static org.openmetadata.service.util.EntityUtil.nextMajorVersion;
import static org.openmetadata.service.util.EntityUtil.nextVersion;
import static org.openmetadata.service.util.EntityUtil.objectMatch;
import static org.openmetadata.service.util.EntityUtil.tagLabelMatch;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.networknt.schema.JsonSchema;
import com.networknt.schema.ValidationMessage;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.json.JsonPatch;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.jdbi.v3.sqlobject.transaction.Transaction;
import org.openmetadata.common.utils.CommonUtil;
import org.openmetadata.schema.CreateEntity;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.schema.api.VoteRequest;
import org.openmetadata.schema.api.VoteRequest.VoteType;
import org.openmetadata.schema.api.feed.ResolveTask;
import org.openmetadata.schema.api.teams.CreateTeam;
import org.openmetadata.schema.entity.data.Table;
import org.openmetadata.schema.entity.teams.Team;
import org.openmetadata.schema.entity.teams.User;
import org.openmetadata.schema.type.ChangeDescription;
import org.openmetadata.schema.type.ChangeEvent;
import org.openmetadata.schema.type.Column;
import org.openmetadata.schema.type.EntityHistory;
import org.openmetadata.schema.type.EntityReference;
import org.openmetadata.schema.type.EventType;
import org.openmetadata.schema.type.Include;
import org.openmetadata.schema.type.LifeCycle;
import org.openmetadata.schema.type.ProviderType;
import org.openmetadata.schema.type.Relationship;
import org.openmetadata.schema.type.TagLabel;
import org.openmetadata.schema.type.TaskType;
import org.openmetadata.schema.type.ThreadType;
import org.openmetadata.schema.type.Votes;
import org.openmetadata.schema.type.csv.CsvImportResult;
import org.openmetadata.schema.utils.EntityInterfaceUtil;
import org.openmetadata.service.Entity;
import org.openmetadata.service.OpenMetadataApplicationConfig;
import org.openmetadata.service.TypeRegistry;
import org.openmetadata.service.exception.CatalogExceptionMessage;
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.exception.UnhandledServerException;
import org.openmetadata.service.jdbi3.CollectionDAO.EntityRelationshipRecord;
import org.openmetadata.service.jdbi3.CollectionDAO.EntityVersionPair;
import org.openmetadata.service.jdbi3.CollectionDAO.ExtensionRecord;
import org.openmetadata.service.jdbi3.FeedRepository.TaskWorkflow;
import org.openmetadata.service.jdbi3.FeedRepository.ThreadContext;
import org.openmetadata.service.resources.tags.TagLabelUtil;
import org.openmetadata.service.search.SearchRepository;
import org.openmetadata.service.util.EntityUtil;
import org.openmetadata.service.util.EntityUtil.Fields;
import org.openmetadata.service.util.FullyQualifiedName;
import org.openmetadata.service.util.JsonUtils;
import org.openmetadata.service.util.RestUtil;
import org.openmetadata.service.util.RestUtil.DeleteResponse;
import org.openmetadata.service.util.RestUtil.PatchResponse;
import org.openmetadata.service.util.RestUtil.PutResponse;
import org.openmetadata.service.util.ResultList;
/**
* This is the base class used by Entity Resources to perform READ and WRITE operations to the backend database to
* Create, Retrieve, Update, and Delete entities.
*
* <p>An entity has two types of fields - `attributes` and `relationships`.
*
* <ul>
* <li>The `attributes` are the core properties of the entity, example - entity id, name, fullyQualifiedName, columns
* for a table, etc.
* <li>The `relationships` are an associated between two entities, example - table belongs to a database, table has a
* tag, user owns a table, etc. All relationships are captured using {@code EntityReference}.
* </ul>
*
* Entities are stored as JSON documents in the database. Each entity is stored in a separate table and is accessed
* through a <i>Data Access Object</i> or <i>DAO</i> that corresponds to each of the entity. For example,
* <i>table_entity</i> is the database table used to store JSON docs corresponding to <i>table</i> entity and {@link
* org.openmetadata.service.jdbi3.CollectionDAO.TableDAO} is used as the DAO object to access the table_entity table.
* All DAO objects for an entity are available in {@code daoCollection}. <br>
* <br>
* Relationships between entity is stored in a separate table that captures the edge - fromEntity, toEntity, and the
* relationship name <i>entity_relationship</i> table and are supported by {@link
* org.openmetadata.service.jdbi3.CollectionDAO.EntityRelationshipDAO} DAO object.
*
* <p>JSON document of an entity stores only <i>required</i> attributes of an entity. Some attributes such as
* <i>href</i> are not stored and are created on the fly. <br>
* <br>
* Json document of an entity does not store relationships. As an example, JSON document for <i>table</i> entity does
* not store the relationship <i>database</i> which is of type <i>EntityReference</i>. This is always retrieved from the
* relationship table when required to ensure, the data stored is efficiently and consistently, and relationship
* information does not become stale.
*/
@Slf4j
@Repository()
public abstract class EntityRepository<T extends EntityInterface> {
public static final LoadingCache<Pair<String, String>, EntityInterface> CACHE_WITH_NAME =
CacheBuilder.newBuilder()
.maximumSize(5000)
.expireAfterWrite(30, TimeUnit.SECONDS)
.recordStats()
.build(new EntityLoaderWithName());
public static final LoadingCache<Pair<String, UUID>, EntityInterface> CACHE_WITH_ID =
CacheBuilder.newBuilder()
.maximumSize(5000)
.expireAfterWrite(30, TimeUnit.SECONDS)
.recordStats()
.build(new EntityLoaderWithId());
private final String collectionPath;
private final Class<T> entityClass;
@Getter protected final String entityType;
@Getter protected final EntityDAO<T> dao;
@Getter protected final CollectionDAO daoCollection;
@Getter protected final SearchRepository searchRepository;
@Getter protected final Set<String> allowedFields;
public final boolean supportsSoftDelete;
@Getter protected final boolean supportsTags;
@Getter protected final boolean supportsOwner;
@Getter protected final boolean supportsStyle;
@Getter protected final boolean supportsLifeCycle;
protected final boolean supportsFollower;
protected final boolean supportsExtension;
protected final boolean supportsVotes;
@Getter protected final boolean supportsDomain;
protected final boolean supportsDataProducts;
@Getter protected final boolean supportsReviewers;
@Getter protected final boolean supportsExperts;
protected boolean quoteFqn = false; // Entity FQNS not hierarchical such user, teams, services need to be quoted
protected boolean renameAllowed = false; // Entity can be renamed
/** Fields that can be updated during PATCH operation */
@Getter private final Fields patchFields;
/** Fields that can be updated during PUT operation */
@Getter protected final Fields putFields;
protected boolean supportsSearch = false;
protected EntityRepository(
String collectionPath,
String entityType,
Class<T> entityClass,
EntityDAO<T> entityDAO,
String patchFields,
String putFields) {
this.collectionPath = collectionPath;
this.entityClass = entityClass;
allowedFields = getEntityFields(entityClass);
this.dao = entityDAO;
this.daoCollection = Entity.getCollectionDAO();
this.searchRepository = Entity.getSearchRepository();
this.entityType = entityType;
this.patchFields = getFields(patchFields);
this.putFields = getFields(putFields);
this.supportsTags = allowedFields.contains(FIELD_TAGS);
if (supportsTags) {
this.patchFields.addField(allowedFields, FIELD_TAGS);
this.putFields.addField(allowedFields, FIELD_TAGS);
}
this.supportsOwner = allowedFields.contains(FIELD_OWNER);
if (supportsOwner) {
this.patchFields.addField(allowedFields, FIELD_OWNER);
this.putFields.addField(allowedFields, FIELD_OWNER);
}
this.supportsSoftDelete = allowedFields.contains(FIELD_DELETED);
this.supportsFollower = allowedFields.contains(FIELD_FOLLOWERS);
if (supportsFollower) {
this.patchFields.addField(allowedFields, FIELD_FOLLOWERS);
this.putFields.addField(allowedFields, FIELD_FOLLOWERS);
}
this.supportsExtension = allowedFields.contains(FIELD_EXTENSION);
if (supportsExtension) {
this.patchFields.addField(allowedFields, FIELD_EXTENSION);
this.putFields.addField(allowedFields, FIELD_EXTENSION);
}
this.supportsVotes = allowedFields.contains(FIELD_VOTES);
if (supportsVotes) {
this.patchFields.addField(allowedFields, FIELD_VOTES);
this.putFields.addField(allowedFields, FIELD_VOTES);
}
this.supportsDomain = allowedFields.contains(FIELD_DOMAIN);
if (supportsDomain) {
this.patchFields.addField(allowedFields, FIELD_DOMAIN);
this.putFields.addField(allowedFields, FIELD_DOMAIN);
}
this.supportsReviewers = allowedFields.contains(FIELD_REVIEWERS);
if (supportsReviewers) {
this.patchFields.addField(allowedFields, FIELD_REVIEWERS);
this.putFields.addField(allowedFields, FIELD_REVIEWERS);
}
this.supportsExperts = allowedFields.contains(FIELD_EXPERTS);
if (supportsExperts) {
this.patchFields.addField(allowedFields, FIELD_EXPERTS);
this.putFields.addField(allowedFields, FIELD_EXPERTS);
}
this.supportsDataProducts = allowedFields.contains(FIELD_DATA_PRODUCTS);
if (supportsDataProducts) {
this.patchFields.addField(allowedFields, FIELD_DATA_PRODUCTS);
this.putFields.addField(allowedFields, FIELD_DATA_PRODUCTS);
}
this.supportsStyle = allowedFields.contains(FIELD_STYLE);
if (supportsStyle) {
this.patchFields.addField(allowedFields, FIELD_STYLE);
this.putFields.addField(allowedFields, FIELD_STYLE);
}
this.supportsLifeCycle = allowedFields.contains(FIELD_LIFE_CYCLE);
if (supportsLifeCycle) {
this.patchFields.addField(allowedFields, FIELD_LIFE_CYCLE);
this.putFields.addField(allowedFields, FIELD_LIFE_CYCLE);
}
Entity.registerEntity(entityClass, entityType, this);
}
/**
* Set the requested fields in an entity. This is used for requesting specific fields in the object during GET
* operations. It is also used during PUT and PATCH operations to set up fields that can be updated.
*/
public abstract void setFields(T entity, Fields fields);
/**
* Set the requested fields in an entity. This is used for requesting specific fields in the object during GET
* operations. It is also used during PUT and PATCH operations to set up fields that can be updated.
*/
public abstract void clearFields(T entity, Fields fields);
/**
* This method is used for validating an entity to be created during POST, PUT, and PATCH operations and prepare the
* entity with all the required attributes and relationships.
*
* <p>The implementation of this method must perform the following:
*
* <ol>
* <li>Prepare the values for attributes that are not required in the request but can be derived on the server side.
* Example - <i>>FullyQualifiedNames</i> of an entity can be derived from the hierarchy that an entity belongs
* to .
* <li>Validate all the attributes of an entity.
* <li>Validate all the relationships of an entity. As an example - during <i>table</i> creation, relationships such
* as <i>Tags</i>, <i>Owner</i>, <i>Database</i>a table belongs to are validated. During validation additional
* information that is not required in the create/update request are set up in the corresponding relationship
* fields.
* </ol>
*
* At the end of this operation, entity is expected to be valid and fully constructed with all the fields that will be
* sent as payload in the POST, PUT, and PATCH operations response.
*
* @see TableRepository#prepare(Table, boolean) for an example implementation
*/
public abstract void prepare(T entity, boolean update);
/**
* An entity is stored in the backend database as JSON document. The JSON includes some attributes of the entity and
* does not include attributes such as <i>href</i>. The relationship fields of an entity is never stored in the JSON
* document. It is always reconstructed based on relationship edges from the backend database. <br>
* <br>
* As an example, when <i>table</i> entity is stored, the attributes such as <i>href</i> and the relationships such as
* <i>owner</i>, <i>database</i>, and <i>tags</i> are set to null. These attributes are restored back after the JSON
* document is stored to be sent as response.
*
* @see TableRepository#storeEntity(Table, boolean) for an example implementation
*/
public abstract void storeEntity(T entity, boolean update);
/**
* This method is called to store all the relationships of an entity. It is expected that all relationships are
* already validated and completely setup before this method is called and no validation of relationships is required.
*
* @see TableRepository#storeRelationships(Table) for an example implementation
*/
public abstract void storeRelationships(T entity);
/**
* This method is called to set inherited fields that an entity inherits from its parent.
*
* @see TableRepository#setInheritedFields(Table, Fields) for an example implementation
*/
@SuppressWarnings("unused")
public T setInheritedFields(T entity, Fields fields) {
EntityInterface parent = supportsDomain ? getParentEntity(entity, "domain") : null;
return parent != null ? inheritDomain(entity, fields, parent) : entity;
}
/**
* PATCH operations can't overwrite certain fields, such as entity ID, fullyQualifiedNames etc. Instead of throwing an
* error, we take lenient approach of ignoring the user error and restore those attributes based on what is already
* stored in the original entity.
*/
public void restorePatchAttributes(T original, T updated) {
updated.setId(original.getId());
updated.setName(renameAllowed ? updated.getName() : original.getName());
updated.setFullyQualifiedName(original.getFullyQualifiedName());
updated.setChangeDescription(original.getChangeDescription());
}
/** Set fullyQualifiedName of an entity */
public void setFullyQualifiedName(T entity) {
entity.setFullyQualifiedName(quoteName(entity.getName()));
}
/**
* Initialize data from json files if seed data does not exist in corresponding tables. Seed data is stored under
* openmetadata-service/src/main/resources/json/data/{entityType}
*
* <p>This method needs to be explicitly called, typically from initialize method. See {@link
* org.openmetadata.service.resources.teams.RoleResource#initialize(OpenMetadataApplicationConfig)}
*/
public void initSeedDataFromResources() throws IOException {
List<T> entities = getEntitiesFromSeedData();
for (T entity : entities) {
initializeEntity(entity);
}
}
public List<T> getEntitiesFromSeedData() throws IOException {
return getEntitiesFromSeedData(String.format(".*json/data/%s/.*\\.json$", entityType));
}
public List<T> getEntitiesFromSeedData(String path) throws IOException {
return getEntitiesFromSeedData(entityType, path, entityClass);
}
public static <U> List<U> getEntitiesFromSeedData(String entityType, String path, Class<U> clazz) throws IOException {
List<U> entities = new ArrayList<>();
List<String> jsonDataFiles = EntityUtil.getJsonDataResources(path);
jsonDataFiles.forEach(
jsonDataFile -> {
try {
String json = CommonUtil.getResourceAsStream(EntityRepository.class.getClassLoader(), jsonDataFile);
json = json.replace("<separator>", Entity.SEPARATOR);
entities.add(JsonUtils.readValue(json, clazz));
} catch (Exception e) {
LOG.warn("Failed to initialize the {} from file {}", entityType, jsonDataFile, e);
}
});
return entities;
}
/** Initialize a given entity if it does not exist. */
@Transaction
public void initializeEntity(T entity) {
T existingEntity = findByNameOrNull(entity.getFullyQualifiedName(), ALL);
if (existingEntity != null) {
LOG.info("{} {} is already initialized", entityType, entity.getFullyQualifiedName());
return;
}
LOG.info("{} {} is not initialized", entityType, entity.getFullyQualifiedName());
entity.setUpdatedBy(ADMIN_USER_NAME);
entity.setUpdatedAt(System.currentTimeMillis());
entity.setId(UUID.randomUUID());
create(null, entity);
LOG.info("Created a new {} {}", entityType, entity.getFullyQualifiedName());
}
public final T copy(T entity, CreateEntity request, String updatedBy) {
EntityReference owner = validateOwner(request.getOwner());
EntityReference domain = validateDomain(request.getDomain());
entity.setId(UUID.randomUUID());
entity.setName(request.getName());
entity.setDisplayName(request.getDisplayName());
entity.setDescription(request.getDescription());
entity.setOwner(owner);
entity.setDomain(domain);
entity.setTags(request.getTags());
entity.setDataProducts(getEntityReferences(Entity.DATA_PRODUCT, request.getDataProducts()));
entity.setLifeCycle(request.getLifeCycle());
entity.setExtension(request.getExtension());
entity.setUpdatedBy(updatedBy);
entity.setUpdatedAt(System.currentTimeMillis());
return entity;
}
public EntityUpdater getUpdater(T original, T updated, Operation operation) {
return new EntityUpdater(original, updated, operation);
}
public final T get(UriInfo uriInfo, UUID id, Fields fields) {
return get(uriInfo, id, fields, NON_DELETED, false);
}
/** Used for getting an entity with a set of requested fields */
public final T get(UriInfo uriInfo, UUID id, Fields fields, Include include, boolean fromCache) {
if (!fromCache) {
// Clear the cache and always get the entity from the database to ensure read-after-write consistency
CACHE_WITH_ID.invalidate(new ImmutablePair<>(entityType, id));
}
// Find the entity from the cache. Set all the fields that are not already set
T entity = find(id, include);
setFieldsInternal(entity, fields);
setInheritedFields(entity, fields);
// Clone the entity from the cache and reset all the fields that are not already set
// Cloning is necessary to ensure different threads making a call to this method don't
// overwrite the fields of the entity being returned
T entityClone = JsonUtils.deepCopy(entity, entityClass);
clearFieldsInternal(entityClone, fields);
return withHref(uriInfo, entityClone);
}
/** getReference is used for getting the entity references from the entity in the cache. */
public final EntityReference getReference(UUID id, Include include) throws EntityNotFoundException {
return find(id, include).getEntityReference();
}
/**
* Find method is used for getting an entity only with core fields stored as JSON without any relational fields set
*/
public T find(UUID id, Include include) throws EntityNotFoundException {
try {
@SuppressWarnings("unchecked")
T entity = (T) CACHE_WITH_ID.get(new ImmutablePair<>(entityType, id));
if (include == NON_DELETED && Boolean.TRUE.equals(entity.getDeleted())
|| include == DELETED && !Boolean.TRUE.equals(entity.getDeleted())) {
throw new EntityNotFoundException(entityNotFound(entityType, id));
}
return entity;
} catch (ExecutionException | UncheckedExecutionException e) {
throw new EntityNotFoundException(entityNotFound(entityType, id));
}
}
public T getByName(UriInfo uriInfo, String fqn, Fields fields) {
return getByName(uriInfo, fqn, fields, NON_DELETED, false);
}
public final T getByName(UriInfo uriInfo, String fqn, Fields fields, Include include, boolean fromCache) {
fqn = quoteFqn ? EntityInterfaceUtil.quoteName(fqn) : fqn;
if (!fromCache) {
// Clear the cache and always get the entity from the database to ensure read-after-write consistency
CACHE_WITH_NAME.invalidate(new ImmutablePair<>(entityType, fqn));
}
// Find the entity from the cache. Set all the fields that are not already set
T entity = findByName(fqn, include);
setFieldsInternal(entity, fields);
setInheritedFields(entity, fields);
// Clone the entity from the cache and reset all the fields that are not already set
// Cloning is necessary to ensure different threads making a call to this method don't
// overwrite the fields of the entity being returned
T entityClone = JsonUtils.deepCopy(entity, entityClass);
clearFieldsInternal(entityClone, fields);
return withHref(uriInfo, entityClone);
}
public final EntityReference getReferenceByName(String fqn, Include include) {
fqn = quoteFqn ? EntityInterfaceUtil.quoteName(fqn) : fqn;
return findByName(fqn, include).getEntityReference();
}
public T findByNameOrNull(String fqn, Include include) {
try {
return findByName(fqn, include);
} catch (EntityNotFoundException e) {
return null;
}
}
/**
* Find method is used for getting an entity only with core fields stored as JSON without any relational fields set
*/
public T findByName(String fqn, Include include) {
fqn = quoteFqn ? EntityInterfaceUtil.quoteName(fqn) : fqn;
try {
@SuppressWarnings("unchecked")
T entity = (T) CACHE_WITH_NAME.get(new ImmutablePair<>(entityType, fqn));
if (include == NON_DELETED && Boolean.TRUE.equals(entity.getDeleted())
|| include == DELETED && !Boolean.TRUE.equals(entity.getDeleted())) {
throw new EntityNotFoundException(entityNotFound(entityType, fqn));
}
return entity;
} catch (ExecutionException | UncheckedExecutionException e) {
throw new EntityNotFoundException(entityNotFound(entityType, fqn));
}
}
public final List<T> listAll(Fields fields, ListFilter filter) {
// forward scrolling, if after == null then first page is being asked
List<String> jsons = dao.listAfter(filter, Integer.MAX_VALUE, "");
List<T> entities = new ArrayList<>();
for (String json : jsons) {
T entity = setFieldsInternal(JsonUtils.readValue(json, entityClass), fields);
entity = clearFieldsInternal(entity, fields);
entities.add(entity);
}
return entities;
}
public ResultList<T> listAfter(UriInfo uriInfo, Fields fields, ListFilter filter, int limitParam, String after) {
int total = dao.listCount(filter);
List<T> entities = new ArrayList<>();
if (limitParam > 0) {
// forward scrolling, if after == null then first page is being asked
List<String> jsons = dao.listAfter(filter, limitParam + 1, after == null ? "" : RestUtil.decodeCursor(after));
for (String json : jsons) {
T entity = setFieldsInternal(JsonUtils.readValue(json, entityClass), fields);
entity = clearFieldsInternal(entity, fields);
entities.add(withHref(uriInfo, entity));
}
String beforeCursor;
String afterCursor = null;
beforeCursor = after == null ? null : entities.get(0).getName();
if (entities.size() > limitParam) { // If extra result exists, then next page exists - return after cursor
entities.remove(limitParam);
afterCursor = entities.get(limitParam - 1).getName();
}
return getResultList(entities, beforeCursor, afterCursor, total);
} else {
// limit == 0 , return total count of entity.
return getResultList(entities, null, null, total);
}
}
public ResultList<T> listAfterWithSkipFailure(
UriInfo uriInfo, Fields fields, ListFilter filter, int limitParam, String after) {
List<String> errors = new ArrayList<>();
List<T> entities = new ArrayList<>();
int beforeOffset = Integer.parseInt(RestUtil.decodeCursor(after));
int currentOffset = beforeOffset;
int total = dao.listCount(filter);
if (limitParam > 0) {
// forward scrolling, if after == null then first page is being asked
List<String> jsons = dao.listAfterWithOffset(limitParam, currentOffset);
for (String json : jsons) {
try {
T entity = setFieldsInternal(JsonUtils.readValue(json, entityClass), fields);
entity = clearFieldsInternal(entity, fields);
entities.add(withHref(uriInfo, entity));
} catch (Exception e) {
LOG.error("Failed in Set Fields for Entity with Json : {}", json);
errors.add(String.format("Error Message : %s , %n Entity Json : %s", e.getMessage(), json));
}
}
currentOffset = currentOffset + limitParam;
String newAfter = currentOffset > total ? null : String.valueOf(currentOffset);
return getResultList(entities, errors, String.valueOf(beforeOffset), newAfter, total);
} else {
// limit == 0 , return total count of entity.
return getResultList(entities, errors, null, null, total);
}
}
public ResultList<T> listBefore(UriInfo uriInfo, Fields fields, ListFilter filter, int limitParam, String before) {
// Reverse scrolling - Get one extra result used for computing before cursor
List<String> jsons = dao.listBefore(filter, limitParam + 1, RestUtil.decodeCursor(before));
List<T> entities = new ArrayList<>();
for (String json : jsons) {
T entity = setFieldsInternal(JsonUtils.readValue(json, entityClass), fields);
entity = clearFieldsInternal(entity, fields);
entities.add(withHref(uriInfo, entity));
}
int total = dao.listCount(filter);
String beforeCursor = null;
String afterCursor;
if (entities.size() > limitParam) { // If extra result exists, then previous page exists - return before cursor
entities.remove(0);
beforeCursor = entities.get(0).getName();
}
afterCursor = entities.get(entities.size() - 1).getName();
return getResultList(entities, beforeCursor, afterCursor, total);
}
public T getVersion(UUID id, String version) {
Double requestedVersion = Double.parseDouble(version);
String extension = EntityUtil.getVersionExtension(entityType, requestedVersion);
// Get previous version from version history
String json = daoCollection.entityExtensionDAO().getExtension(id, extension);
if (json != null) {
return JsonUtils.readValue(json, entityClass);
}
// If requested the latest version, return it from current version of the entity
T entity = setFieldsInternal(find(id, ALL), putFields);
if (entity.getVersion().equals(requestedVersion)) {
return entity;
}
throw EntityNotFoundException.byMessage(
CatalogExceptionMessage.entityVersionNotFound(entityType, id, requestedVersion));
}
public EntityHistory listVersions(UUID id) {
T latest = setFieldsInternal(find(id, ALL), putFields);
String extensionPrefix = EntityUtil.getVersionExtensionPrefix(entityType);
List<ExtensionRecord> records = daoCollection.entityExtensionDAO().getExtensions(id, extensionPrefix);
List<EntityVersionPair> oldVersions = new ArrayList<>();
records.forEach(r -> oldVersions.add(new EntityVersionPair(r)));
oldVersions.sort(EntityUtil.compareVersion.reversed());
final List<Object> allVersions = new ArrayList<>();
allVersions.add(JsonUtils.pojoToJson(latest));
oldVersions.forEach(version -> allVersions.add(version.getEntityJson()));
return new EntityHistory().withEntityType(entityType).withVersions(allVersions);
}
public final T create(UriInfo uriInfo, T entity) {
entity = withHref(uriInfo, createInternal(entity));
return entity;
}
public final T createInternal(T entity) {
prepareInternal(entity, false);
return createNewEntity(entity);
}
public void prepareInternal(T entity, boolean update) {
validateTags(entity);
prepare(entity, update);
setFullyQualifiedName(entity);
validateExtension(entity);
// Domain is already validated
}
public void storeRelationshipsInternal(T entity) {
storeOwner(entity, entity.getOwner());
applyTags(entity);
storeDomain(entity, entity.getDomain());
storeDataProducts(entity, entity.getDataProducts());
storeRelationships(entity);
}
public T setFieldsInternal(T entity, Fields fields) {
entity.setOwner(fields.contains(FIELD_OWNER) ? getOwner(entity) : entity.getOwner());
entity.setTags(fields.contains(FIELD_TAGS) ? getTags(entity) : entity.getTags());
entity.setExtension(fields.contains(FIELD_EXTENSION) ? getExtension(entity) : entity.getExtension());
entity.setDomain(fields.contains(FIELD_DOMAIN) ? getDomain(entity) : entity.getDomain());
entity.setDataProducts(fields.contains(FIELD_DATA_PRODUCTS) ? getDataProducts(entity) : entity.getDataProducts());
entity.setFollowers(fields.contains(FIELD_FOLLOWERS) ? getFollowers(entity) : entity.getFollowers());
entity.setChildren(fields.contains(FIELD_CHILDREN) ? getChildren(entity) : entity.getChildren());
entity.setExperts(fields.contains(FIELD_EXPERTS) ? getExperts(entity) : entity.getExperts());
entity.setReviewers(fields.contains(FIELD_REVIEWERS) ? getReviewers(entity) : entity.getReviewers());
entity.setVotes(fields.contains(FIELD_VOTES) ? getVotes(entity) : entity.getVotes());
setFields(entity, fields);
return entity;
}
public T clearFieldsInternal(T entity, Fields fields) {
entity.setOwner(fields.contains(FIELD_OWNER) ? entity.getOwner() : null);
entity.setTags(fields.contains(FIELD_TAGS) ? entity.getTags() : null);
entity.setExtension(fields.contains(FIELD_EXTENSION) ? entity.getExtension() : null);
entity.setDomain(fields.contains(FIELD_DOMAIN) ? entity.getDomain() : null);
entity.setDataProducts(fields.contains(FIELD_DATA_PRODUCTS) ? entity.getDataProducts() : null);
entity.setFollowers(fields.contains(FIELD_FOLLOWERS) ? entity.getFollowers() : null);
entity.setChildren(fields.contains(FIELD_CHILDREN) ? entity.getChildren() : null);
entity.setExperts(fields.contains(FIELD_EXPERTS) ? entity.getExperts() : null);
entity.setReviewers(fields.contains(FIELD_REVIEWERS) ? entity.getReviewers() : null);
entity.setVotes(fields.contains(FIELD_VOTES) ? entity.getVotes() : null);
clearFields(entity, fields);
return entity;
}
@Transaction
public final PutResponse<T> createOrUpdate(UriInfo uriInfo, T updated) {
T original = findByNameOrNull(updated.getFullyQualifiedName(), ALL);
if (original == null) { // If an original entity does not exist then create it, else update
return new PutResponse<>(Status.CREATED, withHref(uriInfo, createNewEntity(updated)), RestUtil.ENTITY_CREATED);
}
return update(uriInfo, original, updated);
}
@SuppressWarnings("unused")
protected void postCreate(T entity) {
if (supportsSearch) {
searchRepository.createEntity(entity);
}
}
@SuppressWarnings("unused")
protected void postUpdate(T original, T updated) {
if (supportsSearch) {
searchRepository.updateEntity(updated);
}
}
@Transaction
public PutResponse<T> update(UriInfo uriInfo, T original, T updated) {
// Get all the fields in the original entity that can be updated during PUT operation
setFieldsInternal(original, putFields);
// If the entity state is soft-deleted, recursively undelete the entity and it's children
if (Boolean.TRUE.equals(original.getDeleted())) {
restoreEntity(updated.getUpdatedBy(), entityType, original.getId());
}
// Update the attributes and relationships of an entity
EntityUpdater entityUpdater = getUpdater(original, updated, Operation.PUT);
entityUpdater.update();
String change = entityUpdater.fieldsChanged() ? RestUtil.ENTITY_UPDATED : RestUtil.ENTITY_NO_CHANGE;
setInheritedFields(updated, new Fields(allowedFields));
return new PutResponse<>(Status.OK, withHref(uriInfo, updated), change);
}
@Transaction
public final PatchResponse<T> patch(UriInfo uriInfo, UUID id, String user, JsonPatch patch) {
// Get all the fields in the original entity that can be updated during PATCH operation
T original = setFieldsInternal(find(id, NON_DELETED), patchFields);
setInheritedFields(original, patchFields);
// Apply JSON patch to the original entity to get the updated entity
T updated = JsonUtils.applyPatch(original, patch, entityClass);
updated.setUpdatedBy(user);
updated.setUpdatedAt(System.currentTimeMillis());
prepareInternal(updated, true);
populateOwner(updated.getOwner());
restorePatchAttributes(original, updated);
// Update the attributes and relationships of an entity
EntityUpdater entityUpdater = getUpdater(original, updated, Operation.PATCH);
entityUpdater.update();
String change = RestUtil.ENTITY_NO_CHANGE;
if (entityUpdater.fieldsChanged()) {
change = RestUtil.ENTITY_UPDATED;
setInheritedFields(original, patchFields); // Restore inherited fields after a change
}
return new PatchResponse<>(Status.OK, withHref(uriInfo, updated), change);
}
@Transaction
public PutResponse<T> addFollower(String updatedBy, UUID entityId, UUID userId) {
T entity = find(entityId, NON_DELETED);
// Validate follower
User user = daoCollection.userDAO().findEntityById(userId);
if (Boolean.TRUE.equals(user.getDeleted())) {
throw new IllegalArgumentException(CatalogExceptionMessage.deletedUser(userId));
}
// Add relationship
addRelationship(userId, entityId, Entity.USER, entityType, Relationship.FOLLOWS);
ChangeDescription change = new ChangeDescription().withPreviousVersion(entity.getVersion());
fieldAdded(change, FIELD_FOLLOWERS, List.of(user.getEntityReference()));
ChangeEvent changeEvent =
new ChangeEvent()
.withEntity(entity)
.withChangeDescription(change)
.withEventType(EventType.ENTITY_UPDATED)
.withEntityType(entityType)
.withEntityId(entityId)
.withEntityFullyQualifiedName(entity.getFullyQualifiedName())
.withUserName(updatedBy)
.withTimestamp(System.currentTimeMillis())
.withCurrentVersion(entity.getVersion())
.withPreviousVersion(change.getPreviousVersion());
entity.setChangeDescription(change);
postUpdate(entity, entity);
return new PutResponse<>(Status.OK, changeEvent, RestUtil.ENTITY_FIELDS_CHANGED);
}
@Transaction
public PutResponse<T> updateVote(String updatedBy, UUID entityId, VoteRequest request) {
T originalEntity = find(entityId, NON_DELETED);
// Validate User
User user = daoCollection.userDAO().findEntityByName(FullyQualifiedName.quoteName(updatedBy));
UUID userId = user.getId();
if (Boolean.TRUE.equals(user.getDeleted())) {
throw new IllegalArgumentException(CatalogExceptionMessage.deletedUser(userId));
}
ChangeDescription change = new ChangeDescription().withPreviousVersion(originalEntity.getVersion());
fieldUpdated(change, FIELD_VOTES, null, request.getUpdatedVoteType());
// Add or Delete relationship
if (request.getUpdatedVoteType() == VoteType.UN_VOTED) {
deleteRelationship(userId, Entity.USER, entityId, entityType, Relationship.VOTED);
} else {
addRelationship(
userId,
entityId,
Entity.USER,
entityType,
Relationship.VOTED,
JsonUtils.pojoToJson(request.getUpdatedVoteType()),
false);
}
setFieldsInternal(originalEntity, new Fields(allowedFields, "votes"));
ChangeEvent changeEvent =
new ChangeEvent()
.withEntity(originalEntity)
.withChangeDescription(change)
.withEventType(EventType.ENTITY_UPDATED)
.withEntityType(entityType)
.withEntityId(entityId)
.withEntityFullyQualifiedName(originalEntity.getFullyQualifiedName())
.withUserName(updatedBy)
.withTimestamp(System.currentTimeMillis())
.withCurrentVersion(originalEntity.getVersion())
.withPreviousVersion(change.getPreviousVersion());
postUpdate(originalEntity, originalEntity);
return new PutResponse<>(Status.OK, changeEvent, RestUtil.ENTITY_FIELDS_CHANGED);
}
@Transaction
public final DeleteResponse<T> delete(String updatedBy, UUID id, boolean recursive, boolean hardDelete) {
DeleteResponse<T> response = deleteInternal(updatedBy, id, recursive, hardDelete);
postDelete(response.getEntity());
return response;
}
@Transaction
public final DeleteResponse<T> deleteByName(String updatedBy, String name, boolean recursive, boolean hardDelete) {
name = quoteFqn ? quoteName(name) : name;
DeleteResponse<T> response = deleteInternalByName(updatedBy, name, recursive, hardDelete);
postDelete(response.getEntity());
return response;
}
protected void preDelete(T entity, String deletedBy) {
// Override this method to perform any operation required after deletion.
// For example ingestion pipeline deletes a pipeline in AirFlow.
}
protected void postDelete(T entity) {}
public void deleteFromSearch(T entity, String changeType) {
if (supportsSearch) {
if (changeType.equals(RestUtil.ENTITY_SOFT_DELETED)) {
searchRepository.softDeleteOrRestoreEntity(entity, true);
} else {
searchRepository.deleteEntity(entity);
}
}
}
public void restoreFromSearch(T entity) {
if (supportsSearch) {
searchRepository.softDeleteOrRestoreEntity(entity, false);
}
}
@Transaction
private DeleteResponse<T> delete(String deletedBy, T original, boolean recursive, boolean hardDelete) {
checkSystemEntityDeletion(original);
preDelete(original, deletedBy);
setFieldsInternal(original, putFields);
deleteChildren(original.getId(), recursive, hardDelete, deletedBy);
String changeType;
T updated = get(null, original.getId(), putFields, ALL, false);
if (supportsSoftDelete && !hardDelete) {
updated.setUpdatedBy(deletedBy);
updated.setUpdatedAt(System.currentTimeMillis());
updated.setDeleted(true);
EntityUpdater updater = getUpdater(original, updated, Operation.SOFT_DELETE);
updater.update();
changeType = RestUtil.ENTITY_SOFT_DELETED;
} else {
cleanup(updated);
changeType = RestUtil.ENTITY_DELETED;
}
LOG.info("{} deleted {}", hardDelete ? "Hard" : "Soft", updated.getFullyQualifiedName());
return new DeleteResponse<>(updated, changeType);
}
@Transaction
public final DeleteResponse<T> deleteInternalByName(
String updatedBy, String name, boolean recursive, boolean hardDelete) {
// Validate entity
T entity = findByName(name, ALL);
return delete(updatedBy, entity, recursive, hardDelete);
}
@Transaction
public final DeleteResponse<T> deleteInternal(String updatedBy, UUID id, boolean recursive, boolean hardDelete) {
// Validate entity
T entity = find(id, ALL);
return delete(updatedBy, entity, recursive, hardDelete);
}
@Transaction
private void deleteChildren(UUID id, boolean recursive, boolean hardDelete, String updatedBy) {
// If an entity being deleted contains other **non-deleted** children entities, it can't be deleted
List<EntityRelationshipRecord> childrenRecords =
daoCollection
.relationshipDAO()
.findTo(id, entityType, List.of(Relationship.CONTAINS.ordinal(), Relationship.PARENT_OF.ordinal()));
if (childrenRecords.isEmpty()) {
LOG.info("No children to delete");
return;
}
// Entity being deleted contains children entities
if (!recursive) {
throw new IllegalArgumentException(CatalogExceptionMessage.entityIsNotEmpty(entityType));
}
// Delete all the contained entities
for (EntityRelationshipRecord entityRelationshipRecord : childrenRecords) {
LOG.info(
"Recursively {} deleting {} {}",
hardDelete ? "hard" : "soft",
entityRelationshipRecord.getType(),
entityRelationshipRecord.getId());
Entity.deleteEntity(
updatedBy, entityRelationshipRecord.getType(), entityRelationshipRecord.getId(), true, hardDelete);
}
}
@Transaction
protected void cleanup(T entityInterface) {
UUID id = entityInterface.getId();
// Delete all the relationships to other entities
daoCollection.relationshipDAO().deleteAll(id, entityType);
// Delete all the field relationships to other entities
daoCollection.fieldRelationshipDAO().deleteAllByPrefix(entityInterface.getFullyQualifiedName());
// Delete all the extensions of entity
daoCollection.entityExtensionDAO().deleteAll(id);