-
Notifications
You must be signed in to change notification settings - Fork 131
/
PoolSelectionUnitV2.java
3240 lines (2837 loc) · 112 KB
/
PoolSelectionUnitV2.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
package diskCacheV111.poolManager;
import static diskCacheV111.poolManager.PoolSelectionUnit.UnitType.DCACHE;
import static diskCacheV111.poolManager.PoolSelectionUnit.UnitType.NET;
import static diskCacheV111.poolManager.PoolSelectionUnit.UnitType.PROTOCOL;
import static diskCacheV111.poolManager.PoolSelectionUnit.UnitType.STORE;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;
import static org.dcache.namespace.FileAttribute.CACHECLASS;
import static org.dcache.namespace.FileAttribute.HSM;
import static org.dcache.namespace.FileAttribute.STORAGECLASS;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Streams;
import diskCacheV111.pools.PoolV2Mode;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.vehicles.GenericStorageInfo;
import diskCacheV111.vehicles.StorageInfo;
import dmg.cells.nucleus.CellAddressCore;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellLifeCycleAware;
import dmg.cells.nucleus.CellSetupProvider;
import dmg.util.CommandException;
import dmg.util.CommandSyntaxException;
import dmg.util.command.Argument;
import dmg.util.command.Command;
import dmg.util.command.Option;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.dcache.namespace.FileAttribute;
import org.dcache.util.Args;
import org.dcache.util.Glob;
import org.dcache.vehicles.FileAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PoolSelectionUnitV2
implements Serializable, PoolSelectionUnit, PoolSelectionUnitAccess, CellSetupProvider,
CellCommandListener, CellLifeCycleAware {
private static final String __version = "$Id: PoolSelectionUnitV2.java,v 1.42 2007-10-25 14:03:54 tigran Exp $";
private static final Logger LOGGER = LoggerFactory.getLogger(PoolSelectionUnitV2.class);
private static final String NO_NET = "<no net>";
private static final Set<FileAttribute> STORAGE_INFO = Set.of(FileAttribute.CACHECLASS,
FileAttribute.STORAGECLASS, FileAttribute.HSM, FileAttribute.OWNER,
FileAttribute.OWNER_GROUP);
private static final String DEFAULT_PROTOCOL_UNIT = "*/*";
private static final String DEFAULT_IPV4_NET_UNIT = "0.0.0.0/0.0.0.0";
private static final String DEFAULT_IPV6_NET_UNIT = "::/0";
@Override
public String getVersion() {
return __version;
}
private static final long serialVersionUID = 4852540784324544199L;
private Collection<Pool> _poolsFromBeforeSetup;
private final Map<String, PGroup> _pGroups = new HashMap<>();
private final Map<String, Pool> _pools = new HashMap<>();
private final Map<String, Link> _links = new HashMap<>();
private final Map<String, LinkGroup> _linkGroups = new HashMap<>();
private final Map<String, UGroup> _uGroups = new HashMap<>();
private final Map<String, Unit> _units = new HashMap<>();
private final Cache<String, PoolPreferenceLevel[]> cachedMatchValue =
CacheBuilder.newBuilder()
.maximumSize(100000)
.build();
private boolean _useRegex;
private boolean _allPoolsActive;
/**
* Ok, this is the critical part of PoolManager, but (!!!) the whole select path is READ-ONLY,
* unless we change setup. So ReadWriteLock is what we are looking for, while is a point of
* serialization.
*/
private final ReentrantReadWriteLock _psuReadWriteLock = new ReentrantReadWriteLock();
private final Lock _psuReadLock = _psuReadWriteLock.readLock();
private final Lock _psuWriteLock = _psuReadWriteLock.writeLock();
private final NetHandler _netHandler = new NetHandler();
private transient PnfsHandler _pnfsHandler;
@Override
public Map<String, SelectionLink> getLinks() {
rlock();
try {
return Maps.newHashMap(_links);
} finally {
runlock();
}
}
@Override
public Map<String, SelectionUnit> getSelectionUnits() {
rlock();
try {
return Maps.newHashMap(_units);
} finally {
runlock();
}
}
@Override
public Map<String, SelectionUnitGroup> getUnitGroups() {
rlock();
try {
return Maps.newHashMap(_uGroups);
} finally {
runlock();
}
}
@Override
public Collection<SelectionLink> getLinksPointingToPoolGroup(String poolGroup)
throws NoSuchElementException {
rlock();
try {
PGroup group = _pGroups.get(poolGroup);
if (group == null) {
throw new NoSuchElementException("No such pool group: " + poolGroup);
}
return new ArrayList<>(group._linkList.values());
} finally {
runlock();
}
}
@Override
public SelectionLink getLinkByName(String name) throws NoSuchElementException {
Link link = null;
rlock();
try {
link = _links.get(name);
if (link == null) {
throw new NoSuchElementException("Link not found : " + name);
}
} finally {
runlock();
}
return link;
}
@Override
public String[] getDefinedPools(boolean enabledOnly) {
rlock();
try {
return _pools.values().stream()
.filter(p -> p.isEnabled() || !enabledOnly)
.map(Pool::getName)
.toArray(String[]::new);
} finally {
runlock();
}
}
@Override
public String[] getActivePools() {
rlock();
try {
return _pools.values().stream()
.filter(Pool::isActive)
.filter(Pool::isEnabled)
.map(Pool::getName)
.toArray(String[]::new);
} finally {
runlock();
}
}
@Override
public void beforeSetup() {
wlock();
_poolsFromBeforeSetup = Lists.newArrayList(_pools.values());
clear();
}
@Override
public void afterSetup() {
_poolsFromBeforeSetup.stream().filter(Pool::isActive)
.forEach(p -> {
Pool pool = _pools.get(p.getName());
if (pool == null) {
pool = new Pool(p.getName());
_pools.put(pool.getName(), pool);
PGroup group = _pGroups.get("default");
if (group != null) {
pool._pGroupList.put(group.getName(), group);
group._poolList.put(pool.getName(), pool);
}
}
pool.setAddress(p.getAddress());
pool.setPoolMode(p.getPoolMode());
pool.setHsmInstances(p.getHsmInstances());
pool.setActive(true);
pool.setSerialId(p.getSerialId());
});
_poolsFromBeforeSetup = null;
wunlock();
}
@Override
public void printSetup(PrintWriter pw) {
rlock();
try {
pw.append("psu set regex ").println(_useRegex ? "on" : "off");
pw.append("psu set allpoolsactive ").println(_allPoolsActive ? "on" : "off");
pw.println();
_units.values().stream().sorted(comparing(Unit::getType).thenComparing(Unit::getName))
.forEachOrdered(
unit -> {
pw.append("psu create unit ");
switch (unit.getType()) {
case STORE:
pw.append("-store");
break;
case DCACHE:
pw.append("-dcache");
break;
case PROTOCOL:
pw.append("-protocol");
break;
case NET:
pw.append("-net");
break;
}
pw.append(" ").println(unit.getName());
if (unit instanceof StorageUnit) {
StorageUnit sunit = (StorageUnit) unit;
Integer required = sunit.getRequiredCopies();
if (required != null) {
pw.append("psu set storage unit ")
.append(sunit.getName())
.append(" -required=")
.append(String.valueOf(required));
List<String> tags = sunit.getOnlyOneCopyPer();
if (!tags.isEmpty()) {
pw.append(" -onlyOneCopyPer=")
.append(Joiner.on(",").join(tags));
}
pw.println();
}
}
});
pw.println();
_uGroups.values().stream().sorted(comparing(UGroup::getName)).forEachOrdered(
group -> {
pw.append("psu create ugroup ").println(group.getName());
group._unitList.values().stream().sorted(comparing(Unit::getName))
.forEachOrdered(
unit -> pw
.append("psu addto ugroup ")
.append(group.getName())
.append(" ")
.println(unit.getName()));
pw.println();
});
_pools.values().stream().sorted(comparing(Pool::getName)).forEachOrdered(
pool -> {
pw.append("psu create pool ").append(pool.getName());
if (!pool.isPing()) {
pw.append(" -noping");
}
if (!pool.isEnabled()) {
pw.append(" -disabled");
}
if (pool.isReadOnly()) {
pw.append(" -rdonly");
}
pw.println();
});
pw.println();
_pGroups.values().stream().sorted(comparing(PGroup::getName)).forEachOrdered(
group -> {
pw.append("psu create pgroup ").append(group.getName());
if (group.isPrimary()) {
pw.append(" -resilient");
}
// don't explicitly add pools into dynamic pool groups
if (group instanceof DynamicPGroup) {
pw.append(" -dynamic");
Map<String, String> tags = ((DynamicPGroup) group).getTags();
String asOption = tags.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(","));
pw.append(" -tags=" + asOption);
pw.println();
} else {
pw.println();
group._poolList.values().stream().sorted(comparing(Pool::getName))
.forEachOrdered(
pool -> pw
.append("psu addto pgroup ")
.append(group.getName())
.append(" ")
.println(pool.getName())
);
}
pw.println();
});
//nested -pools
_pGroups.values().stream().sorted(comparing(PGroup::getName)).forEachOrdered(
group -> {
pw.println();
group._pgroupList.stream().sorted(comparing(PGroup::getName))
.forEachOrdered(
groupS -> {pw
.append("psu addto pgroup ")
.append(group.getName())
.append(" ")
.println("@" + groupS.getName());
LOGGER.info(groupS.getName() + " " + group.getName());
}
);
pw.println();
});
_links.values().stream().sorted(comparing(Link::getName)).forEachOrdered(
link -> {
pw.append("psu create link ").append(link.getName());
link._uGroupList.values().stream().map(UGroup::getName).sorted()
.forEachOrdered(
name -> pw.append(" ").append(name));
pw.println();
pw.append("psu set link ").append(link.getName()).append(" ")
.println(link.getAttraction());
link._poolList.values().stream().sorted(comparing(PoolCore::getName))
.forEachOrdered(
poolCore -> pw
.append("psu addto link ")
.append(link.getName())
.append(" ")
.println(poolCore.getName()));
pw.println();
});
_linkGroups.values().stream().sorted(comparing(LinkGroup::getName)).forEachOrdered(
linkGroup -> {
pw.append("psu create linkGroup ").println(linkGroup.getName());
pw.append("psu set linkGroup custodialAllowed ").append(
linkGroup.getName()).append(" ").println(
linkGroup.isCustodialAllowed());
pw.append("psu set linkGroup replicaAllowed ").append(
linkGroup.getName()).append(" ").println(
linkGroup.isReplicaAllowed());
pw.append("psu set linkGroup nearlineAllowed ").append(
linkGroup.getName()).append(" ").println(
linkGroup.isNearlineAllowed());
pw.append("psu set linkGroup outputAllowed ").append(
linkGroup.getName()).append(" ").println(
linkGroup.isOutputAllowed());
pw.append("psu set linkGroup onlineAllowed ").append(
linkGroup.getName()).append(" ").println(
linkGroup.isOnlineAllowed());
linkGroup.getLinks().stream().sorted(comparing(SelectionLink::getName))
.forEachOrdered(
link -> pw
.append("psu addto linkGroup ")
.append(linkGroup.getName())
.append(" ")
.println(link.getName()));
pw.println();
});
} finally {
runlock();
}
}
public void clear() {
wlock();
try {
_netHandler.clear();
_pGroups.clear();
_pools.clear();
_links.clear();
_uGroups.clear();
_units.clear();
_linkGroups.clear();
} finally {
wunlock();
}
}
public void setActive(String poolName, boolean active) {
wlock();
try {
Pool pool = _pools.get(poolName);
if (pool != null) {
pool.setActive(active);
}
} finally {
wunlock();
}
}
private int setEnabled(Glob glob, boolean enabled) {
wlock();
try {
int count = 0;
for (Pool pool : getPools(glob.toPattern())) {
count++;
pool.setEnabled(enabled);
}
return count;
} finally {
wunlock();
}
}
@Override
public SelectionPool getPool(String poolName) {
SelectionPool pool = null;
rlock();
try {
pool = _pools.get(poolName);
} finally {
runlock();
}
return pool;
}
@Override
public boolean updatePool(String poolName, CellAddressCore address,
String canonicalHostName, long serialId,
PoolV2Mode mode, Set<String> hsmInstances,
Map<String, String> tags) {
/* For compatibility with previous versions of dCache, a pool
* marked DISABLED, but without any other DISABLED_ flags set
* is considered fully disabled.
*/
boolean disabled =
mode.getMode() == PoolV2Mode.DISABLED
|| mode.isDisabled(PoolV2Mode.DISABLED_DEAD)
|| mode.isDisabled(PoolV2Mode.DISABLED_STRICT);
/* By convention, the serial number is set to zero when a pool
* is disabled. This is used by the watchdog to identify, that
* we have already announced that the pool is down.
*/
long newSerialId = disabled ? 0 : serialId;
/* The update is done in two steps; most of the time an update will not change anything except
* refresh the heartbeat timestamp. We do this under a read lock.
*/
rlock();
try {
Pool pool = _pools.get(poolName);
if (pool != null) {
/* Any change in the kind of operations a pool might be able
* to perform has to be propagated to a number of other
* components.
*
* Notice that calling setSerialId has a side-effect, which is
* why we call it first.
*/
boolean changed =
pool.getSerialId() != newSerialId
|| pool.isActive() == disabled
|| (mode.getMode() != pool.getPoolMode().getMode())
|| !Objects.equals(pool.getHsmInstances(), hsmInstances)
|| !Objects.equals(pool.getAddress(), address)
|| !Objects.equals(pool.getCanonicalHostName(),
Optional.ofNullable(canonicalHostName));
if (!changed) {
pool.setActive(!disabled);
return false;
}
}
} finally {
runlock();
}
/* We detected that something changed and fall through to a full update under a write lock.
*/
wlock();
try {
Pool pool = _pools.get(poolName);
if (pool == null) {
pool = new Pool(poolName);
_pools.put(pool.getName(), pool);
PGroup group = _pGroups.get("default");
if (group == null) {
throw new IllegalArgumentException("Not found : " + "default");
}
pool._pGroupList.put(group.getName(), group);
group._poolList.put(pool.getName(), pool);
}
PoolV2Mode oldMode = pool.getPoolMode();
/* Any change in the kind of operations a pool might be able
* to perform has to be propagated to a number of other
* components.
*
* Notice that calling setSerialId has a side-effect, which is
* why we call it first.
*/
boolean isRestarted = pool.setSerialId(newSerialId);
boolean changed =
isRestarted
|| pool.isActive() == disabled
|| (mode.getMode() != oldMode.getMode())
|| !Objects.equals(pool.getHsmInstances(), hsmInstances)
|| !Objects.equals(pool.getAddress(), address)
|| !Objects.equals(pool.getCanonicalHostName(),
Optional.ofNullable(canonicalHostName));
if (mode.getMode() != oldMode.getMode()) {
LOGGER.warn("Pool {} changed from mode {} to {}.", poolName, oldMode, mode);
}
pool.setAddress(address);
pool.setPoolMode(mode);
pool.setHsmInstances(hsmInstances);
pool.setActive(!disabled);
pool.setCanonicalHostName(canonicalHostName);
pool.setTags(tags);
// create a dynamic pool group based on pool tags.
if (isRestarted && !disabled) {
final Pool p = pool;
_pGroups.values().stream()
.filter(DynamicPGroup.class::isInstance)
.map(DynamicPGroup.class::cast)
.forEach(pg -> pg.addIfMatches(p));
}
return changed;
} finally {
wunlock();
}
}
public Map<String, Link> match(Map<String, Link> map, Unit unit,
DirectionType ioType) {
Map<String, Link> newmap = match(unit, null, ioType);
if (map == null) {
return newmap;
}
Map<String, Link> resultMap = new HashMap<>();
for (Link link : map.values()) {
if (newmap.get(link.getName()) != null) {
resultMap.put(link.getName(), link);
}
}
return resultMap;
}
private LinkMap match(LinkMap linkMap, Unit unit, LinkGroup linkGroup,
DirectionType ioType) {
Map<String, Link> map = match(unit, linkGroup, ioType);
for (Link link : map.values()) {
linkMap.addLink(link);
}
return linkMap;
}
/**
* Matches using logical AND.
* <p>
* The AND is only valid if we have at least as many units (from the arguments) as required by
* the number of uGroupList(s).
*
* @param type of I/O direction
* @param netUnitName IP address/hostname or <code>null</code> (= default)
* @param protocolUnitName of the form name/version, or <code>null</code> (= default)
* @param fileAttributes with minimally storage info defined
* @param linkGroupName can be <code>null</code>
* @param exclude for matching excluded hosts
* @return array of pools sorted by preference level
*/
@Override
public PoolPreferenceLevel[] match(DirectionType type, String netUnitName,
String protocolUnitName,
FileAttributes fileAttributes, String linkGroupName, Predicate<String> exclude) {
requireNonNull(exclude, "Predicate argument cannot be null.");
StorageInfo storageInfo = fileAttributes.getStorageInfo();
String storageClass = storageInfo.getStorageClass();
String hsm = storageInfo.getHsm();
String dCacheUnitName = storageInfo.getCacheClass();
/*
* The preference level build requires these to be present in the file attributes.
*/
if (fileAttributes.isUndefined(STORAGECLASS)) {
fileAttributes.setStorageClass(storageClass);
}
if (fileAttributes.isUndefined(HSM)) {
fileAttributes.setHsm(hsm);
}
if (fileAttributes.isUndefined(CACHECLASS)) {
fileAttributes.setCacheClass(dCacheUnitName);
}
String storeUnitName = storageClass + "@" + hsm;
Map<String, String> variableMap = storageInfo.getMap();
String netUnitGroup = null;
LOGGER.debug(
"running match: type={} store={} dCacheUnit={} net={} protocol={} keys={} locations={} linkGroup={}",
type, storeUnitName, dCacheUnitName, netUnitName, protocolUnitName,
variableMap, storageInfo.locations(), linkGroupName);
String cacheKey = null;
try {
Unit unit = _netHandler.match(netUnitName);
netUnitGroup = unit._uGroupList.values()
.stream()
.map(UGroup::getName).findFirst().get();
LOGGER.debug("this IP address belongs to {} in uGroup {} ", netUnitName, netUnitGroup);
} catch (UnknownHostException e) {
LOGGER.error("Caching did not work, please check the configuration " + e);
}
cacheKey = type.toString() + storeUnitName + dCacheUnitName +
netUnitGroup + protocolUnitName + linkGroupName;
PoolPreferenceLevel[] cachedMatchValueTmp = cachedMatchValue.getIfPresent(cacheKey);
if (cachedMatchValueTmp != null) {
return cachedMatchValueTmp;
}
PoolPreferenceLevel[] result = null;
rlock();
try {
List<Unit> units = new ArrayList<>();
resolveStorageUnit(units, storeUnitName);
addProtocolUnit(units, protocolUnitName);
addDCacheUnit(units, dCacheUnitName);
addNetUnit(units, netUnitName);
LinkGroup linkGroup = resolveLinkGroup(linkGroupName);
Set<Link> sortedSet = findMatchingLinks(units, linkGroup, type);
List<List<Link>> linkLists = matchPreferences(type, sortedSet);
result = buildPreferenceLevels(type, linkLists, fileAttributes, exclude);
} finally {
runlock();
}
if (LOGGER.isDebugEnabled()) {
logResult(result);
}
cachedMatchValue.put(cacheKey, result);
return result;
}
private void resolveStorageUnit(List<Unit> list, String storeUnitName) {
if (_useRegex) {
Unit universalCoverage = null;
Unit classCoverage = null;
for (Unit unit : _units.values()) {
if (unit.getType() != STORE) {
continue;
}
if (unit.getName().equals("*@*")) {
universalCoverage = unit;
} else if (unit.getName().equals("*@" + storeUnitName)) {
classCoverage = unit;
} else {
if (Pattern.matches(unit.getName(), storeUnitName)) {
list.add(unit);
break;
}
}
}
if (list.isEmpty()) {
if (classCoverage != null) {
list.add(classCoverage);
} else if (universalCoverage != null) {
list.add(universalCoverage);
} else {
throw new IllegalArgumentException(
"Unit not found : " + storeUnitName);
}
}
} else {
Unit unit = _units.get(storeUnitName);
if (unit == null) {
int ind = storeUnitName.lastIndexOf('@');
if ((ind > 0) && (ind < (storeUnitName.length() - 1))) {
String template = "*@"
+ storeUnitName.substring(ind + 1);
if ((unit = _units.get(template)) == null) {
if ((unit = _units.get("*@*")) == null) {
LOGGER.debug("no matching storage unit found for: {}",
storeUnitName);
throw new IllegalArgumentException(
"Unit not found : " + storeUnitName);
}
}
} else {
throw new IllegalArgumentException(
"IllegalUnitFormat : " + storeUnitName);
}
}
LOGGER.debug("matching storage unit found for: {}", storeUnitName);
list.add(unit);
}
}
private void addProtocolUnit(List<Unit> list, String protocolUnitName) {
if (protocolUnitName != null) {
Unit unit = findProtocolUnit(protocolUnitName);
if (unit == null) {
LOGGER.debug("no matching protocol unit found for: {}", protocolUnitName);
/* for backward compatibility, do not throw exception */
return;
}
LOGGER.debug("matching protocol unit found: {}", unit);
list.add(unit);
}
}
private void addDCacheUnit(List<Unit> list, String dCacheUnitName) {
if (dCacheUnitName != null) {
Unit unit = _units.get(dCacheUnitName);
if (unit == null || unit.getType() != DCACHE) {
LOGGER.debug("no matching dCache unit found for: {}", dCacheUnitName);
throw new IllegalArgumentException("Unit not found : "
+ dCacheUnitName);
}
LOGGER.debug("matching dCache unit found: {}", unit);
list.add(unit);
}
}
private void addNetUnit(List<Unit> list, String netUnitName) {
if (netUnitName != null) {
try {
Unit unit;
if (DEFAULT_IPV4_NET_UNIT.equals(netUnitName)
|| DEFAULT_IPV6_NET_UNIT.equals(netUnitName)) {
unit = _units.get(netUnitName);
} else {
unit = _netHandler.match(netUnitName);
}
if (unit == null) {
LOGGER.debug("no matching net unit found for: {}", netUnitName);
/* for backward compatibility, do not throw exception */
return;
}
LOGGER.debug("matching net unit found: {}", unit);
list.add(unit);
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException(
"NetUnit not resolved : " + netUnitName);
}
}
}
private LinkGroup resolveLinkGroup(String linkGroupName) {
LinkGroup linkGroup = null;
if (linkGroupName != null) {
linkGroup = _linkGroups.get(linkGroupName);
if (linkGroup == null) {
LOGGER.debug("LinkGroup not found : {}", linkGroupName);
throw new IllegalArgumentException("LinkGroup not found : "
+ linkGroupName);
}
}
return linkGroup;
}
private Set<Link> findMatchingLinks(List<Unit> units, LinkGroup linkGroup,
DirectionType type) {
Set<Link> sortedSet = new TreeSet<>(new LinkComparator(type));
LinkMap matchingLinks = new LinkMap();
int fitCount = units.size();
for (Unit unit : units) {
matchingLinks = match(matchingLinks, unit, linkGroup, type);
}
Iterator<Link> linkIterator = matchingLinks.iterator();
while (linkIterator.hasNext()) {
Link link = linkIterator.next();
if (link._uGroupList.size() <= fitCount) {
sortedSet.add(link);
}
}
return sortedSet;
}
private List<List<Link>> matchPreferences(DirectionType type, Set<Link> sortedSet) {
int pref = -1;
List<List<Link>> linkLists = new ArrayList<>();
List<Link> currentList = null;
switch (type) {
case READ:
for (Link link : sortedSet) {
if (link.getReadPref() < 1) {
continue;
}
if (link.getReadPref() != pref) {
linkLists.add(currentList = new ArrayList<>());
pref = link.getReadPref();
}
currentList.add(link);
}
break;
case CACHE:
for (Link link : sortedSet) {
if (link.getCachePref() < 1) {
continue;
}
if (link.getCachePref() != pref) {
linkLists.add(currentList = new ArrayList<>());
pref = link.getCachePref();
}
currentList.add(link);
}
break;
case P2P:
for (Link link : sortedSet) {
int tmpPref = link.getP2pPref() < 0 ? link.getReadPref()
: link.getP2pPref();
if (tmpPref < 1) {
continue;
}
if (tmpPref != pref) {
linkLists.add(currentList = new ArrayList<>());
pref = tmpPref;
}
currentList.add(link);
}
break;
case WRITE:
for (Link link : sortedSet) {
if (link.getWritePref() < 1) {
continue;
}
if (link.getWritePref() != pref) {
linkLists.add(currentList = new ArrayList<>());
pref = link.getWritePref();
}
currentList.add(link);
}
}
return linkLists;
}
private PoolPreferenceLevel[] buildPreferenceLevels(DirectionType type,
List<List<Link>> linkLists, FileAttributes fileAttributes, Predicate<String> exclude) {
List<Link>[] linkListsArray = linkLists.toArray(List[]::new);
PoolPreferenceLevel[] result = new PoolPreferenceLevel[linkListsArray.length];
for (int i = 0; i < linkListsArray.length; i++) {
List<Link> linkList = linkListsArray[i];
List<String> resultList = new ArrayList<>();
String tag = null;
for (Link link : linkList) {
if ((tag == null) && (link.getTag() != null)) {
tag = link.getTag();
}
for (PoolCore poolCore : link._poolList.values()) {
if (poolCore instanceof Pool) {
Pool pool = (Pool) poolCore;
LOGGER.debug("Pool: {} can read from tape? : {}", pool,
pool.canReadFromTape());
if (((type == DirectionType.READ && pool.canRead())
|| (type == DirectionType.CACHE && pool.canReadFromTape()
&& poolCanStageFile(pool, fileAttributes))
|| (type == DirectionType.WRITE && pool.canWrite())
|| (type == DirectionType.P2P && pool.canWriteForP2P()))
&& (_allPoolsActive || pool.isActive())) {
if (exclude.test(pool.getName())) {
LOGGER.debug(
"Qualifying pool {} is on excluded host {}; skipping.",
pool.getName(),
pool.getCanonicalHostName());
} else {
resultList.add(pool.getName());
}
}
} else {
for (Pool pool : ((PGroup) poolCore)._poolList.values()) {
LOGGER.debug("Pool: {} can read from tape? : {}", pool,
pool.canReadFromTape());
if (((type == DirectionType.READ && pool.canRead())
|| (type == DirectionType.CACHE && pool.canReadFromTape()
&& poolCanStageFile(pool, fileAttributes))
|| (type == DirectionType.WRITE && pool.canWrite())
|| (type == DirectionType.P2P && pool.canWriteForP2P()))
&& (_allPoolsActive || pool.isActive())) {
if (exclude.test(pool.getName())) {
LOGGER.debug(
"Qualifying pool {} is on excluded host {}; skipping.",
pool.getName(),
pool.getCanonicalHostName());
} else {
resultList.add(pool.getName());
}
}
}
}
}
}
result[i] = new PoolPreferenceLevel(resultList, tag);
}
return result;
}
private void logResult(PoolPreferenceLevel[] result) {
StringBuilder sb = new StringBuilder("match done: ");
for (int i = 0; i < result.length; i++) {
sb.append("[").append(i).append("] :");
for (String poolName : result[i].getPoolList()) {
sb.append(" ").append(poolName);
}
}
LOGGER.debug(sb.toString());
}
private String printPreferenceLevels(PoolPreferenceLevel[] list) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.length; i++) {
String tag = list[i].getTag();
sb.append("Preference : ").append(i).append("\n");
sb.append(" Tag : ").append(tag == null ? "NONE" : tag)
.append("\n");
for (String s : list[i].getPoolList()) {
sb.append(" ").append(s)
.append("\n");
}