-
Notifications
You must be signed in to change notification settings - Fork 131
/
DCapDoorInterpreterV3.java
2554 lines (2197 loc) · 91 KB
/
DCapDoorInterpreterV3.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.doors;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
import com.google.common.net.InetAddresses;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import diskCacheV111.poolManager.PoolSelectionUnit.DirectionType;
import diskCacheV111.poolManager.RequestContainerV5;
import diskCacheV111.repository.CacheRepositoryEntryInfo;
import diskCacheV111.util.AccessLatency;
import diskCacheV111.util.CacheException;
import diskCacheV111.util.DCapUrl;
import diskCacheV111.util.FsPath;
import diskCacheV111.util.InvalidMessageCacheException;
import diskCacheV111.util.PermissionDeniedCacheException;
import diskCacheV111.util.PnfsHandler;
import diskCacheV111.util.PnfsId;
import diskCacheV111.util.RetentionPolicy;
import diskCacheV111.util.SpreadAndWait;
import diskCacheV111.vehicles.DCapProtocolInfo;
import diskCacheV111.vehicles.DirRequestMessage;
import diskCacheV111.vehicles.DoorRequestInfoMessage;
import diskCacheV111.vehicles.DoorTransferFinishedMessage;
import diskCacheV111.vehicles.IoDoorEntry;
import diskCacheV111.vehicles.IoDoorInfo;
import diskCacheV111.vehicles.Message;
import diskCacheV111.vehicles.PnfsCreateEntryMessage;
import diskCacheV111.vehicles.PnfsFlagMessage;
import diskCacheV111.vehicles.Pool;
import diskCacheV111.vehicles.PoolAcceptFileMessage;
import diskCacheV111.vehicles.PoolDeliverFileMessage;
import diskCacheV111.vehicles.PoolIoFileMessage;
import diskCacheV111.vehicles.PoolMgrQueryPoolsMsg;
import diskCacheV111.vehicles.PoolMgrSelectPoolMsg;
import diskCacheV111.vehicles.PoolMgrSelectReadPoolMsg;
import diskCacheV111.vehicles.PoolMgrSelectWritePoolMsg;
import diskCacheV111.vehicles.PoolMoverKillMessage;
import diskCacheV111.vehicles.PoolPassiveIoFileMessage;
import diskCacheV111.vehicles.StorageInfo;
import dmg.cells.nucleus.CellAddressCore;
import dmg.cells.nucleus.CellCommandListener;
import dmg.cells.nucleus.CellEndpoint;
import dmg.cells.nucleus.CellInfoProvider;
import dmg.cells.nucleus.CellMessage;
import dmg.cells.nucleus.CellMessageReceiver;
import dmg.cells.nucleus.CellPath;
import dmg.util.CommandException;
import dmg.util.CommandExitException;
import dmg.util.KeepAliveListener;
import org.dcache.acl.enums.AccessMask;
import org.dcache.acl.enums.RsType;
import org.dcache.acl.parser.ACLParser;
import org.dcache.auth.LoginNamePrincipal;
import org.dcache.auth.LoginReply;
import org.dcache.auth.LoginStrategy;
import org.dcache.auth.Origin;
import org.dcache.auth.Subjects;
import org.dcache.auth.attributes.LoginAttributes;
import org.dcache.auth.attributes.Restriction;
import org.dcache.auth.attributes.Restrictions;
import org.dcache.cells.CellStub;
import org.dcache.chimera.UnixPermission;
import org.dcache.namespace.FileAttribute;
import org.dcache.pinmanager.PinManagerPinMessage;
import org.dcache.poolmanager.PoolManagerHandler;
import org.dcache.poolmanager.PoolManagerStub;
import org.dcache.util.Args;
import org.dcache.vehicles.FileAttributes;
import org.dcache.vehicles.PnfsGetFileAttributes;
import org.dcache.vehicles.pool.CacheEntryInfoMessage;
import static org.dcache.namespace.FileAttribute.*;
import static org.dcache.namespace.FileType.DIR;
import static org.dcache.namespace.FileType.REGULAR;
public class DCapDoorInterpreterV3
implements KeepAliveListener, CellMessageReceiver, CellInfoProvider, CellCommandListener
{
private static final int UNDEFINED = -1;
public static final Logger _log =
LoggerFactory.getLogger(DCapDoorInterpreterV3.class);
private final DcapDoorSettings _settings;
/**
* Ascii commands supported by this interpreter.
*/
private enum DcapCommand {
HELLO ("hello"),
BYEBYE ("byebye"),
OPEN ("open"),
CHECK ("check"),
CHGRP ("chgrp"),
CHOWN ("chown"),
CHMOD ("chmod"),
LSTAT ("lstat"),
MKDIR ("mkdir"),
OPENDIR ("opendir"),
PING ("ping"),
RENAME ("rename"),
RMDIR ("rmdir"),
STAGE ("stage"),
STAT ("stat"),
STATUS ("status"),
UNLINK ("unlink");
private static final long serialVersionUID = 8393273905860276227L;
private final String _value;
private static final Map<String, DcapCommand> _commands =
new HashMap<>();
static {
for (DcapCommand command : DcapCommand.values()) {
_commands.put(command.getCommand(), command);
}
}
DcapCommand(String value) {
_value = value;
}
String getCommand() {
return _value;
}
static DcapCommand get(String s) {
DcapCommand command = _commands.get(s);
if(command == null) {
throw new IllegalArgumentException("Unsupported command: " + s);
}
return command;
}
}
private final PrintWriter _out ;
private final CellEndpoint _cell ;
private final CellAddressCore _cellAddress;
private String _ourName = "server" ;
private final ConcurrentMap<Integer,SessionHandler> _sessions = new ConcurrentHashMap<>();
private final CellStub _pinManagerStub;
private final PoolManagerStub _poolMgrStub;
private KafkaProducer _kafkaProducer;
/**
* The client PID set through the hello command. Only used for
* billing purposes.
*/
private String _pid = "<unknown>";
/**
* The client UID set through the hello command. Used for setting
* the owner of new name space entries. Never used for
* authorization.
*/
private int _uid = UNDEFINED;
/**
* The client GID set through the hello command. Used for setting
* the group of new name space entries. Never used for
* authorization.
*/
private int _gid = UNDEFINED;
private Version _version;
private final Date _startedTS;
private Date _lastCommandTS;
private final InetAddress _clientAddress;
/**
* Subjected provided to us as a result of authentication in the
* tunnel.
*/
private final Subject _authenticatedSubject;
private final LoginStrategy _loginStrategy;
// flag defined in batch file to allow/disallow AccessLatency and RetentionPolicy re-definition
public DCapDoorInterpreterV3(CellEndpoint cell, CellAddressCore address, DcapDoorSettings settings,
PrintWriter pw, Subject subject, InetAddress clientAddress,
PoolManagerHandler poolManagerHandler)
{
_out = pw;
_cell = cell;
_cellAddress = address;
_authenticatedSubject = new Subject(true,
subject.getPrincipals(),
subject.getPublicCredentials(),
subject.getPrivateCredentials());
_clientAddress = clientAddress;
_settings = settings;
_poolMgrStub = settings.createPoolManagerStub(cell, address, poolManagerHandler);
_pinManagerStub = settings.createPinManagerStub(cell);
_loginStrategy = settings.createLoginStrategy(cell);
if ( _settings.isKafkaEnabled() ){
_kafkaProducer = settings.createKafkaProducer(_settings.getKafkaBootstrapServer(),
address.toString(),
_settings.getKafkaMaxBlockMs(),
_settings.getKafkaRetries());
}
_startedTS = new Date();
}
private LoginReply login(String user)
throws CacheException
{
Subject subject = new Subject();
subject.getPublicCredentials().addAll(_authenticatedSubject.getPublicCredentials());
subject.getPrivateCredentials().addAll(_authenticatedSubject.getPrivateCredentials());
subject.getPrincipals().addAll(_authenticatedSubject.getPrincipals());
subject.getPrincipals().add(new Origin(_clientAddress));
/* The client can specify a custom user name to be used. */
if (user != null) {
subject.getPrincipals().add(new LoginNamePrincipal(user));
}
LoginReply login = _loginStrategy.login(subject);
_log.info("Login completed for {}", login);
return login;
}
static class Version
{
private final int _major;
private final int _minor;
private final Integer _bugfix;
private final String _package;
@VisibleForTesting
protected Version(int major, int minor)
{
this(major, minor, null, null);
}
@VisibleForTesting
protected Version(int major, int minor, Integer bugfix, String pack)
{
_major = major;
_minor = minor;
_bugfix = bugfix;
_package = pack;
}
/**
* Generate a predicate Version: 1.2 matches 1.2, 1.2.3 and 1.2.3-4.
* @param versionString
*/
Version(String versionString)
{
List<String> values = Splitter.on('.').limit(3).splitToList(versionString);
if (values.size() < 2) {
throw new IllegalArgumentException("Versions requires at least one dot.");
}
try {
_major = Integer.parseInt(values.get(0));
_minor = Integer.parseInt(values.get(1));
if (values.size() > 2) {
int idx = values.get(2).indexOf('-');
if (idx == -1) {
_bugfix = Integer.parseInt(values.get(2));
_package = null;
} else {
_bugfix = Integer.parseInt(values.get(2).substring(0, idx));
_package = values.get(2).substring(idx+1);
}
} else {
_bugfix = null;
_package = null;
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("invalid integer: " + e.getMessage());
}
}
public int getMajor()
{
return _major;
}
public int getMinor()
{
return _minor;
}
/**
* Similar to compareTo but use this Version as a predicate. For
* example if this is Version(1,2) then matches returns
*
* -1 for Version(1,1), Version(1,1,5) and Version(1,1,5,"3")
*
* 0 for Version(1,2), Version(1,2,5) and Version(1,2,5,"3")
*
* 1 for Version(1,3), Version(1,3,5) and Version(1,3,5,"3")
*
* Note that this method is asymmetric if the number of defined
* elements is the same; e.g.,
*
* Version(1,2).matches(Version(1,3)) is 1
* Version(1,3).matches(Version(1,2)) is -1
*
* but not asymmetric if the number of defined elements differs; e.g.,
*
* Version(1,2).matches(Version(1,2,3)) is 0
* Version(1,2,3).matches(Version(1,2)) is 1
*/
public int matches(Version other)
{
ComparisonChain cc = ComparisonChain.start()
.compare(_major, other._major)
.compare(_minor, other._minor);
if (_bugfix != null) {
cc = cc.compare(_bugfix, other._bugfix, Ordering.natural().nullsFirst());
}
if (_package != null) {
cc = cc.compare(_package, other._package, Ordering.natural().nullsFirst());
}
return cc.result();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(_major).append('.').append(_minor);
if (_bugfix != null) {
sb.append('.').append(_bugfix);
}
if (_package != null) {
sb.append('-').append(_package);
}
return sb.toString();
}
@Override
public boolean equals(Object obj)
{
if (obj == this) {
return true;
}
if (!(obj instanceof Version)) {
return false;
}
Version o = (Version) obj;
return Objects.equals(_major, o._major)
&& Objects.equals(_minor, o._minor)
&& Objects.equals(_bugfix, o._bugfix)
&& Objects.equals(_package, o._package);
}
@Override
public int hashCode() {
return Objects.hash(_major, _minor, _bugfix, _package);
}
}
public synchronized void println( String str ){
_log.debug("(DCapDoorInterpreterV3) toclient(println) : {}", str);
_out.println(str);
}
@Override
public void keepAlive(){
for (SessionHandler sh: _sessions.values()){
try{
sh.keepAlive() ;
} catch (Throwable t) {
_log.error("Keep Alive problem in {}: {}", sh, t);
}
}
}
/**
* Convenience method to start a SessionHandler.
*/
private void start(SessionHandler session)
throws CommandException
{
session.start();
}
//////////////////////////////////////////////////////////////////
//
// the command functions String com_<commandName>(int,int,Args)
//
public String com_hello( int sessionId , int commandId , VspArgs args )
throws CommandException
{
if( args.argc() < 2 ) {
throw new
CommandExitException("Command Syntax Exception", 2);
}
try {
int major = Integer.parseInt(args.argv(2));
int minor = Integer.parseInt(args.argv(3));
Integer bugfix = args.argc() > 4 ? Integer.parseInt(args.argv(4)) : null;
String patch = args.argv(5);
_version = new Version(major, minor, bugfix, patch);
} catch (NumberFormatException e) {
_log.error("Syntax error in client version number {} : {}", args, e.toString());
throw new CommandException("Invalid client version number", e);
}
/*
replace current values if alternatives are provided
*/
_pid = args.getOption("pid", _pid);
_uid = args.getIntOption("uid", _uid);
_gid = args.getIntOption("gid", _gid);
_log.debug("Client Version : {}", _version);
if (_settings.getMinClientVersion().matches(_version) > 0 ||
_settings.getMaxClientVersion().matches(_version) < 0) {
_log.error("Client {} (proc \"{}\" running with uid:{} gid:{}) rejected: bad client version: {}",
InetAddresses.toAddrString(_clientAddress), _pid, _uid, _gid, _version);
throw new CommandExitException("Client version rejected : "+_version, 1);
}
String yourName = args.getName() ;
if( yourName.equals("server") ) {
_ourName = "client";
}
return "0 0 "+_ourName+" welcome "+_version.getMajor()+" "+_version.getMinor();
}
public String com_byebye( int sessionId , int commandId , VspArgs args )
throws CommandException
{
throw new CommandExitException("byeBye",commandId) ;
}
public synchronized String com_open( int sessionId , int commandId , VspArgs args )
throws CacheException, CommandException
{
if( args.argc() < 4 ) {
throw new
CommandException(3, "Not enough arguments for put");
}
start(new IoHandler(sessionId,commandId,args));
return null ;
}
public synchronized String com_stage( int sessionId , int commandId , VspArgs args )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for stage");
}
start(new PrestageHandler(sessionId, commandId, args));
return null ;
}
public synchronized String com_lstat( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return get_stat( sessionId , commandId , args , false ) ;
}
public synchronized String com_stat( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return get_stat( sessionId , commandId , args , true ) ;
}
public synchronized String com_unlink( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_unlink( sessionId , commandId , args , true ) ;
}
public synchronized String com_rename( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_rename( sessionId , commandId , args ) ;
}
public synchronized String com_rmdir( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_rmdir( sessionId , commandId , args , true ) ;
}
public synchronized String com_mkdir( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_mkdir( sessionId , commandId , args , true ) ;
}
public synchronized String com_chmod( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_chmod( sessionId , commandId , args , true ) ;
}
public synchronized String com_chown( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_chown( sessionId , commandId , args , true ) ;
}
public synchronized String com_chgrp( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_chgrp( sessionId , commandId , args , true ) ;
}
public synchronized String com_opendir( int sessionId , int commandId , VspArgs args )
throws CommandException
{
return do_opendir( sessionId , commandId , args ) ;
}
private synchronized String do_unlink(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for unlink");
}
start(new UnlinkHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_rename(int sessionId, int commandId, VspArgs args)
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for unlink");
}
start(new RenameHandler(sessionId, commandId, args));
return null ;
}
private synchronized String do_rmdir(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for rmdir");
}
start(new RmDirHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_mkdir(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for unlink");
}
start(new MkDirHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_chown(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for chown");
}
start(new ChownHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_chgrp(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for chgrp");
}
start(new ChgrpHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_chmod(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for chmod");
}
start(new ChmodHandler(sessionId, commandId, args, resolvePath));
return null ;
}
private synchronized String do_opendir( int sessionId , int commandId , VspArgs args )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for opendir");
}
start(new OpenDirHandler(sessionId,commandId,args));
return null ;
}
private synchronized String get_stat(
int sessionId , int commandId , VspArgs args , boolean resolvePath )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for stat");
}
start(new StatHandler(sessionId, commandId, args, resolvePath));
return null ;
}
public synchronized String com_ping( int sessionId , int commandId , VspArgs args )
{
println(String.valueOf(sessionId)+" "+commandId+" server pong");
return null ;
}
public synchronized String com_check( int sessionId , int commandId , VspArgs args )
throws CommandException
{
if( args.argc() < 1 ) {
throw new
CommandException(3, "Not enough arguments for check");
}
start(new CheckFileHandler(sessionId, commandId, args));
return null ;
}
public String com_status(int sessionId, int commandId, VspArgs args)
throws CommandException
{
SessionHandler handler = _sessions.get(sessionId);
if (handler == null) {
throw new
CommandException(5, "Session ID " + sessionId + " not found.");
}
return ""+sessionId+" "+commandId+" "+args.getName()+
" ok "+" 0 " + "\""+handler+ "\"" ;
}
public static final String hh_get_door_info = "[-binary]" ;
public Object ac_get_door_info( Args args ){
IoDoorInfo info = new IoDoorInfo(_cellAddress);
info.setProtocol("dcap","3");
info.setOwner(String.valueOf(_uid));
info.setProcess(_pid);
List<IoDoorEntry> list = new ArrayList<>(_sessions.size());
for (SessionHandler session: _sessions.values()) {
if (session instanceof IoHandler) {
list.add(((IoHandler) session).getIoDoorEntry());
}
}
info.setIoDoorEntries( list.toArray(new IoDoorEntry[list.size()]) );
if( args.hasOption("binary") ) {
return info;
} else {
return info.toString();
}
}
public static final String hh_toclient = " <id> <subId> server <command ...>" ;
public String ac_toclient_$_3_99( Args args )
{
StringBuilder sb = new StringBuilder() ;
for( int i = 0 ; i < args.argc() ; i++ ) {
sb.append(args.argv(i)).append(" ");
}
String str = sb.toString() ;
_log.debug("toclient (commander) : {}", str);
println(str);
return "" ;
}
public static final String hh_retry = "<sessionId> [-weak]" ;
public String ac_retry_$_1( Args args ) throws CommandException
{
int sessionId = Integer.parseInt(args.argv(0));
SessionHandler session;
if ((session = _sessions.get(sessionId)) == null) {
throw new CommandException(5, "No such session ID " + sessionId);
}
if (!(session instanceof PnfsSessionHandler)) {
throw new
CommandException(6, "Not a PnfsSessionHandler "+sessionId+
" but "+session.getClass().getName());
}
((PnfsSessionHandler) session).again( !args.hasOption("weak") ) ;
return "" ;
}
////////////////////////////////////////////////////////////////////
//
// the client handler
//
protected class SessionHandler {
protected VspArgs _vargs;
protected int _sessionId;
protected int _commandId;
protected boolean _verbose;
protected long _started = System.currentTimeMillis() ;
protected DoorRequestInfoMessage _info;
protected String _status = "<init>" ;
protected long _statusSince = System.currentTimeMillis() ;
protected String _ioHandlerQueue;
private final long _timestamp = System.currentTimeMillis() ;
protected Subject _subject;
protected OptionalLong _maximumFileSize = OptionalLong.empty();
protected Origin _origin;
protected Restriction _authz = Restrictions.denyAll();
protected String _explanation = "unspecified problem";
protected SessionHandler(int sessionId, int commandId, VspArgs args)
{
_sessionId = sessionId ;
_commandId = commandId ;
_vargs = args ;
_info = new DoorRequestInfoMessage(DCapDoorInterpreterV3.this._cellAddress);
_ioHandlerQueue = args.getOpt("io-queue") ;
_ioHandlerQueue = (_ioHandlerQueue == null ) || ( _ioHandlerQueue.length() == 0 ) ?
null : _ioHandlerQueue ;
}
protected void doLogin()
throws CacheException
{
LoginReply login = login(_vargs.getOpt("role"));
_subject = login.getSubject();
_maximumFileSize = LoginAttributes.maximumUploadSize(login.getLoginAttributes());
_origin = Subjects.getOrigin(_subject);
_authz = Restrictions.concat(_settings.getDoorRestriction(), login.getRestriction());
_info.setSubject(_subject);
}
/**
* Called from the start method. Must perform whatever action
* is needed to kick of processing the request.
*/
protected void doStart()
throws CacheException
{
}
/**
* Starts the SessionHandler. This will cause the session
* handler to be added the session map and initiate any action
* required to process the request.
*/
public final void start()
throws CommandException
{
boolean isStarted = false;
addUs();
try {
doLogin();
doStart();
isStarted = true;
} catch (PermissionDeniedCacheException e) {
throw new CommandException(2, e.getMessage());
} catch (CacheException e) {
throw new CommandException(e.getRc(), e.getMessage());
} finally {
if (!isStarted) {
removeUs();
}
}
}
protected void sendComment( String comment ){
String reply = ""+_sessionId+" 1 "+
_vargs.getName()+" "+comment ;
println( reply ) ;
_log.debug(reply) ;
}
public void keepAlive(){
_log.debug("Keep alived called for : {}", this);
}
protected void sendReply( String tag , int rc , String msg){
sendReply(tag, rc, msg, "");
}
protected void sendReply( String tag , int rc , String msg , String posixErr){
sendReply(tag, rc, msg, posixErr, msg);
}
protected void sendReply( String tag , int rc , String msg ,
String posixErr , String billingMessage){
String problem;
_info.setTransactionDuration(System.currentTimeMillis()-_timestamp);
if( rc == 0 ){
problem = String.format("%d %d %s ok", _sessionId, _commandId, _vargs.getName());
}else{
problem = String.format("%d %d %s failed %d \"%s\" %s",
_sessionId, _commandId, _vargs.getName(),
rc, msg, posixErr);
_info.setResult( rc , billingMessage ) ;
}
_log.debug("{}: {}", tag, problem);
println( problem ) ;
postToBilling(_info);
}
protected void sendReply( String tag , Message msg ){
sendReply( tag, msg.getReturnCode(), String.valueOf(msg.getErrorObject()) ) ;
}
protected void addUs()
throws CommandException
{
if (_sessions.putIfAbsent(_sessionId, this) != null) {
throw new CommandException(5, "Duplicated session id");
}
}
protected void removeUs()
{
_sessions.remove(_sessionId);
}
protected void setStatus( String status ){
_status = status ;
_statusSince = System.currentTimeMillis() ;
}
@Override
public String toString(){
return "["+_sessionId+"]["+getUid()+"]["+_pid+"] "+
_status+"("+
( (System.currentTimeMillis()-_statusSince)/1000 )+")" ;
}
/**
* Returns the UID that is used as an owner for new name space
* entries.
*/
protected int getUid()
{
if (!Subjects.isNobody(_subject)) {
return (int) Subjects.getUid(_subject);
}
String s = _vargs.getOpt("uid");
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
_log.warn("Failed to parse UID: {}", s);
}
}
return _uid;
}
/**
* Returns the GID that is used as an owner for new name space
* entries.
*/
protected int getGid()
{
if (!Subjects.isNobody(_subject)) {
return (int) Subjects.getPrimaryGid(_subject);
}
String s = _vargs.getOpt("gid");
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
_log.warn("Failed to parse GID: {}", s);
}
}
return _gid;
}
/**
* Returns the value that is used as mode for new name space
* entries.
*
* @param mode Default value if mode was not specified
*/
protected int getMode(int mode)
{
String s = _vargs.getOpt("mode");
if (s != null) {
try {
mode = Integer.decode(s);
} catch (NumberFormatException e) {
_log.warn("Failed to parse mode: {}", s);
}
}
return mode;
}
}
protected abstract class PnfsSessionHandler extends SessionHandler {
protected String _path;
protected FileAttributes _fileAttributes;
private long _timer;
private final Object _timerLock = new Object() ;
private long _timeout;
protected Set<FileAttribute> _attributes;
protected PnfsGetFileAttributes _message;
protected PnfsHandler _pnfs;
protected final boolean _isUrl;
protected PnfsSessionHandler(int sessionId, int commandId, VspArgs args,
boolean metaDataOnly, boolean resolvePath)
{
super(sessionId, commandId, args);
_attributes = EnumSet.of(OWNER, OWNER_GROUP, MODE, TYPE, SIZE,
CREATION_TIME, ACCESS_TIME, MODIFICATION_TIME, PNFSID);
if (!metaDataOnly) {
_attributes.addAll(PoolMgrSelectReadPoolMsg.getRequiredAttributes());
}
String tmp = args.getOpt("timeout");
if (tmp != null) {
try {