/
RequestContainerV5.java
2174 lines (1920 loc) · 81.7 KB
/
RequestContainerV5.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 com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ListenableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.CheckStagePermission;
import diskCacheV111.util.CostException;
import diskCacheV111.util.DestinationCostException;
import diskCacheV111.util.FileNotInCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.util.SourceCostException;
import diskCacheV111.vehicles.DCapProtocolInfo;
import diskCacheV111.vehicles.IpProtocolInfo;
import diskCacheV111.vehicles.Pool2PoolTransferMsg;
import diskCacheV111.vehicles.PoolFetchFileMessage;
import diskCacheV111.vehicles.PoolHitInfoMessage;
import diskCacheV111.vehicles.PoolMgrReplicateFileMsg;
import diskCacheV111.vehicles.PoolMgrSelectReadPoolMsg;
import diskCacheV111.vehicles.PoolStatusChangedMessage;
import diskCacheV111.vehicles.ProtocolInfo;
import diskCacheV111.vehicles.RestoreHandlerInfo;
import diskCacheV111.vehicles.StorageInfo;
import diskCacheV111.vehicles.WarningPnfsFileInfoMessage;
import dmg.cells.nucleus.AbstractCellComponent;
import dmg.cells.nucleus.CDC;
import dmg.cells.nucleus.CellAddressCore;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.cells.nucleus.CellMessage;
import dmg.cells.nucleus.CellMessageReceiver;
import dmg.cells.nucleus.CellPath;
import dmg.cells.nucleus.CellSetupProvider;
import dmg.cells.nucleus.NoRouteToCellException;
import dmg.cells.nucleus.UOID;
import dmg.util.CommandException;
import dmg.util.command.Argument;
import dmg.util.command.Command;
import org.dcache.cells.CellStub;
import org.dcache.poolmanager.Partition;
import org.dcache.poolmanager.PartitionManager;
import org.dcache.poolmanager.PoolInfo;
import org.dcache.poolmanager.PoolManagerGetRestoreHandlerInfo;
import org.dcache.poolmanager.PoolSelector;
import org.dcache.poolmanager.SelectedPool;
import org.dcache.util.Args;
import org.dcache.util.FireAndForgetTask;
import org.dcache.vehicles.FileAttributes;
import static com.google.common.base.Preconditions.checkArgument;
import static dmg.util.CommandException.checkCommand;
import static java.util.stream.Collectors.toList;
import static diskCacheV111.poolManager.RequestContainerV5.StateType.*;
import static java.util.Objects.requireNonNull;
public class RequestContainerV5
extends AbstractCellComponent
implements Runnable, CellCommandListener, CellMessageReceiver, CellSetupProvider, CellInfoProvider
{
private static final Logger _log =
LoggerFactory.getLogger(RequestContainerV5.class);
protected enum StateType {
/**
* A TRANSITORY state is one in which a call to stateEngine method is
* guaranteed to change the state. Such states require no (external)
* stimulus.
*/
TRANSITORY,
/**
* A WAITING state is one in which the request is waiting asynchronously
* for some external event. Such states require some (external)
* stimulus to trigger a change in state.
*/
WAITING
}
/**
* The various states that a request can adopt as it is being processed.
*/
public enum RequestState {
/** The initial request state. */
ST_INIT(TRANSITORY),
/**
* Processing is complete and the outcome of the request has been
* determined. Some final steps are still needed; for example, sending
* cell messages to inform the doors of the result.
*/
ST_DONE(TRANSITORY),
/**
* It has been determined that the request cannot be satisfied as-is and
* a pool-to-pool copy is required. The pool-to-pool copy is to be
* initiated.
*/
ST_POOL_2_POOL(TRANSITORY),
/**
* It has been determined that the request cannot be satisfied as-is and
* the file should be staged back from tape. The staging request is to
* be initiated.
*/
ST_STAGE(TRANSITORY),
/**
* A pool has been requested to stage a file. Waiting for that stage
* request to complete.
*/
ST_WAITING_FOR_STAGING(WAITING),
/**
* A pool has been requested to create a replica: a pool-to-pool copy.
* Waiting for that pool-to-pool request to complete.
*/
ST_WAITING_FOR_POOL_2_POOL(WAITING),
/**
* No further processing is currently possible. External changes (such
* as pools becoming available or manual intervention) may trigger a
* change in state.
*/
ST_SUSPENDED(WAITING),
/** All processing is now completed. Nothing further to do. */
ST_OUT(TRANSITORY);
private final StateType type;
public boolean is(StateType type)
{
return this.type == type;
}
RequestState(StateType type)
{
this.type = type;
}
}
private static final String POOL_UNKNOWN_STRING = "<unknown>" ;
private static final String STRING_NEVER = "never" ;
private static final String STRING_BESTEFFORT = "besteffort" ;
private static final String STRING_NOTCHECKED = "notchecked" ;
/** value in milliseconds */
private static final int DEFAULT_TICKER_INTERVAL = 60000;
private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("MM.dd HH:mm:ss");
private final Map<UOID, PoolRequestHandler> _messageHash = new HashMap<>() ;
private final Map<String, PoolRequestHandler> _handlerHash = new HashMap<>() ;
private CellStub _billing;
private CellStub _poolStub;
private long _retryTimer = 15 * 60 * 1000 ;
private static final int MAX_REQUEST_CLUMPING = 20;
private String _onError = "suspend" ;
private int _maxRetries = 3 ;
private int _maxRestore = -1 ;
private CheckStagePermission _stagePolicyDecisionPoint;
private boolean _allowAnonymousStaging;
private boolean _sendHitInfo;
private int _restoreExceeded;
private boolean _suspendIncoming;
private boolean _suspendStaging;
private PoolSelectionUnit _selectionUnit;
private PoolMonitorV5 _poolMonitor;
private PnfsHandler _pnfsHandler;
private Executor _executor;
private final Map<PnfsId, CacheException> _selections = new HashMap<>() ;
private PartitionManager _partitionManager ;
private volatile long _checkFilePingTimer = 10 * 60 * 1000 ;
/** value in milliseconds */
private final long _ticketInterval;
private Thread _tickerThread;
private PoolPingThread _poolPingThread;
/**
* Tape Protection.
* allStates defines that all states are allowed.
* allStatesExceptStage defines that all states except STAGE are allowed.
*/
public static final EnumSet<RequestState> allStates =
EnumSet.allOf(RequestState.class);
public static final EnumSet<RequestState> allStatesExceptStage =
EnumSet.complementOf(EnumSet.of(RequestState.ST_STAGE));
/**
* RC state machine states sufficient to access online files.
*/
public static final EnumSet<RequestState> ONLINE_FILES_ONLY
= EnumSet.of(RequestState.ST_INIT, RequestState.ST_DONE);
public RequestContainerV5(long tickerInterval) {
_ticketInterval = tickerInterval;
}
public RequestContainerV5()
{
this(DEFAULT_TICKER_INTERVAL);
}
@Override
public CellSetupProvider mock()
{
RequestContainerV5 mock = new RequestContainerV5();
mock.setPartitionManager(new PartitionManager());
return mock;
}
public void start()
{
_tickerThread = new Thread(this, "Container-ticker");
_tickerThread.start();
_poolPingThread = new PoolPingThread();
_poolPingThread.start();
}
public void shutdown()
{
if (_tickerThread != null) {
_tickerThread.interrupt();
}
if (_poolPingThread != null) {
_poolPingThread.interrupt();
}
}
@Required
public void setPoolSelectionUnit(PoolSelectionUnit selectionUnit)
{
_selectionUnit = selectionUnit;
}
@Required
public void setPoolMonitor(PoolMonitorV5 poolMonitor)
{
_poolMonitor = poolMonitor;
}
@Required
public void setPnfsHandler(PnfsHandler pnfsHandler)
{
_pnfsHandler = pnfsHandler;
}
@Required
public void setPartitionManager(PartitionManager partitionManager)
{
_partitionManager = partitionManager;
}
@Required
public void setExecutor(Executor executor)
{
_executor = executor;
}
public void setHitInfoMessages(boolean sendHitInfo)
{
_sendHitInfo = sendHitInfo;
}
@Required
public void setBilling(CellStub billing)
{
_billing = billing;
}
@Required
public void setPoolStub(CellStub poolStub)
{
_poolStub = poolStub;
}
public void messageArrived(CellMessage envelope, Object message)
{
UOID uoid = envelope.getLastUOID();
PoolRequestHandler handler;
synchronized (_messageHash) {
handler = _messageHash.remove(uoid);
if (handler == null) {
return;
}
}
handler.mailForYou(message);
}
@Override
public void run()
{
while (!Thread.interrupted()) {
try {
Thread.sleep(_ticketInterval) ;
List<PoolRequestHandler> list;
synchronized (_handlerHash) {
list = new ArrayList<>(_handlerHash.values());
}
list.forEach(PoolRequestHandler::checkExpiredRequests);
} catch (InterruptedException e) {
break;
} catch (Throwable t) {
Thread thisThread = Thread.currentThread();
UncaughtExceptionHandler ueh =
thisThread.getUncaughtExceptionHandler();
ueh.uncaughtException(thisThread, t);
}
}
_log.debug("Container-ticker done");
}
public void poolStatusChanged(String poolName, int poolStatus) {
_log.info("Restore Manager : got 'poolRestarted' for {}", poolName);
try {
List<PoolRequestHandler> list;
synchronized (_handlerHash) {
list = new ArrayList<>(_handlerHash.values());
}
for (PoolRequestHandler rph : list) {
switch( poolStatus ) {
case PoolStatusChangedMessage.UP:
/*
* if pool is up, re-try all request scheduled to this pool
* and all requests, which do not have any pool candidates
*
* in this construction we will fall down to next case
*/
if (rph.getPoolCandidate().equals(POOL_UNKNOWN_STRING) ) {
_log.info("Restore Manager : retrying : {}", rph);
rph.retry();
}
case PoolStatusChangedMessage.DOWN:
/*
* if pool is down, re-try all request scheduled to this
* pool
*/
if (rph.getPoolCandidate().equals(poolName) ) {
_log.info("Restore Manager : retrying : {}", rph);
rph.retry();
}
}
}
} catch (RuntimeException e) {
_log.error("Problem retrying pool " + poolName, e);
}
}
@Override
public void getInfo(PrintWriter pw)
{
Partition def = _partitionManager.getDefaultPartition();
pw.println( " Retry Timeout : "+(_retryTimer/1000)+" seconds" ) ;
pw.println( " Thread Controller : "+_executor ) ;
pw.println( " Maximum Retries : "+_maxRetries ) ;
pw.println( " Pool Ping Timer : "+(_checkFilePingTimer/1000) + " seconds" ) ;
pw.println( " On Error : "+_onError ) ;
pw.println( " Allow p2p : "+( def._p2pAllowed ? "on" : "off" )+
" oncost="+( def._p2pOnCost ? "on" : "off" )+
" fortransfer="+( def._p2pForTransfer ? "on" : "off" ) );
pw.println( " Allow staging : "+(def._hasHsmBackend ? "on":"off") ) ;
pw.println( "Allow stage on cost : "+(def._stageOnCost ? "on":"off") ) ;
pw.println( " Restore Limit : "+(_maxRestore<0?"unlimited":(String.valueOf(_maxRestore))));
pw.println( " Restore Exceeded : "+_restoreExceeded ) ;
if( _suspendIncoming ) {
pw.println(" Suspend Incoming : on (not persistent)");
}
if( _suspendStaging ) {
pw.println(" Suspend Staging : on (not persistent)");
}
}
@Override
public void printSetup(PrintWriter pw)
{
pw.append("rc onerror ").println(_onError);
pw.append("rc set max retries ").println(_maxRetries);
pw.append("rc set retry ").println(_retryTimer/1000);
pw.append("rc set poolpingtimer ").println(_checkFilePingTimer/1000);
pw.append("rc set max restore ")
.println(_maxRestore<0?"unlimited":(String.valueOf(_maxRestore)));
}
public static final String hh_rc_set_sameHostCopy =
STRING_NEVER+"|"+STRING_BESTEFFORT+"|"+STRING_NOTCHECKED;
@AffectsSetup
public String ac_rc_set_sameHostCopy_$_1(Args args)
{
_partitionManager.setProperties("default", ImmutableMap.of("sameHostCopy", args.argv(0)));
return "";
}
public static final String hh_rc_set_sameHostRetry =
STRING_NEVER+"|"+STRING_BESTEFFORT+"|"+STRING_NOTCHECKED;
@AffectsSetup
public String ac_rc_set_sameHostRetry_$_1(Args args)
{
_partitionManager.setProperties("default", ImmutableMap.of("sameHostRetry", args.argv(0)));
return "" ;
}
public static final String fh_rc_set_max_restore = "Limit total number of concurrent restores. If the total number of\n" +
"restores reaches this limit then any additional restores will fail;\n" +
"when the total number of restores drops below limit then additional\n" +
"restores will be accepted. Setting the limit to \"0\" will result in\n" +
"all restores failing; setting the limit to \"unlimited\" will remove\n" +
"the limit.";
public static final String hh_rc_set_max_restore = "<maxNumberOfRestores>" ;
@AffectsSetup
public String ac_rc_set_max_restore_$_1( Args args ){
if( args.argv(0).equals("unlimited") ){
_maxRestore = -1 ;
return "" ;
}
int n = Integer.parseInt(args.argv(0));
if( n < 0 ) {
throw new
IllegalArgumentException("must be >=0");
}
_maxRestore = n ;
return "" ;
}
public static final String hh_rc_select = "[<pnfsId> [<errorNumber> [<errorMessage>]] [-remove]]" ;
public String ac_rc_select_$_0_3( Args args ){
synchronized( _selections ){
if( args.argc() == 0 ){
StringBuilder sb = new StringBuilder() ;
for( Map.Entry<PnfsId, CacheException > entry: _selections.entrySet() ){
sb.append(entry.getKey().toString()).
append(" ").
append(entry.getValue().toString()).
append("\n");
}
return sb.toString() ;
}
boolean remove = args.hasOption("remove") ;
PnfsId pnfsId = new PnfsId(args.argv(0));
if( remove ){
_selections.remove( pnfsId ) ;
return "" ;
}
int errorNumber = args.argc() > 1 ? Integer.parseInt(args.argv(1)) : 1 ;
String errorMessage = args.argc() > 2 ? args.argv(2) : ("Failed-"+errorNumber);
_selections.put( pnfsId , new CacheException(errorNumber,errorMessage) ) ;
}
return "" ;
}
public static final String hh_rc_set_warning_path = " # obsolete";
public String ac_rc_set_warning_path_$_0_1( Args args ){
return "";
}
public static final String fh_rc_set_poolpingtimer =
" rc set poolpingtimer <timer/seconds> "+
""+
" If set to a nonzero value, the restore handler will frequently"+
" check the pool whether the request is still pending, failed"+
" or has been successful" +
"";
public static final String hh_rc_set_poolpingtimer = "<checkPoolFileTimer/seconds>" ;
@AffectsSetup
public String ac_rc_set_poolpingtimer_$_1(Args args ){
_checkFilePingTimer = 1000L * Long.parseLong(args.argv(0));
PoolPingThread poolPingThread = _poolPingThread;
if (poolPingThread != null) {
synchronized (poolPingThread) {
poolPingThread.notify();
}
}
return "" ;
}
public static final String hh_rc_set_retry = "<retryTimer/seconds>" ;
@AffectsSetup
public String ac_rc_set_retry_$_1(Args args ){
_retryTimer = 1000L * Long.parseLong(args.argv(0));
return "" ;
}
public static final String hh_rc_set_max_retries = "<maxNumberOfRetries>" ;
@AffectsSetup
public String ac_rc_set_max_retries_$_1(Args args ){
_maxRetries = Integer.parseInt(args.argv(0));
return "" ;
}
public static final String hh_rc_suspend = "[on|off] -all" ;
public String ac_rc_suspend_$_0_1( Args args ){
boolean all = args.hasOption("all") ;
if( args.argc() == 0 ){
if(all) {
_suspendIncoming = true;
}
_suspendStaging = true ;
}else{
String mode = args.argv(0) ;
switch (mode) {
case "on":
if (all) {
_suspendIncoming = true;
}
_suspendStaging = true;
break;
case "off":
if (all) {
_suspendIncoming = false;
}
_suspendStaging = false;
break;
default:
throw new
IllegalArgumentException("Usage : rc suspend [on|off]");
}
}
return "" ;
}
public static final String hh_rc_onerror = "suspend|fail" ;
@AffectsSetup
public String ac_rc_onerror_$_1(Args args ){
String onerror = args.argv(0) ;
if( ( ! onerror.equals("suspend") ) &&
( ! onerror.equals("fail") ) ) {
throw new
IllegalArgumentException("Usage : rc onerror fail|suspend");
}
_onError = onerror ;
return "onerror "+_onError ;
}
public static final String fh_rc_retry =
"NAME\n"+
" rc retry\n\n"+
"SYNOPSIS\n"+
" I) rc retry <pnfsId> [OPTIONS]\n"+
" II) rc retry * -force-all [OPTIONS]\n\n"+
"DESCRIPTION\n"+
" Forces a 'restore request' to be retried.\n"+
" While using syntax I, a single request is retried,\n"+
" syntax II retries all requests which reported an error.\n"+
" If the '-force-all' options is given, all requests are\n"+
" retried, regardless of their current status.\n";
public static final String hh_rc_retry = "<pnfsId>|* -force-all";
public String ac_rc_retry_$_1( Args args )
{
boolean forceAll = args.hasOption("force-all") ;
if( args.argv(0).equals("*") ){
List<PoolRequestHandler> all;
//
// Remember : we are not allowed to call 'retry' as long
// as we are holding the _handlerHash lock.
//
synchronized( _handlerHash ){
all = new ArrayList<>( _handlerHash.values() ) ;
}
all.stream()
.filter(h -> forceAll || h._currentRc != 0)
.forEach(PoolRequestHandler::retry);
}else{
PoolRequestHandler rph;
synchronized( _handlerHash ){
rph = _handlerHash.get(args.argv(0));
if( rph == null ) {
throw new
IllegalArgumentException("Not found : " + args
.argv(0));
}
}
rph.retry() ;
}
return "";
}
@Command(name = "rc failed", hint = "abort a file read request",
description = "Aborts all requests from clients to read a"
+ " particular file. This is typically done when"
+ " the request is suspended and it is impossible for"
+ " dCache to provide that file (for example, the disk"
+ " server with that file has been decomissioned, the tape"
+ " containing that file's data is broken). Although this"
+ " command is useful for recovering from these situations,"
+ " its usage often points to misconfiguration elsewhere in"
+ " dCache.")
public class FailedCommand implements Callable<String>
{
@Argument(usage="The request ID, as shown in the first column of the 'rc ls' command.")
String id;
@Argument(index=1, required=false, usage="The error number to return to the door.")
Integer errorNumber = 1;
@Argument(index=2, required=false, usage="The error message explaining why the transfer failed.")
String errorString = "Operator Intervention";
@Override
public String call() throws CommandException
{
checkCommand(errorNumber >= 0, "Error number must be >= 0");
PoolRequestHandler rph;
synchronized (_handlerHash) {
rph = _handlerHash.get(id);
}
checkCommand(rph != null, "Not found : %s", id);
rph.fail(errorNumber, errorString);
return "";
}
}
public static final String hh_rc_ls = " [<regularExpression>] [-w] [-l] # lists pending requests" ;
public String ac_rc_ls_$_0_1( Args args ){
StringBuilder sb = new StringBuilder() ;
Pattern pattern = args.argc() > 0 ? Pattern.compile(args.argv(0)) : null ;
boolean isLongListing = args.hasOption("l");
if( !args.hasOption("w") ){
List<PoolRequestHandler> allRequestHandlers;
synchronized( _handlerHash ){
allRequestHandlers = new ArrayList<>( _handlerHash.values() ) ;
}
for( PoolRequestHandler h : allRequestHandlers ){
if( h == null ) {
continue;
}
String line = h.toString() ;
if( ( pattern == null ) || pattern.matcher(line).matches() ) {
sb.append(line).append("\n");
if (isLongListing) {
for(CellMessage m: h.getMessages()) {
PoolMgrSelectReadPoolMsg request =
(PoolMgrSelectReadPoolMsg) m.getMessageObject();
sb.append(" ").append(request.getProtocolInfo()).append('\n');
}
}
}
}
}else{
Map<UOID, PoolRequestHandler> allPendingRequestHandlers = new HashMap<>() ;
synchronized(_messageHash){
allPendingRequestHandlers.putAll( _messageHash ) ;
}
for (Map.Entry<UOID, PoolRequestHandler> requestHandler : allPendingRequestHandlers.entrySet()) {
UOID uoid = requestHandler.getKey();
PoolRequestHandler h = requestHandler.getValue();
if (h == null) {
continue;
}
String line = uoid.toString() + " " + h.toString();
if ((pattern == null) || pattern.matcher(line).matches()) {
sb.append(line).append("\n");
}
}
}
return sb.toString();
}
public PoolManagerGetRestoreHandlerInfo messageArrived(PoolManagerGetRestoreHandlerInfo msg) {
msg.setResult(getRestoreHandlerInfo());
return msg;
}
public List<RestoreHandlerInfo> getRestoreHandlerInfo() {
List<RestoreHandlerInfo> requests;
synchronized (_handlerHash) {
requests = _handlerHash.values().stream()
.map(PoolRequestHandler::getRestoreHandlerInfo)
.collect(toList());
}
return requests;
}
public static final String hh_xrc_ls = " # lists pending requests (binary)" ;
public Object ac_xrc_ls( Args args ){
List<PoolRequestHandler> all;
synchronized (_handlerHash) {
all = new ArrayList<>(_handlerHash.values());
}
return all.stream()
.map(PoolRequestHandler::getRestoreHandlerInfo)
.toArray(RestoreHandlerInfo[]::new);
}
public void messageArrived(CellMessage envelope,
PoolMgrSelectReadPoolMsg request)
throws PatternSyntaxException, IOException
{
boolean enforceP2P = false ;
PnfsId pnfsId = request.getPnfsId() ;
String poolGroup = request.getPoolGroup();
ProtocolInfo protocolInfo = request.getProtocolInfo() ;
EnumSet<RequestState> allowedStates = request.getAllowedStates();
String hostName;
if (protocolInfo instanceof IpProtocolInfo) {
InetSocketAddress target = ((IpProtocolInfo)protocolInfo).getSocketAddress();
hostName = target.isUnresolved() ? target.getHostString() : target.getAddress().getHostAddress();
} else {
hostName = "NoSuchHost";
}
String netName = _selectionUnit.getNetIdentifier(hostName);
String protocolNameFromInfo = protocolInfo.getProtocol()+"/"+protocolInfo.getMajorVersion() ;
String protocolName = _selectionUnit.getProtocolUnit( protocolNameFromInfo ) ;
if( protocolName == null ) {
throw new
IllegalArgumentException("Protocol not found : "+protocolNameFromInfo);
}
if( request instanceof PoolMgrReplicateFileMsg ){
if( request.isReply() ){
_log.warn("Unexpected PoolMgrReplicateFileMsg arrived (is a reply)");
return ;
}else{
enforceP2P = true ;
}
}
String canonicalName = pnfsId +"@"+netName+"-"+protocolName+(enforceP2P?"-p2p":"")
+(poolGroup == null ? "" : ("-pg-" + poolGroup));
PoolRequestHandler handler;
_log.info( "Adding request for : {}", canonicalName ) ;
synchronized( _handlerHash ){
handler = _handlerHash.computeIfAbsent(canonicalName, n ->
new PoolRequestHandler(pnfsId,
poolGroup,
n,
allowedStates));
handler.addRequest(envelope) ;
}
}
// replicate a file
public static final String hh_replicate = " <pnfsid> <client IP>";
public String ac_replicate_$_2(Args args) {
String commandReply = "Replication initiated...";
try {
FileAttributes fileAttributes =
_pnfsHandler.getFileAttributes(new PnfsId(args.argv(0)),
PoolMgrReplicateFileMsg.getRequiredAttributes());
// TODO: call p2p direct
// send message to yourself
PoolMgrReplicateFileMsg req =
new PoolMgrReplicateFileMsg(fileAttributes,
new DCapProtocolInfo("DCap", 3, 0,
new InetSocketAddress(args.argv(1),
2222)));
sendMessage( new CellMessage(new CellAddressCore("PoolManager"), req) );
} catch (CacheException e) {
commandReply = "P2P failed : " + e.getMessage();
}
return commandReply;
}
/**
* Return Codes used in PoolRequestHandler
*/
public enum RequestStatusCode {
OK,
FOUND,
NOT_FOUND,
ERROR,
OUT_OF_RESOURCES,
COST_EXCEEDED,
NOT_PERMITTED,
S_COST_EXCEEDED,
DELAY
}
///////////////////////////////////////////////////////////////
//
// the read io request handler
//
private class PoolRequestHandler {
protected final PnfsId _pnfsId;
protected final String _poolGroup;
protected final List<CellMessage> _messages = new ArrayList<>() ;
protected int _retryCounter;
private final CDC _cdc = new CDC();
private UOID _waitingFor;
private String _status = "[<idle>]";
private volatile RequestState _state = RequestState.ST_INIT;
private final Collection<RequestState> _allowedStates;
private boolean _stagingDenied;
private int _currentRc;
private String _currentRm = "" ;
/**
* The best pool found by askIfAvailable(). In contrast to
* _poolCandidateInfo, _bestPool may be set even when
* askIfAvailable() returns with an error. Eg when the best
* pool is too expensive.
*/
private SelectedPool _bestPool;
/**
* The pool from which to read the file or the pool to which
* to stage the file. Set by askIfAvailable() when it returns
* RequestStatusCode.FOUND, by exercisePool2PoolReply() when it returns
* RequestStatusCode.OK, and by askForStaging(). Also set in the
* stateEngine() at various points.
*/
private volatile SelectedPool _poolCandidate;
/**
* The pool used for staging.
*
* Serves a critical role when retrying staging to avoid that
* the same pool is chosen twice in a row.
*/
private Optional<SelectedPool> _stageCandidate = Optional.empty();
/**
* The destination of a pool to pool transfer. Set by
* askForPoolToPool() when it returns RequestStatusCode.FOUND.
*/
private volatile SelectedPool _p2pDestinationPool;
/**
* The source of a pool to pool transfer. Set by
* askForPoolToPool() when it return RequestStatusCode.FOUND.
*/
private SelectedPool _p2pSourcePool;
private final long _started = System.currentTimeMillis() ;
private final String _name;
private FileAttributes _fileAttributes;
private StorageInfo _storageInfo;
private ProtocolInfo _protocolInfo;
private String _linkGroup;
private String _billingPath;
private String _transferPath;
private boolean _enforceP2P;
private int _destinationFileStatus = Pool2PoolTransferMsg.UNDETERMINED ;
private PoolSelector _poolSelector;
private Partition _parameter = _partitionManager.getDefaultPartition();
/**
* Indicates the next time a TTL of a request message will be
* exceeded.
*/
private long _nextTtlTimeout = Long.MAX_VALUE;
private boolean _failOnExcluded;
public PoolRequestHandler(PnfsId pnfsId,
String poolGroup,
String canonicalName,
Collection<RequestState> allowedStates)
{
_pnfsId = pnfsId ;
_poolGroup = poolGroup;
_name = canonicalName ;
_allowedStates = allowedStates ;
}
//...........................................................
//
// the following methods can be called from outside
// at any time.
//...........................................................
//
// add request is assumed to be synchronized by a higher level.
//
public void addRequest( CellMessage message ){
PoolMgrSelectReadPoolMsg request =
(PoolMgrSelectReadPoolMsg)message.getMessageObject() ;
// fail-fast if state is not allowed
if (!request.getAllowedStates().contains(_state)) {
request.setFailed(CacheException.PERMISSION_DENIED, "Pool manager state not allowed");
message.revertDirection();
sendMessage(message);
return;
}
_messages.add(message);
_stagingDenied = false;
long ttl = message.getTtl();
if (ttl < Long.MAX_VALUE) {
long timeout = System.currentTimeMillis() + ttl;
_nextTtlTimeout = Math.min(_nextTtlTimeout, timeout);
}
if (_poolSelector != null) {
return;
}
_linkGroup = request.getLinkGroup();
_protocolInfo = request.getProtocolInfo();
_fileAttributes = request.getFileAttributes();
_storageInfo = _fileAttributes.getStorageInfo();
_billingPath = request.getBillingPath();
_transferPath = request.getTransferPath();
_retryCounter = request.getContext().getRetryCounter();
_stageCandidate = Optional.ofNullable(request.getContext().getPreviousStagePool());
if( request instanceof PoolMgrReplicateFileMsg ){
_enforceP2P = true ;
_destinationFileStatus = ((PoolMgrReplicateFileMsg)request).getDestinationFileStatus() ;
}
Set<String> excluded = request.getExcludedHosts();
_failOnExcluded = excluded != null && !excluded.isEmpty();
_poolSelector =
_poolMonitor.getPoolSelector(_fileAttributes,
_protocolInfo,
_linkGroup,
excluded);
//
//
//
add(null) ;
}
public List<CellMessage> getMessages() {
synchronized( _handlerHash ){
return new ArrayList<>(_messages);