/
MaterialRepository.java
1108 lines (1006 loc) · 53.5 KB
/
MaterialRepository.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 2023 Thoughtworks, Inc.
*
* 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 com.thoughtworks.go.server.persistence;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.materials.AbstractMaterial;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.Materials;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.materials.*;
import com.thoughtworks.go.domain.materials.dependency.DependencyMaterialInstance;
import com.thoughtworks.go.server.cache.CacheKeyGenerator;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.FeedModifier;
import com.thoughtworks.go.server.database.Database;
import com.thoughtworks.go.server.database.QueryExtensions;
import com.thoughtworks.go.server.service.MaterialConfigConverter;
import com.thoughtworks.go.server.service.MaterialExpansionService;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import com.thoughtworks.go.server.ui.ModificationForPipeline;
import com.thoughtworks.go.server.ui.PipelineId;
import com.thoughtworks.go.server.util.CollectionUtil;
import com.thoughtworks.go.server.util.Pagination;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import java.io.File;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import static com.thoughtworks.go.server.persistence.MaterialQueries.loadModificationQuery;
import static com.thoughtworks.go.util.ExceptionUtils.bomb;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.hibernate.criterion.Restrictions.eq;
import static org.hibernate.criterion.Restrictions.isNull;
/**
* Understands how to store and retrieve Materials from the database
*/
@Component
public class MaterialRepository extends HibernateDaoSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(MaterialRepository.class.getName());
private final GoCache goCache;
private final TransactionSynchronizationManager transactionSynchronizationManager;
private final MaterialConfigConverter materialConfigConverter;
private final QueryExtensions queryExtensions;
private final CacheKeyGenerator cacheKeyGenerator;
private final int latestModificationsCacheLimit;
private final MaterialExpansionService materialExpansionService;
@Autowired
public MaterialRepository(SessionFactory sessionFactory,
GoCache goCache,
@Value("${cruise.material.modifications.cache.limit}") int latestModificationsCacheLimit,
TransactionSynchronizationManager transactionSynchronizationManager,
MaterialConfigConverter materialConfigConverter,
MaterialExpansionService materialExpansionService,
Database databaseStrategy) {
this.goCache = goCache;
this.latestModificationsCacheLimit = latestModificationsCacheLimit;
this.transactionSynchronizationManager = transactionSynchronizationManager;
this.materialConfigConverter = materialConfigConverter;
this.materialExpansionService = materialExpansionService;
this.queryExtensions = databaseStrategy.getQueryExtensions();
setSessionFactory(sessionFactory);
this.cacheKeyGenerator = new CacheKeyGenerator(getClass());
}
@SuppressWarnings("unchecked")
public List<Modification> getModificationsForPipelineRange(final String pipelineName,
final Integer fromCounter,
final Integer toCounter) {
return (List<Modification>) getHibernateTemplate().execute(session -> {
final List<Long> fromInclusiveModificationList = fromInclusiveModificationsForPipelineRange(session, pipelineName, fromCounter, toCounter);
final Set<Long> fromModifications = new TreeSet<>(fromInclusiveModificationsForPipelineRange(session, pipelineName, fromCounter, fromCounter));
final Set<Long> fromExclusiveModificationList = new HashSet<>();
for (Long modification : fromInclusiveModificationList) {
if (fromModifications.contains(modification)) {
fromModifications.remove(modification);
} else {
fromExclusiveModificationList.add(modification);
}
}
SQLQuery query = session.createSQLQuery("SELECT * FROM modifications WHERE id IN (:ids) ORDER BY materialId ASC, id DESC");
query.addEntity(Modification.class);
query.setParameterList("ids", fromExclusiveModificationList.isEmpty() ? fromInclusiveModificationList : fromExclusiveModificationList);
return query.list();
});
}
private List<Long> fromInclusiveModificationsForPipelineRange(Session session,
String pipelineName,
Integer fromCounter,
Integer toCounter) {
String pipelineIdsSql = queryExtensions.queryFromInclusiveModificationsForPipelineRange(pipelineName, fromCounter, toCounter);
SQLQuery pipelineIdsQuery = session.createSQLQuery(pipelineIdsSql);
@SuppressWarnings("unchecked") final List<Long> ids = pipelineIdsQuery.list();
if (ids.isEmpty()) {
return new ArrayList<>();
}
String minMaxQuery = " SELECT mods1.materialId as materialId, min(mods1.id) as min, max(mods1.id) as max"
+ " FROM modifications mods1 "
+ " INNER JOIN pipelineMaterialRevisions pmr ON (mods1.id >= pmr.actualFromRevisionId AND mods1.id <= pmr.toRevisionId) AND mods1.materialId = pmr.materialId "
+ " WHERE pmr.pipelineId IN (:ids) "
+ " GROUP BY mods1.materialId";
SQLQuery query = session.createSQLQuery("SELECT mods.id "
+ " FROM modifications mods"
+ " INNER JOIN (" + minMaxQuery + ") as edges on edges.materialId = mods.materialId and mods.id >= min and mods.id <= max"
+ " ORDER BY mods.materialId ASC, mods.id DESC");
query.addScalar("id", new LongType());
query.setParameterList("ids", ids);
//noinspection unchecked
return query.list();
}
public Map<Long, List<ModificationForPipeline>> findModificationsForPipelineIds(final List<Long> pipelineIds) {
final int MODIFICATION = 0;
final int RELEVANT_PIPELINE_ID = 1;
final int RELEVANT_PIPELINE_NAME = 2;
final int MATERIAL_TYPE = 3;
final int MATERIAL_FINGERPRINT = 4;
return getHibernateTemplate().execute(session -> {
if (pipelineIds.isEmpty()) {
return new HashMap<>();
}
Map<PipelineId, Set<Long>> relevantToLookedUpMap = relevantToLookedUpDependencyMap(session, pipelineIds);
SQLQuery query = session.createSQLQuery("SELECT mods.*, pmr.pipelineId as pmrPipelineId, p.name as pmrPipelineName, m.type as materialType, m.fingerprint as fingerprint"
+ " FROM modifications mods "
+ " INNER JOIN pipelineMaterialRevisions pmr ON (mods.id >= pmr.fromRevisionId AND mods.id <= pmr.toRevisionId) AND mods.materialId = pmr.materialId "
+ " INNER JOIN pipelines p ON pmr.pipelineId = p.id"
+ " INNER JOIN materials m ON mods.materialId = m.id"
+ " WHERE pmr.pipelineId IN (:ids)");
@SuppressWarnings("unchecked") List<Object[]> allModifications = query.
addEntity("mods", Modification.class).
addScalar("pmrPipelineId", new LongType()).
addScalar("pmrPipelineName", new StringType()).
addScalar("materialType", new StringType()).
addScalar("fingerprint", new StringType()).
setParameterList("ids", relevantToLookedUpMap.keySet().stream().map(PipelineId::getPipelineId).collect(Collectors.toList())).
list();
Map<Long, List<ModificationForPipeline>> modificationsForPipeline = new HashMap<>();
CollectionUtil.CollectionValueMap<Long, ModificationForPipeline> modsForPipeline = CollectionUtil.collectionValMap(modificationsForPipeline,
new CollectionUtil.ArrayList<>());
for (Object[] modAndPmr : allModifications) {
Modification mod = (Modification) modAndPmr[MODIFICATION];
Long relevantPipelineId = (Long) modAndPmr[RELEVANT_PIPELINE_ID];
String relevantPipelineName = (String) modAndPmr[RELEVANT_PIPELINE_NAME];
String materialType = (String) modAndPmr[MATERIAL_TYPE];
String materialFingerprint = (String) modAndPmr[MATERIAL_FINGERPRINT];
PipelineId relevantPipeline = new PipelineId(relevantPipelineName, relevantPipelineId);
Set<Long> longs = relevantToLookedUpMap.get(relevantPipeline);
for (Long lookedUpPipeline : longs) {
modsForPipeline.put(lookedUpPipeline, new ModificationForPipeline(relevantPipeline, mod, materialType, materialFingerprint));
}
}
return modificationsForPipeline;
});
}
private Map<PipelineId, Set<Long>> relevantToLookedUpDependencyMap(Session session, List<Long> pipelineIds) {
final int LOOKED_UP_PIPELINE_ID = 2;
final int RELEVANT_PIPELINE_ID = 0;
final int RELEVANT_PIPELINE_NAME = 1;
String pipelineIdsSql = queryExtensions.queryRelevantToLookedUpDependencyMap(pipelineIds);
SQLQuery pipelineIdsQuery = session.createSQLQuery(pipelineIdsSql);
pipelineIdsQuery.addScalar("id", new LongType());
pipelineIdsQuery.addScalar("name", new StringType());
pipelineIdsQuery.addScalar("lookedUpId", new LongType());
@SuppressWarnings("unchecked") final List<Object[]> ids = pipelineIdsQuery.list();
Map<Long, List<PipelineId>> lookedUpToParentMap = new HashMap<>();
CollectionUtil.CollectionValueMap<Long, PipelineId> lookedUpToRelevantMap = CollectionUtil.collectionValMap(lookedUpToParentMap, new CollectionUtil.ArrayList<>());
for (Object[] relevantAndLookedUpId : ids) {
lookedUpToRelevantMap.put((Long) relevantAndLookedUpId[LOOKED_UP_PIPELINE_ID],
new PipelineId((String) relevantAndLookedUpId[RELEVANT_PIPELINE_NAME], (Long) relevantAndLookedUpId[RELEVANT_PIPELINE_ID]));
}
return CollectionUtil.reverse(lookedUpToParentMap);
}
public MaterialRevisions findMaterialRevisionsForPipeline(long pipelineId) {
List<PipelineMaterialRevision> revisions = findPipelineMaterialRevisions(pipelineId);
MaterialRevisions materialRevisions = new MaterialRevisions();
for (PipelineMaterialRevision revision : revisions) {
List<Modification> modifications = findModificationsFor(revision);
materialRevisions.addRevision(new MaterialRevision(revision.getMaterial(), revision.getChanged(), modifications.toArray(new Modification[0])));
}
return materialRevisions;
}
public void cacheMaterialRevisionsForPipelines(Set<Long> pipelineIds) {
List<Long> ids = new ArrayList<>(pipelineIds);
final int batchSize = 500;
loadPMRsIntoCache(ids, batchSize);
}
private void loadPMRsIntoCache(List<Long> ids, int batchSize) {
int total = ids.size(), remaining = total;
while (!ids.isEmpty()) {
LOGGER.info("Loading PMRs,Remaining {} Pipelines (Total: {})...", remaining, total);
final List<Long> idsBatch = batchIds(ids, batchSize);
loadPMRByPipelineIds(idsBatch);
remaining -= batchSize;
}
}
private <T> List<T> batchIds(List<T> items, int batchSize) {
List<T> ids = new ArrayList<>();
for (int i = 0; i < batchSize; ++i) {
if (items.isEmpty()) {
break;
}
ids.add(items.remove(0));
}
return ids;
}
public List<PipelineMaterialRevision> findPipelineMaterialRevisions(long pipelineId) {
String cacheKey = pipelinePmrsKey(pipelineId);
synchronized (cacheKey) {
List<PipelineMaterialRevision> results = goCache.get(cacheKey);
if (results != null) {
return results;
}
results = findPMRByPipelineId(pipelineId);
goCache.put(cacheKey, results);
return results;
}
}
@SuppressWarnings("unchecked")
private List<PipelineMaterialRevision> findPMRByPipelineId(long pipelineId) {
return (List<PipelineMaterialRevision>) getHibernateTemplate().find("FROM PipelineMaterialRevision WHERE pipelineId = ? ORDER BY id", pipelineId);
}
private void loadPMRByPipelineIds(List<Long> pipelineIds) {
@SuppressWarnings("unchecked") List<PipelineMaterialRevision> pmrs = (List<PipelineMaterialRevision>) getHibernateTemplate().findByCriteria(buildPMRDetachedQuery(pipelineIds));
sortPersistentObjectsById(pmrs, true);
final Set<PipelineMaterialRevision> uniquePmrs = new HashSet<>();
for (PipelineMaterialRevision pmr : pmrs) {
String cacheKey = pipelinePmrsKey(pmr.getPipelineId());
List<PipelineMaterialRevision> pmrsForId = goCache.get(cacheKey);
if (pmrsForId == null) {
pmrsForId = new ArrayList<>();
goCache.put(cacheKey, pmrsForId);
}
pmrsForId.add(pmr);
putMaterialInstanceIntoCache(pmr.getToModification().getMaterialInstance());
uniquePmrs.add(pmr);
}
loadModificationsIntoCache(uniquePmrs);
}
private void sortPersistentObjectsById(List<? extends PersistentObject> persistentObjects, boolean asc) {
Comparator<PersistentObject> ascendingSort = (po1, po2) -> (int) (po1.getId() - po2.getId());
Comparator<PersistentObject> descendingSort = (po1, po2) -> (int) (po2.getId() - po1.getId());
persistentObjects.sort(asc ? ascendingSort : descendingSort);
}
public void putMaterialInstanceIntoCache(MaterialInstance materialInstance) {
String cacheKey = materialKey(materialInstance.getFingerprint());
goCache.put(cacheKey, materialInstance);
}
private DetachedCriteria buildPMRDetachedQuery(List<Long> pipelineIds) {
DetachedCriteria criteria = DetachedCriteria.forClass(PipelineMaterialRevision.class);
criteria.add(Restrictions.in("pipelineId", pipelineIds));
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria;
}
private void loadModificationsIntoCache(Set<PipelineMaterialRevision> pmrs) {
List<PipelineMaterialRevision> pmrList = new ArrayList<>(pmrs);
int batchSize = 100, total = pmrList.size(), remaining = total;
while (!pmrList.isEmpty()) {
LOGGER.info("Loading modifications, Remaining {} PMRs(Total: {})...", remaining, total);
final List<PipelineMaterialRevision> pmrBatch = batchIds(pmrList, batchSize);
loadModificationsForPMR(pmrBatch);
remaining -= batchSize;
}
}
private void loadModificationsForPMR(List<PipelineMaterialRevision> pmrs) {
List<Criterion> criterions = new ArrayList<>();
for (PipelineMaterialRevision pmr : pmrs) {
if (goCache.get(pmrModificationsKey(pmr)) != null) {
continue;
}
final Criterion modificationClause = Restrictions.between("id", pmr.getFromModification().getId(), pmr.getToModification().getId());
final SimpleExpression idClause = Restrictions.eq("materialInstance", pmr.getMaterialInstance());
criterions.add(Restrictions.and(idClause, modificationClause));
}
@SuppressWarnings("unchecked") List<Modification> modifications = (List<Modification>) getHibernateTemplate().findByCriteria(buildModificationDetachedQuery(criterions));
sortPersistentObjectsById(modifications, false);
for (Modification modification : modifications) {
List<String> cacheKeys = pmrModificationsKey(modification, pmrs);
for (String cacheKey : cacheKeys) {
List<Modification> modificationList = goCache.get(cacheKey);
if (modificationList == null) {
modificationList = new ArrayList<>();
goCache.put(cacheKey, modificationList);
}
modificationList.add(modification);
}
}
}
private DetachedCriteria buildModificationDetachedQuery(List<Criterion> criteria) {
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Modification.class);
Disjunction disjunction = Restrictions.disjunction();
detachedCriteria.add(disjunction);
for (Criterion criterion : criteria) {
disjunction.add(criterion);
}
detachedCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return detachedCriteria;
}
private String pipelinePmrsKey(long pipelineId) {
return (MaterialRepository.class.getName() + "_pipelinePMRs_" + pipelineId).intern();
}
@SuppressWarnings("unchecked")
List<Modification> findMaterialRevisionsForMaterial(long id) {
return (List<Modification>) getHibernateTemplate().find("FROM Modification WHERE materialId = ?", new Object[]{id});
}
List<Modification> findModificationsFor(PipelineMaterialRevision pmr) {
String cacheKey = pmrModificationsKey(pmr);
List<Modification> modifications = goCache.get(cacheKey);
if (modifications == null) {
synchronized (cacheKey) {
modifications = goCache.get(cacheKey);
if (modifications == null) {
//noinspection unchecked
modifications = (List<Modification>) getHibernateTemplate().find(
"FROM Modification WHERE materialId = ? AND id BETWEEN ? AND ? ORDER BY id DESC",
new Object[]{findMaterialInstance(pmr.getMaterial()).getId(), pmr.getFromModification().getId(), pmr.getToModification().getId()});
goCache.put(cacheKey, modifications);
}
}
}
return modifications;
}
private String pmrModificationsKey(PipelineMaterialRevision pmr) {
// we intern() it because we might synchronize on the returned String
return (MaterialRepository.class.getName() + "_pmrModifications_" + pmr.getId()).intern();
}
private List<String> pmrModificationsKey(Modification modification, List<PipelineMaterialRevision> pmrs) {
final long id = modification.getId();
final MaterialInstance materialInstance = modification.getMaterialInstance();
Collection<PipelineMaterialRevision> matchedPmrs = CollectionUtils.select(pmrs, pmr -> {
long from = pmr.getFromModification().getId();
long to = pmr.getToModification().getId();
MaterialInstance pmi = findMaterialInstance(pmr.getMaterial());
return from <= id && id <= to && materialInstance.equals(pmi);
});
List<String> keys = new ArrayList<>(matchedPmrs.size());
for (PipelineMaterialRevision matchedPmr : matchedPmrs) {
keys.add(pmrModificationsKey(matchedPmr));
}
return keys;
}
String latestMaterialModificationsKey(MaterialInstance materialInstance) {
// we intern() it because we might synchronize on the returned String
return (MaterialRepository.class.getName() + "_latestMaterialModifications_" + materialInstance.getId()).intern();
}
String materialModificationCountKey(MaterialInstance materialInstance) {
// we intern() it because we might synchronize on the returned String
return (MaterialRepository.class.getName() + "_materialModificationCount_" + materialInstance.getId()).intern();
}
String materialModificationsWithPaginationKey(MaterialInstance materialInstance) {
// we intern() it because we might synchronize on the returned String
return (MaterialRepository.class.getName() + "_materialModificationsWithPagination_" + materialInstance.getId()).intern();
}
String materialModificationsWithPaginationSubKey(Pagination pagination) {
return String.format("%s-%s", pagination.getOffset(), pagination.getPageSize());
}
public void saveOrUpdate(MaterialInstance materialInstance) {
String cacheKey = materialKey(materialInstance.getFingerprint());
synchronized (cacheKey) {
getHibernateTemplate().saveOrUpdate(materialInstance);
goCache.remove(cacheKey);
goCache.put(cacheKey, materialInstance);
}
}
public MaterialInstance find(long id) {
return getHibernateTemplate().load(MaterialInstance.class, id);
}
public MaterialInstance saveMaterialRevision(MaterialRevision materialRevision) {
LOGGER.info("Saving revision {}", materialRevision);
MaterialInstance materialInstance = findOrCreateFrom(materialRevision.getMaterial());
saveModifications(materialInstance, materialRevision.getModifications());
return materialInstance;
}
@TestOnly
public void saveModification(MaterialInstance materialInstance, Modification modification) {
modification.setMaterialInstance(materialInstance);
try {
getHibernateTemplate().saveOrUpdate(modification);
removeLatestCachedModification(materialInstance);
removeCachedModificationCountFor(materialInstance);
removeCachedModificationsFor(materialInstance);
} catch (Exception e) {
String message = "Cannot save modification " + modification;
LOGGER.error(message, e);
throw new RuntimeException(message, e);
}
}
public MaterialInstance findOrCreateFrom(Material material) {
String cacheKey = materialKey(material);
synchronized (cacheKey) {
MaterialInstance materialInstance = findMaterialInstance(material);
if (materialInstance == null) {
LOGGER.debug("Material instance for material '{}' not found in the database, creating a new instance now.", material);
materialInstance = material.createMaterialInstance();
saveOrUpdate(materialInstance);
}
return materialInstance;
}
}
final String materialKey(Material material) {
return materialKey(material.getFingerprint());
}
private String materialKey(String fingerprint) {
// we intern() it because we synchronize on the returned String
return (MaterialRepository.class.getName() + "_materialInstance_" + fingerprint).intern();
}
public MaterialInstance findMaterialInstance(Material material) {
String cacheKey = materialKey(material);
MaterialInstance materialInstance = goCache.get(cacheKey);
if (materialInstance == null) {
synchronized (cacheKey) {
materialInstance = goCache.get(cacheKey);
if (materialInstance == null) {
DetachedCriteria hibernateCriteria = DetachedCriteria.forClass(material.getInstanceType());
materialInstance = findMaterialInstanceWithHibernate(cacheKey, hibernateCriteria, material.getSqlCriteria());
}
}
}
return materialInstance;//TODO: clone me, caller may mutate
}
public MaterialInstance findMaterialInstance(MaterialConfig materialConfig) {
String cacheKey = materialKey(materialConfig.getFingerprint());
MaterialInstance materialInstance = goCache.get(cacheKey);
if (materialInstance == null) {
synchronized (cacheKey) {
materialInstance = goCache.get(cacheKey);
if (materialInstance == null) {
DetachedCriteria hibernateCriteria = DetachedCriteria.forClass(materialConfigConverter.getInstanceType(materialConfig));
materialInstance = findMaterialInstanceWithHibernate(cacheKey, hibernateCriteria, materialConfig.getSqlCriteria());
}
}
}
return materialInstance;//TODO: clone me, caller may mutate
}
@Nullable
private MaterialInstance findMaterialInstanceWithHibernate(String cacheKey, DetachedCriteria hibernateCriteria, Map<String, Object> sqlCriteria) {
MaterialInstance materialInstance;
for (Map.Entry<String, Object> property : sqlCriteria.entrySet()) {
if (!property.getKey().equals(AbstractMaterial.SQL_CRITERIA_TYPE)) {//type is polymorphic mapping discriminator
if (property.getValue() == null) {
hibernateCriteria.add(isNull(property.getKey()));
} else {
hibernateCriteria.add(eq(property.getKey(), property.getValue()));
}
}
}
materialInstance = firstResult(hibernateCriteria);
if (materialInstance != null) {
goCache.put(cacheKey, materialInstance);
}
return materialInstance;
}
@SuppressWarnings("unchecked")
private <T> T firstResult(DetachedCriteria criteria) {
List<T> results = (List<T>) getHibernateTemplate().findByCriteria(criteria);
if (results.isEmpty()) {
return null;
}
return results.get(0);
}
public void savePipelineMaterialRevision(Pipeline pipeline, long pipelineId, MaterialRevision materialRevision) {
Modification from = materialRevision.getOldestModification();
Modification to = materialRevision.getLatestModification();
Long actualFromModificationId = getLastBuiltModificationId(pipeline, to.getMaterialInstance(), from);
if (!from.hasId() || !to.hasId()) {
throw bomb("You cannot save a PipelineMaterialRevision unless the modifications have already been saved.");
}
PipelineMaterialRevision revision = new PipelineMaterialRevision(pipelineId, materialRevision, actualFromModificationId);
save(revision, pipeline.getName());
}
private Long getLastBuiltModificationId(final Pipeline pipeline,
final MaterialInstance materialInstance,
Modification from) {
if (materialInstance instanceof DependencyMaterialInstance) {
Long id = findLastBuiltModificationId(pipeline, materialInstance);
if (id == null) {
return from.getId();
} else {
return modificationAfter(id, materialInstance);
}
}
return from.getId();
}
private long modificationAfter(final long id, final MaterialInstance materialInstance) {
BigInteger result = (BigInteger) getHibernateTemplate().execute(session -> {
String sql = "SELECT id "
+ " FROM modifications "
+ " WHERE materialId = ? "
+ " AND id > ?"
+ " ORDER BY id"
+ " LIMIT 1";
SQLQuery query = session.createSQLQuery(sql);
query.setLong(0, materialInstance.getId());
query.setLong(1, id);
return query.uniqueResult();
});
return result == null ? id : result.longValue();
}
private Long findLastBuiltModificationId(final Pipeline pipeline, final MaterialInstance materialInstance) {
BigInteger result = (BigInteger) getHibernateTemplate().execute(session -> {
String sql = "SELECT fromRevisionId "
+ " FROM pipelineMaterialRevisions pmr "
+ " INNER JOIN pipelines p on p.id = pmr.pipelineId "
+ " WHERE materialId = ? "
+ " AND p.name = ? "
+ " AND pipelineId < ? "
+ " ORDER BY pmr.id DESC"
+ " LIMIT 1";
SQLQuery query = session.createSQLQuery(sql);
query.setLong(0, materialInstance.getId());
query.setString(1, pipeline.getName());
query.setLong(2, pipeline.getId());
return query.uniqueResult();
});
return result == null ? null : result.longValue();
}
private void save(final PipelineMaterialRevision pipelineMaterialRevision, final String pipelineName) {
getHibernateTemplate().save(pipelineMaterialRevision);
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
String key = cacheKeyForLatestPmrForPipelineKey(pipelineMaterialRevision.getMaterialId(), pipelineName.toLowerCase());
synchronized (key) {
goCache.remove(key);
}
}
});
}
public void createPipelineMaterialRevisions(Pipeline pipeline,
Long pipelineId,
MaterialRevisions materialRevisions) {
for (MaterialRevision materialRevision : materialRevisions) {
savePipelineMaterialRevision(pipeline, pipelineId, materialRevision);
}
}
@TestOnly
public void save(MaterialRevisions materialRevisions) {
for (MaterialRevision materialRevision : materialRevisions) {
saveMaterialRevision(materialRevision);
}
}
public List<Modification> findModificationsSinceAndUptil(Material material,
MaterialRevision materialRevision,
PipelineTimelineEntry.Revision scmRevision) {
List<Modification> modificationsSince = findModificationsSince(material, materialRevision);
if (scmRevision == null) {
return modificationsSince;
}
ArrayList<Modification> modificationsUptil = new ArrayList<>();
for (Modification modification : modificationsSince) {
if (modification.getId() <= scmRevision.id) {
modificationsUptil.add(modification);
}
}
return modificationsUptil;
}
public List<Modification> findModificationsSince(Material material, MaterialRevision revision) {
MaterialInstance materialInstance = findOrCreateFrom(material);
String cacheKey = latestMaterialModificationsKey(materialInstance);
synchronized (cacheKey) {
long sinceModificationId = revision.getLatestModification().getId();
Modifications modifications = cachedModifications(materialInstance);
if (!modificationExists(sinceModificationId, modifications)) {
LOGGER.debug("CACHE-MISS for findModificationsSince - {}: {}", materialInstance, revision.getLatestModification());
modifications = _findModificationsSince(materialInstance, sinceModificationId);
if (shouldCache(modifications)) {
goCache.put(cacheKey, modifications);
} else {
goCache.remove(cacheKey);
}
}
return modifications.since(sinceModificationId);
}
}
private boolean modificationExists(long sinceModificationId, Modifications modifications) {
return modifications != null && modifications.hasModification(sinceModificationId);
}
private boolean shouldCache(Modifications modifications) {
return modifications.size() <= latestModificationsCacheLimit;
}
@SuppressWarnings("unchecked")
private Modifications _findModificationsSince(MaterialInstance materialInstance, long sinceModificationId) {
return new Modifications((List<Modification>) getHibernateTemplate().find("FROM Modification WHERE materialId = ? AND id >= ? ORDER BY id DESC", new Object[]{materialInstance.getId(), sinceModificationId}));
}
private void removeLatestCachedModification(final MaterialInstance materialInstance) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
String cacheKey = latestMaterialModificationsKey(materialInstance);
synchronized (cacheKey) {
goCache.remove(cacheKey);
}
}
});
}
private void removeCachedModificationCountFor(final MaterialInstance materialInstance) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
String key = materialModificationCountKey(materialInstance);
synchronized (key) {
goCache.remove(key);
}
}
});
}
private void removeCachedModificationsFor(final MaterialInstance materialInstance) {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
String key = materialModificationsWithPaginationKey(materialInstance);
synchronized (key) {
goCache.remove(key);
}
}
});
}
Modifications cachedModifications(MaterialInstance materialInstance) {
return goCache.get(latestMaterialModificationsKey(materialInstance));
}
public MaterialRevisions findLatestModification(Material material) {
MaterialInstance materialInstance = findMaterialInstance(material);
if (materialInstance == null) {
return new MaterialRevisions();
}
Materials materials = new Materials();
materialExpansionService.expandForHistory(material, materials);
MaterialRevisions allModifications = new MaterialRevisions();
for (Material expanded : materials) {
final MaterialInstance expandedInstance = findOrCreateFrom(expanded);
Modification modification = findLatestModification(expandedInstance);
if (modification != null) {
allModifications.addRevision(expanded, modification);
}
}
return allModifications;
}
Modification findLatestModification(final MaterialInstance expandedInstance) {
Modifications modifications = cachedModifications(expandedInstance);
if (modifications != null && !modifications.isEmpty()) {
return modifications.get(0);
}
String cacheKey = latestMaterialModificationsKey(expandedInstance);
synchronized (cacheKey) {
Modification modification = (Modification) getHibernateTemplate().execute(session -> {
Query query = session.createQuery("FROM Modification WHERE materialId = ? ORDER BY id DESC");
query.setMaxResults(1);
query.setLong(0, expandedInstance.getId());
return query.uniqueResult();
});
goCache.put(cacheKey, new Modifications(modification));
return modification;
}
}
public void saveModifications(MaterialInstance materialInstance, List<Modification> newChanges) {
if (newChanges.isEmpty()) {
return;
}
List<Modification> list = new ArrayList<>(newChanges);
Collections.reverse(list);
for (Modification modification : list) {
modification.setMaterialInstance(materialInstance);
}
try {
checkAndRemoveDuplicates(materialInstance, newChanges, list);
for (Modification modification : list) {
getHibernateTemplate().saveOrUpdate(modification);
}
} catch (Exception e) {
String message = "Cannot save modification: ";
LOGGER.error(message, e);
throw new RuntimeException(message + e.getMessage(), e);
}
removeLatestCachedModification(materialInstance);
removeCachedModificationCountFor(materialInstance);
removeCachedModificationsFor(materialInstance);
}
private void checkAndRemoveDuplicates(MaterialInstance materialInstance,
List<Modification> newChanges,
List<Modification> list) {
if (!new SystemEnvironment().get(SystemEnvironment.CHECK_AND_REMOVE_DUPLICATE_MODIFICATIONS)) {
return;
}
DetachedCriteria criteria = DetachedCriteria.forClass(Modification.class);
criteria.setProjection(Projections.projectionList().add(Projections.property("revision")));
criteria.add(Restrictions.eq("materialInstance.id", materialInstance.getId()));
ArrayList<String> revisions = new ArrayList<>();
for (Modification modification : newChanges) {
revisions.add(modification.getRevision());
}
criteria.add(Restrictions.in("revision", revisions));
@SuppressWarnings("unchecked") List<String> matchingRevisionsFromDb = (List<String>) getHibernateTemplate().findByCriteria(criteria);
if (!matchingRevisionsFromDb.isEmpty()) {
for (final String revision : matchingRevisionsFromDb) {
Modification modification = list.stream().filter(item -> item.getRevision().equals(revision)).findFirst().orElse(null);
list.remove(modification);
}
}
if (!newChanges.isEmpty() && list.isEmpty()) {
LOGGER.debug("All modifications already exist in db [{}]", revisions);
}
if (!matchingRevisionsFromDb.isEmpty()) {
LOGGER.info("Saving revisions for material [{}] after removing the following duplicates {}",
materialInstance.toOldMaterial(null, null, null).getLongDescription(), matchingRevisionsFromDb);
}
}
public Modification findModificationWithRevision(final Material material, final String revision) {
return getHibernateTemplate().execute(session -> {
try {
final long materialId = findOrCreateFrom(material).getId();
return MaterialRepository.this.findModificationWithRevision(session, materialId, revision);
} catch (Exception e) {
LOGGER.error("Error while retrieving modification with material [{}] containing revision [{}]", material, revision, e);
throw e instanceof HibernateException ? (HibernateException) e : new RuntimeException(e);
}
});
}
Modification findModificationWithRevision(Session session, long materialId, String revision) {
Modification modification;
String key = cacheKeyForModificationWithRevision(materialId, revision);
modification = goCache.get(key);
if (modification == null) {
synchronized (key) {
modification = goCache.get(key);
if (modification == null) {
Query query = session.createQuery("FROM Modification WHERE materialId = ? and revision = ? ORDER BY id DESC");
query.setLong(0, materialId);
query.setString(1, revision);
modification = (Modification) query.uniqueResult();
goCache.put(key, modification);
}
}
}
return modification;
}
public MaterialRevisions findLatestRevisions(MaterialConfigs materialConfigs) {
MaterialRevisions materialRevisions = new MaterialRevisions();
for (MaterialConfig materialConfig : materialConfigs) {
MaterialInstance materialInstance = findMaterialInstance(materialConfig);
if (materialInstance != null) {
Modification modification = findLatestModification(materialInstance);
Material material = materialConfigConverter.toMaterial(materialConfig);
materialRevisions.addRevision(modification == null ? new MaterialRevision(material) : new MaterialRevision(material, modification));
}
}
return materialRevisions;
}
public boolean hasPipelineEverRunWith(final String pipelineName, final MaterialRevisions revisions) {
return getHibernateTemplate().execute(session -> {
int numberOfMaterials = revisions.getRevisions().size();
int match = 0;
for (MaterialRevision revision : revisions) {
long materialId = findOrCreateFrom(revision.getMaterial()).getId();
long modificationId = revision.getLatestModification().getId();
String key = cacheKeyForHasPipelineEverRunWithModification(pipelineName, materialId, modificationId);
if (goCache.get(key) != null) {
match++;
continue;
}
String sql = "SELECT materials.id"
+ " FROM pipelineMaterialRevisions"
+ " INNER JOIN pipelines ON pipelineMaterialRevisions.pipelineId = pipelines.id"
+ " INNER JOIN modifications on modifications.id = pipelineMaterialRevisions.torevisionId"
+ " INNER JOIN materials on modifications.materialId = materials.id"
+ " WHERE materials.id = ? AND pipelineMaterialRevisions.toRevisionId >= ? AND pipelineMaterialRevisions.fromRevisionId <= ? AND pipelines.name = ?"
+ " GROUP BY materials.id;";
SQLQuery query = session.createSQLQuery(sql);
query.setLong(0, materialId);
query.setLong(1, modificationId);
query.setLong(2, modificationId);
query.setString(3, pipelineName);
if (!query.list().isEmpty()) {
match++;
goCache.put(key, Boolean.TRUE);
}
}
return match == numberOfMaterials;
});
}
private String cacheKeyForHasPipelineEverRunWithModification(Object pipelineName,
long materialId,
long modificationId) {
return cacheKeyGenerator.generate("hasPipelineEverRunWithModification", pipelineName, materialId, modificationId);
}
public List<MatchedRevision> findRevisionsMatching(final MaterialConfig materialConfig, final String searchString) {
return getHibernateTemplate().execute(session -> {
String sql = "SELECT m.*"
+ " FROM modifications AS m"
+ " INNER JOIN materials mat ON mat.id = m.materialId"
+ " WHERE mat.fingerprint = :finger_print"
+ " AND (m.revision || ' ' || COALESCE(m.username, '') || ' ' || COALESCE(m.comment, '') LIKE :search_string OR m.pipelineLabel LIKE :search_string)"
+ " ORDER BY m.id DESC"
+ " LIMIT 5";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity("m", Modification.class);
Material material = materialConfigConverter.toMaterial(materialConfig);
query.setString("finger_print", material.getFingerprint());
query.setString("search_string", "%" + searchString + "%");
final List<MatchedRevision> list = new ArrayList<>();
//noinspection unchecked
for (Modification mod : (List<Modification>) query.list()) {
list.add(material.createMatchedRevision(mod, searchString));
}
return list;
});
}
public List<Modification> modificationFor(final StageIdentifier stageIdentifier) {
if (stageIdentifier == null) {
return null;
}
String key = cacheKeyForModificationsForStageLocator(stageIdentifier);
List<Modification> modifications = goCache.get(key);
if (modifications == null) {
synchronized (key) {
modifications = goCache.get(key);
if (modifications == null) {
//noinspection unchecked
modifications = getHibernateTemplate().execute(session -> {
Query q = session.createQuery("FROM Modification WHERE revision = :revision ORDER BY id DESC");
q.setParameter("revision", stageIdentifier.getStageLocator());
return q.list();
});
if (!modifications.isEmpty()) {
goCache.put(key, modifications);
}
}
}
}
return modifications;
}
public Long getTotalModificationsFor(final MaterialInstance materialInstance) {
String key = materialModificationCountKey(materialInstance);
Long totalCount = goCache.get(key);
if (totalCount == null || totalCount == 0) {
synchronized (key) {
totalCount = goCache.get(key);
if (totalCount == null || totalCount == 0) {
totalCount = (Long) getHibernateTemplate().execute(session -> {
Query q = session.createQuery("select count(*) FROM Modification WHERE materialId = ?");
q.setLong(0, materialInstance.getId());
return q.uniqueResult();
});
goCache.put(key, totalCount);
}
}
}
return totalCount;
}
public Modifications getModificationsFor(final MaterialInstance materialInstance, final Pagination pagination) {
String key = materialModificationsWithPaginationKey(materialInstance);
String subKey = materialModificationsWithPaginationSubKey(pagination);
Modifications modifications = (Modifications) goCache.get(key, subKey);
if (modifications == null) {
synchronized (key) {
modifications = (Modifications) goCache.get(key, subKey);
if (modifications == null) {
@SuppressWarnings("unchecked") List<Modification> modificationsList = getHibernateTemplate().execute(session -> {
Query q = session.createQuery("FROM Modification WHERE materialId = ? ORDER BY id DESC");
q.setFirstResult(pagination.getOffset());
q.setMaxResults(pagination.getPageSize());
q.setLong(0, materialInstance.getId());
return q.list();
});
if (!modificationsList.isEmpty()) {
modifications = new Modifications(modificationsList);
goCache.put(key, subKey, modifications);
}
}
}
}
return modifications;
}
public Long latestModificationRunByPipeline(final CaseInsensitiveString pipelineName, final Material material) {
final long materialId = findMaterialInstance(material).getId();
String key = cacheKeyForLatestPmrForPipelineKey(materialId, pipelineName.toLower());
Long modificationId = goCache.get(key);
if (modificationId == null) {
synchronized (key) {
modificationId = goCache.get(key);
if (modificationId == null) {
modificationId = (Long) getHibernateTemplate().execute(session -> {
SQLQuery sqlQuery = session.createSQLQuery("SELECT MAX(pmr.toRevisionId) toRevisionId "
+ "FROM (SELECT torevisionid, pipelineid FROM pipelineMaterialRevisions WHERE materialid = :material_id) AS pmr\n"
+ "INNER JOIN pipelines p ON ( p.name = :pipeline_name AND p.id = pmr.pipelineId)");
sqlQuery.setParameter("material_id", materialId);
sqlQuery.setParameter("pipeline_name", pipelineName.toString());
sqlQuery.addScalar("toRevisionId", new LongType());
return sqlQuery.uniqueResult();
});