-
Notifications
You must be signed in to change notification settings - Fork 131
/
FileOperationHandler.java
844 lines (728 loc) · 33.6 KB
/
FileOperationHandler.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
/*
COPYRIGHT STATUS:
Dec 1st 2001, Fermi National Accelerator Laboratory (FNAL) documents and
software are sponsored by the U.S. Department of Energy under Contract No.
DE-AC02-76CH03000. Therefore, the U.S. Government retains a world-wide
non-exclusive, royalty-free license to publish or reproduce these documents
and software for U.S. Government purposes. All documents and software
available from this server are protected under the U.S. and Foreign
Copyright Laws, and FNAL reserves all rights.
Distribution of the software available from this server is free of
charge subject to the user following the terms of the Fermitools
Software Legal Information.
Redistribution and/or modification of the software shall be accompanied
by the Fermitools Software Legal Information (including the copyright
notice).
The user is asked to feed back problems, benefits, and/or suggestions
about the software to the Fermilab Software Providers.
Neither the name of Fermilab, the URA, nor the names of the contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
DISCLAIMER OF LIABILITY (BSD):
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FERMILAB,
OR THE URA, OR THE U.S. DEPARTMENT of ENERGY, OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Liabilities of the Government:
This software is provided by URA, independent from its Prime Contract
with the U.S. Department of Energy. URA is acting independently from
the Government and in its own private capacity and is not acting on
behalf of the U.S. Government, nor as its contractor nor its agent.
Correspondingly, it is understood and agreed that the U.S. Government
has no connection to this software and in no manner whatsoever shall
be liable for nor assume any responsibility or obligation for any claim,
cost, or damages arising out of or resulting from the use of the software
available from this server.
Export Control:
All documents and software available from this server are subject to U.S.
export control laws. Anyone downloading information from this server is
obligated to secure any necessary Government licenses before exporting
documents or software obtained from this server.
*/
package org.dcache.resilience.handlers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.PnfsId;
import diskCacheV111.util.RetentionPolicy;
import diskCacheV111.util.SpreadAndWait;
import diskCacheV111.vehicles.HttpProtocolInfo;
import diskCacheV111.vehicles.PoolCheckFileMessage;
import diskCacheV111.vehicles.PoolManagerPoolInformation;
import dmg.cells.nucleus.CellPath;
import org.dcache.alarms.AlarmMarkerFactory;
import org.dcache.alarms.PredefinedAlarm;
import org.dcache.cells.CellStub;
import org.dcache.pool.migration.PoolMigrationCopyFinishedMessage;
import org.dcache.pool.migration.PoolSelectionStrategy;
import org.dcache.pool.migration.Task;
import org.dcache.pool.migration.TaskParameters;
import org.dcache.pool.repository.ReplicaState;
import org.dcache.pool.repository.StickyRecord;
import org.dcache.resilience.data.FileOperation;
import org.dcache.resilience.data.FileOperationMap;
import org.dcache.resilience.data.FileUpdate;
import org.dcache.resilience.data.MessageType;
import org.dcache.resilience.data.PoolInfoMap;
import org.dcache.resilience.data.StorageUnitConstraints;
import org.dcache.resilience.db.NamespaceAccess;
import org.dcache.resilience.util.CacheExceptionUtils;
import org.dcache.resilience.util.DegenerateSelectionStrategy;
import org.dcache.resilience.util.ExceptionMessage;
import org.dcache.resilience.util.LocationSelectionException;
import org.dcache.resilience.util.LocationSelector;
import org.dcache.resilience.util.RemoveLocationExtractor;
import org.dcache.resilience.util.ResilientFileTask;
import org.dcache.resilience.util.StaticSinglePoolList;
import org.dcache.util.CacheExceptionFactory;
import org.dcache.vehicles.FileAttributes;
import org.dcache.vehicles.resilience.RemoveReplicaMessage;
/**
* <p>Principal resilience logic component.</p>
*
* <p>Contains methods for registering a pnfsid for handling and
* for updating the number of times it should be processed (based
* on the arrival of update messages), for verifying if some
* action indeed needs to be taken, for launching a copy/migration
* task and for eliminating an excess copy.</p>
*
* <p>Class is not marked final for stubbing/mocking purposes.</p>
*/
public class FileOperationHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(
FileOperationHandler.class);
private static final Logger ACTIVITY_LOGGER =
LoggerFactory.getLogger("org.dcache.resilience-log");
private static final String INCONSISTENT_LOCATIONS_ALARM
= "Resilience has detected an inconsistency or lag between "
+ "the namespace replica locations and the actual locations on disk.";
private static final ImmutableList<StickyRecord> ONLINE_STICKY_RECORD
= ImmutableList.of(
new StickyRecord("system", StickyRecord.NON_EXPIRING));
private static final RateLimiter LIMITER = RateLimiter.create(0.001);
private static void sendOutOfSyncAlarm() {
/*
* Create a new alarm every hour by keying the alarm to
* an hourly timestamp. Otherwise, the alarm counter will
* just be updated for each alarm sent. The rate limiter
* will not alarm more than once every 1000 seconds (once every
* 15 minutes).
*/
if (LIMITER.tryAcquire()) {
LOGGER.warn(AlarmMarkerFactory.getMarker(
PredefinedAlarm.RESILIENCE_LOC_SYNC_ISSUE,
Instant.now().truncatedTo(ChronoUnit.HOURS).toString()),
INCONSISTENT_LOCATIONS_ALARM);
}
}
/**
* <p>For communication with the {@link ResilientFileTask}.</p>
*/
public enum Type {
COPY,
REMOVE,
VOID
}
private final PoolSelectionStrategy taskSelectionStrategy
= new DegenerateSelectionStrategy();
private FileOperationMap fileOpMap;
private PoolInfoMap poolInfoMap;
private NamespaceAccess namespace;
private LocationSelector locationSelector;
private CellStub pinManager;
private CellStub pools;
private ScheduledExecutorService taskService;
private ScheduledExecutorService migrationTaskService;
private FileTaskCompletionHandler completionHandler;
private InaccessibleFileHandler inaccessibleFileHandler;
private long launchDelay = 0L;
private TimeUnit launchDelayUnit = TimeUnit.SECONDS;
public ScheduledExecutorService getTaskService() {
return taskService;
}
public ScheduledExecutorService getRemoveService() {
return migrationTaskService;
}
public long getLaunchDelay() {
return launchDelay;
}
public TimeUnit getLaunchDelayUnit() {
return launchDelayUnit;
}
public void handleBrokenFileLocation(PnfsId pnfsId, String pool) {
try {
FileAttributes attributes
= FileUpdate.getAttributes(pnfsId, pool,
MessageType.CORRUPT_FILE,
namespace);
if (attributes == null) {
LOGGER.trace("{} not ONLINE.", pnfsId);
return;
}
if (!poolInfoMap.isResilientPool(pool)) {
LOGGER.trace("{} not in resilient group.", pool);
return;
}
Collection<String> locations = attributes.getLocations();
int actual = locations.size();
int countable = poolInfoMap.getCountableLocations(locations);
if (actual <= 1) {
/*
* This is the only copy, or it is not/no longer in the
* namespace. In either case, do nothing.
*/
LOGGER.error(AlarmMarkerFactory.getMarker(PredefinedAlarm.INACCESSIBLE_FILE,
pnfsId.toString()),
"{}: Repair of broken replicas is not possible, "
+ "file currently inaccessible", pnfsId);
return;
}
removeTarget(pnfsId, pool);
if (countable > 1) {
FileUpdate update = new FileUpdate(pnfsId, pool,
MessageType.CLEAR_CACHE_LOCATION,
false);
/*
* Bypass the message guard check of CDC session.
*/
handleLocationUpdate(update);
} else {
/*
* No alternate readable source; cannot attempt to make
* any further replicas.
*/
LOGGER.error(AlarmMarkerFactory.getMarker(PredefinedAlarm.INACCESSIBLE_FILE,
pnfsId.toString()),
"{}: Repair of broken replicas is not possible, "
+ "file currently inaccessible", pnfsId);
}
} catch (CacheException e) {
LOGGER.error("Error during handling of broken file removal ({}, {}): {}",
pnfsId, pool, new ExceptionMessage(e));
}
}
/**
* <p>The entry method for a PnfsId operation from a location update, called
* in response to an incoming message.</p>
*
* <p>If the entry is already in the current map, its count is incremented.</p>
*
* <p>A check is then made to see if the source belongs to a resilient
* pool group. If not, the update is discarded.</p>
*
* <p>All attributes of the file that are necessary for resilience
* processing are then fetched. Thereafter a series of preliminary
* checks are run for other disqualifying conditions. If the pnfsId
* does qualify, an entry is added to the {@link FileOperationMap}.</p>
*
* @return true if a new operation is added to the map.
*/
public boolean handleLocationUpdate(FileUpdate data)
throws CacheException {
LOGGER.trace("handleLocationUpdate {}", data);
if (data.pool == null) {
LOGGER.debug("Update of {} with no location; file has likely "
+ "been deleted from namespace.",
data.pnfsId);
return false;
}
if (!data.verifyPoolGroup(poolInfoMap)) {
LOGGER.debug("Handle location update ({}, {}, {}; "
+ "pool is not a member "
+ "of a resilient group.",
data.pnfsId, data.pool, data.getGroup());
return false;
}
/*
* Prefetch all necessary file attributes, including current locations.
*/
if (!data.validateAttributes(namespace)) {
/*
* Could be the result of a delete from namespace triggering a
* clear cache location message.
*/
return false;
}
/*
* Determine if action needs to be taken (counts).
*/
if (!data.validateForAction(null, poolInfoMap, locationSelector)) {
return false;
}
LOGGER.trace("handleLocationUpdate, update to be registered: {}", data);
return fileOpMap.register(data);
}
/**
* <p>The entry method for a PnfsId operation from a pool scan task.</p>
*
* <p>If the entry is already in the current map, its count is incremented.</p>
*
* <p>All attributes of the file that are necessary for resilience
* processing are then fetched. Preliminary checks run for disqualifying
* conditions here include whether this is a storage unit modification,
* in which case the task is registered if the file has the storage unit
* in question. Otherwise, verification proceeds as in the
* {@link #handleLocationUpdate(FileUpdate)} method.</p>
*
* @return true if a new operation is added to the map.
*/
public boolean handleScannedLocation(FileUpdate data, Integer storageUnit)
throws CacheException {
LOGGER.debug("handleScannedLocation {}", data);
/*
* Prefetch all necessary file attributes, including current locations.
*/
if (!data.validateAttributes(namespace)) {
/*
* Could be the result of deletion from namespace during the scan.
*/
return false;
}
data.verifyPoolGroup(poolInfoMap);
/*
* Determine if action needs to be taken.
*/
if (!data.validateForAction(storageUnit, poolInfoMap, locationSelector)) {
return false;
}
LOGGER.debug("handleScannedLocation, update to be registered: {}", data);
return fileOpMap.register(data);
}
/**
* <p>Wraps the creation of a migration {@link Task}. The task is given
* a static single pool list and a degenerate selection strategy,
* since the target has already been selected by this handler.</p>
*/
public Task handleMakeOneCopy(FileAttributes attributes) {
PnfsId pnfsId = attributes.getPnfsId();
FileOperation operation = fileOpMap.getOperation(pnfsId);
/*
* Fire-and-forget best effort.
*/
operation.ensureSticky(poolInfoMap, pools);
LOGGER.trace("Configuring migration task for {}.", pnfsId);
StaticSinglePoolList list;
try {
list = new StaticSinglePoolList(poolInfoMap.getPoolManagerInfo(operation.getTarget()));
} catch (NoSuchElementException e) {
CacheException exception = CacheExceptionUtils.getCacheException(
CacheException.NO_POOL_CONFIGURED,
"Copy %s, could not get PoolManager info for %s: %s.",
pnfsId, poolInfoMap.getPool(operation.getTarget()),
e);
completionHandler.taskFailed(pnfsId, exception);
return null;
}
String source = poolInfoMap.getPool(operation.getSource());
TaskParameters taskParameters = new TaskParameters(
pools,
null, // PnfsManager cell stub not used
pinManager,
migrationTaskService,
taskSelectionStrategy,
list,
false, // eager; update should not happen
false, // isMetaOnly; just move the metadata
false, // compute checksum on update; should not happen
false, // force copy even if pool not readable
true, // maintain atime
1);
Task task = new Task(taskParameters, completionHandler, source, pnfsId,
ReplicaState.CACHED, ONLINE_STICKY_RECORD,
Collections.EMPTY_LIST, attributes,
attributes.getAccessTime());
if (ACTIVITY_LOGGER.isInfoEnabled()) {
List<String> allPools = list.getPools().stream()
.map(PoolManagerPoolInformation::getName)
.collect(Collectors.toList());
ACTIVITY_LOGGER.info("Initiating replication of {} from {} to"
+ " pools: {}, offline: {}", pnfsId, source, allPools,
list.getOfflinePools());
}
LOGGER.trace("Created migration task for {}: source {}, list {}.",
pnfsId, source, list);
return task;
}
/**
* @param message returned by pool migration task, needs to be passed
* to the migration task.
*/
public void handleMigrationCopyFinished(
PoolMigrationCopyFinishedMessage message) {
LOGGER.trace("Migration copy finished {}", message);
try {
fileOpMap.updateOperation(message);
} catch (IllegalStateException e) {
/*
* We treat the missing entry benignly, as it is
* possible to have a race between removal from forced cancellation
* and the arrival of the message from the pool.
*/
LOGGER.trace("{}", new ExceptionMessage(e));
}
}
/**
* <p>Calls {@link #removeTarget(PnfsId, String)} and then reports
* success or failure to the completion handler.</p>
*/
public void handleRemoveOneCopy(FileAttributes attributes) {
PnfsId pnfsId = attributes.getPnfsId();
FileOperation operation = fileOpMap.getOperation(pnfsId);
try {
String target = poolInfoMap.getPool(operation.getTarget());
LOGGER.trace("handleRemoveOneCopy {}, removing {}.", pnfsId,
target);
removeTarget(pnfsId, target);
} catch (CacheException e) {
completionHandler.taskFailed(pnfsId, e);
}
completionHandler.taskCompleted(pnfsId);
}
/**
* <p>Called when a pnfsid has been selected from the operation map for
* possible processing. Refreshes locations from namespace, and checks
* which of those are currently readable. Sends an alarm if
* no operation can occur but should.</p>
*
* @return COPY, REMOVE, or VOID if no operation is necessary.
*/
public Type handleVerification(FileAttributes attributes) {
PnfsId pnfsId = attributes.getPnfsId();
FileOperation operation = fileOpMap.getOperation(pnfsId);
int gindex = operation.getPoolGroup();
/*
* Note that the location-dependent checks are run on this thread
* instead of being pre-checked by the FileOperationMap consumer thread
* because they require a call to the database.
*/
try {
namespace.refreshLocations(attributes);
} catch (CacheException e) {
CacheException exception = CacheExceptionUtils.getCacheException(e.getRc(),
FileTaskCompletionHandler.VERIFY_FAILURE_MESSAGE,
pnfsId, null, e.getCause());
completionHandler.taskFailed(pnfsId, exception);
return Type.VOID;
}
Collection<String> locations = attributes.getLocations();
LOGGER.trace("handleVerification {}, locations from namespace: {}",
pnfsId, locations);
/*
* Somehow, all the cache locations for this file have been removed.
*/
if (locations.isEmpty()) {
return inaccessibleFileHandler.handleNoLocationsForFile(operation);
}
locations = poolInfoMap.getMemberLocations(gindex, locations);
LOGGER.trace("handleVerification {}, valid group member locations {}",
pnfsId, locations);
/*
* If all the locations are pools no longer belonging to the group,
* the operation should be voided.
*/
if (locations.isEmpty()) {
fileOpMap.voidOperation(pnfsId);
return Type.VOID;
}
/*
* If we have arrived here, we are expecting there to be an
* available source file. So we need the strictly readable
* locations, not just "countable" ones.
*/
Set<String> namespaceReadable
= poolInfoMap.getReadableLocations(locations);
Set<String> verifiedReadable;
try {
verifiedReadable = verifyLocations(pnfsId,
namespaceReadable,
pools);
} catch (InterruptedException e) {
LOGGER.trace("handleVerification, {}, verify pool "
+ "locations interrupted; "
+ "cancelling operation", pnfsId);
completionHandler.taskCancelled(pnfsId);
return Type.VOID;
}
LOGGER.trace("handleVerification, {}, namespace readable locations {},"
+ "verified readable locations {}", pnfsId,
namespaceReadable, verifiedReadable);
if (namespaceReadable.size() != verifiedReadable.size()) {
ACTIVITY_LOGGER.info("The namespace is not in sync with the pool "
+ "repositories for {}: "
+ "namespace locations "
+ "that are readable: {}; "
+ "actually found: {}.",
pnfsId, namespaceReadable, verifiedReadable);
sendOutOfSyncAlarm();
}
if (inaccessibleFileHandler.isInaccessible(verifiedReadable, operation)) {
LOGGER.trace("handleVerification {}, no readable locations found, "
+ "checking to see if "
+ "file can be staged.", pnfsId);
return inaccessibleFileHandler.handleInaccessibleFile(operation);
}
if (shouldEvictALocation(operation, verifiedReadable)) {
LOGGER.trace("handleVerification, location should be evicted {}",
verifiedReadable);
return Type.REMOVE;
}
LOGGER.trace("handleVerification after eviction check, {}, locations {}",
pnfsId, locations);
return determineTypeFromConstraints(operation,
locations,
verifiedReadable);
}
public void setCompletionHandler(
FileTaskCompletionHandler completionHandler) {
this.completionHandler = completionHandler;
}
public void setFileOpMap(FileOperationMap fileOpMap) {
this.fileOpMap = fileOpMap;
}
public void setInaccessibleFileHandler(
InaccessibleFileHandler inaccessibleFileHandler) {
this.inaccessibleFileHandler = inaccessibleFileHandler;
}
public void setLaunchDelay(long launchDelay) {
this.launchDelay = launchDelay;
}
public void setLaunchDelayUnit(TimeUnit launchDelayUnit) {
this.launchDelayUnit = launchDelayUnit;
}
public void setLocationSelector(LocationSelector locationSelector) {
this.locationSelector = locationSelector;
}
public void setNamespace(NamespaceAccess namespace) {
this.namespace = namespace;
}
public void setPinManagerStub(CellStub pinManager) {
this.pinManager = pinManager;
}
public void setPoolInfoMap(PoolInfoMap poolInfoMap) {
this.poolInfoMap = poolInfoMap;
}
public void setPoolStub(CellStub pools) {
this.pools = pools;
}
public void setMigrationTaskService(ScheduledExecutorService migrationTaskService) {
this.migrationTaskService = migrationTaskService;
}
public void setTaskService(ScheduledExecutorService taskService) {
this.taskService = taskService;
}
/**
* <p>Checks the readable locations against the requirements.
* If previous operations on this pnfsId have already satisfied them,
* the operation should be voided.</p>
*
* @return the type of operation which should take place, if any.
*/
private Type determineTypeFromConstraints(FileOperation operation,
Collection<String> locations,
Set<String> readableLocations) {
PnfsId pnfsId = operation.getPnfsId();
Integer gindex = operation.getPoolGroup();
Integer sindex = operation.getStorageUnit();
LOGGER.trace("determineTypeFromConstraints {}, group {}, unit {}.",
pnfsId, gindex, sindex);
StorageUnitConstraints constraints
= poolInfoMap.getStorageUnitConstraints(sindex);
Set<String> excluded = poolInfoMap.getExcludedLocationNames(locations);
readableLocations = Sets.difference(readableLocations, excluded);
int required = constraints.getRequired();
int missing = required - readableLocations.size();
/*
* First compute the missing files on the basis of just the readable
* files. If this is positive, recompute by adding in all the
* excluded locations. If these satisfy the requirement, void
* the operation. Do no allow removes in this case, since this
* would imply decreasing already deficient locations.
*/
if (missing > 0) {
missing -= excluded.size();
if (missing < 0) {
missing = 0;
}
}
Collection<String> tags = constraints.getOneCopyPer();
LOGGER.trace("{}, readable locations {}, required {}, missing {}.",
pnfsId, readableLocations, constraints.getRequired(),
missing);
Type type;
String source = null;
String target = null;
try {
/*
* Note that if the operation source or target is preset,
* the selection is skipped.
*/
if (missing < 0) {
type = Type.REMOVE;
Integer pool = operation.getTarget();
if (pool == null || !poolInfoMap.isPoolViable(pool, true)) {
target = locationSelector.selectRemoveTarget(operation,
readableLocations, tags);
}
LOGGER.trace("target to remove: {}", target);
} else if (missing > 0) {
type = Type.COPY;
Integer pool = operation.getSource();
if (pool == null || !poolInfoMap.isPoolViable(pool, false)) {
source = locationSelector.selectCopySource(operation,
readableLocations);
}
LOGGER.trace("source: {}", source);
pool = operation.getTarget();
if (pool == null || !poolInfoMap.isPoolViable(pool, true)) {
target = locationSelector.selectCopyTarget(operation, gindex,
readableLocations, tags);
}
LOGGER.trace("target to copy: {}", target);
} else {
LOGGER.trace("Nothing to do, VOID operation for {}", pnfsId);
fileOpMap.voidOperation(pnfsId);
return Type.VOID;
}
} catch (LocationSelectionException e) {
CacheException exception = CacheExceptionUtils.getCacheException(
CacheException.DEFAULT_ERROR_CODE,
FileTaskCompletionHandler.VERIFY_FAILURE_MESSAGE,
pnfsId, null, e);
completionHandler.taskFailed(pnfsId, exception);
return Type.VOID;
}
fileOpMap.updateOperation(pnfsId, source, target);
return type;
}
/**
* <p>Synchronously removes from the target location the cache entry of the
* pnfsid associated with this task. This is done via a message
* sent to a handler for this purpose on the pool itself.</p>
*/
private void removeTarget(PnfsId pnfsId, String target)
throws CacheException {
RemoveReplicaMessage msg = new RemoveReplicaMessage(target,
pnfsId);
LOGGER.trace("Sending RemoveReplicasMessage {}.", msg);
ACTIVITY_LOGGER.info("Removing {} from {}", pnfsId, target);
Future<RemoveReplicaMessage> future = pools.send(new CellPath(target), msg);
try {
msg = future.get();
LOGGER.trace("Returned ReplicationRepRmMessage {}.", msg);
} catch (InterruptedException | ExecutionException e) {
throw CacheExceptionUtils.getCacheException(
CacheException.SELECTED_POOL_FAILED,
FileTaskCompletionHandler.FAILED_REMOVE_MESSAGE,
pnfsId, target, e);
}
CacheException exception = msg.getErrorObject() == null ? null :
CacheExceptionFactory.exceptionOf(msg);
if (exception != null && !CacheExceptionUtils.replicaNotFound(exception)) {
throw CacheExceptionUtils.getCacheException(
CacheException.SELECTED_POOL_FAILED,
FileTaskCompletionHandler.FAILED_REMOVE_MESSAGE,
pnfsId, target, exception);
}
}
/**
* <p>Checks for necessary eviction due to pool tag changes or
* constraint change. This call will automatically set
* the offending location as the target for a remove operation,
* and will increment the operation count so that there will
* be a chance to repeat the operation in order to make a new copy.</p>
*/
private boolean shouldEvictALocation(FileOperation operation,
Collection<String> readableLocations) {
if (readableLocations.isEmpty()) {
return false;
}
Integer sunit = operation.getStorageUnit();
if (sunit == null) {
return false;
}
StorageUnitConstraints constraints
= poolInfoMap.getStorageUnitConstraints(sunit);
RemoveLocationExtractor extractor
= new RemoveLocationExtractor(
constraints.getOneCopyPer(),
poolInfoMap);
String toEvict = extractor.findALocationToEvict(readableLocations);
if (toEvict != null) {
operation.setTarget(poolInfoMap.getPoolIndex(toEvict));
int count = operation.getOpCount();
operation.setOpCount(++count);
return true;
}
return false;
}
/**
* <p>Called when there are no accessible replicas for the file.</p>
*
* <p>If the file's RetentionPolicy is CUSTODIAL, set the count to 1,
* to make sure the task completes after this. Staging is fire-and-forget,
* and depends on a new add cache location message being processed
* after staging.</p>
*
* @return true if file is CUSTODIAL, false otherwise.
*/
private boolean shouldTryToStage(FileAttributes attributes,
FileOperation operation) {
if (attributes.getRetentionPolicy() == RetentionPolicy.CUSTODIAL) {
LOGGER.trace("shouldTryToStage {}, retention policy is CUSTODIAL.",
operation.getPnfsId());
operation.setOpCount(1);
return true;
}
LOGGER.trace("shouldTryToStage {}, retention policy is not CUSTODIAL",
operation.getPnfsId());
return false;
}
/*
* REVISIT -- this will be expanded into a more general verification procedure
*
* Check the readable pools for the actual existence of the replica.
*/
private Set<String> verifyLocations(PnfsId pnfsId,
Collection<String> locations,
CellStub stub)
throws InterruptedException {
SpreadAndWait<PoolCheckFileMessage> controller = new SpreadAndWait<>(pools);
for(String pool: locations) {
LOGGER.trace("Sending query to {} to verify replica exists.", pool);
PoolCheckFileMessage request = new PoolCheckFileMessage(pool, pnfsId);
controller.send(new CellPath(pool), PoolCheckFileMessage.class, request);
}
controller.waitForReplies();
return controller.getReplies().values()
.stream()
.filter(PoolCheckFileMessage::getHave)
.map(PoolCheckFileMessage::getPoolName)
.collect(Collectors.toSet());
}
}