/
CellAdapter.java
1066 lines (971 loc) · 36.4 KB
/
CellAdapter.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 dmg.cells.nucleus;
import com.google.common.base.Ascii;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import dmg.cells.network.PingMessage;
import dmg.cells.services.RoutingManager;
import dmg.util.Authorizable;
import dmg.util.AuthorizedArgs;
import dmg.util.AuthorizedString;
import dmg.util.CommandAclException;
import dmg.util.CommandException;
import dmg.util.CommandExitException;
import dmg.util.CommandInterpreter;
import dmg.util.CommandPanicException;
import dmg.util.CommandSyntaxException;
import dmg.util.CommandThrowableException;
import dmg.util.Gate;
import dmg.util.Pinboard;
import dmg.util.command.Argument;
import dmg.util.command.Command;
import dmg.util.command.Option;
import dmg.util.logback.FilterShell;
import org.dcache.util.Args;
import org.dcache.util.Version;
import static org.dcache.util.MathUtils.addWithInfinity;
import static org.dcache.util.MathUtils.subWithInfinity;
/**
*
*
*
* The CellAdapter builds the basic implementation of a Cell.
* The CellAdapter implements all required methods of the
* Cell interface and performs some basic actions as long
* as those methods are not overloaded by a subclass of
* CellAdapter. CellAdapter introduces a new set of methods
* which provide a similiar functionallity as the original
* Cell callbacks, but are much easier to use.
* Additionally CellAdapter offers a subset of the CellNucleus
* methods to be called directly without storing the
* corresponding handle to the CellNucleus.
* CellAdapter has a buildin command interpreter
* <code>see CommandInterpreter</code> which is automatically
* invokes for each packet containing a plain String object.
* The result is returned to the sender.
* CellAdapter forwards and answers ping requests without
* informing the subclass of CellAdapter as long as this
* capabitity is not switched of explicitly.
*
* @author Patrick Fuhrmann
* @version 0.2.11, 10/22/1998
*/
public class CellAdapter extends CommandInterpreter
implements Cell, CellEventListener, CellEndpoint
{
private final static Logger _log =
LoggerFactory.getLogger(CellAdapter.class);
private final CellVersion _version = new CellVersion(Version.of(this));
private final static ThreadLocal<CellMessage> CURRENT_MESSAGE = new ThreadLocal<>();
private final CellNucleus _nucleus;
private final Gate _startGate = new Gate(false);
private final Args _args;
private boolean _useInterpreter = true;
private boolean _returnCommandException = true;
private boolean _answerPing = true;
private String _autoSetup;
private String _definedSetup;
/**
* Creates a Cell and the corresponding CellNucleus with the
* specified name. An extra boolean argument 'startNow'
* allows to delay the arrival of messages until the
* CellAdapter.start() method is called.
*
* @param cellName is the name of the newly created cell. The name
* has to be unique within the context of this CellDomain.
* @param args an arbitrary argument string with can be obtained
* by getArgs later on.
* @param startNow the arrival of messages is enabled.
* @exception IllegalArgumentException is thrown if the name is
* not unique within this CellDomain.
*/
public CellAdapter(String cellName,
String args,
boolean startNow) {
this(cellName, new Args(args == null ? "" : args), startNow);
}
public CellAdapter(String cellName,
String cellType,
String args,
boolean startNow) {
this(cellName, cellType, new Args(args == null ? "" : args), startNow);
}
public CellAdapter(String cellName,
Args args,
boolean startNow) {
this(cellName, "Generic", args, startNow);
}
public CellAdapter(String cellName,
String cellType,
Args args,
boolean startNow) {
_args = args;
_nucleus = new CellNucleus(this, cellName, cellType);
_nucleus.start();
_autoSetup = cellName + "Setup";
if ((_args.argc() > 0) &&
((_definedSetup = _args.argv(0)).length() > 1) &&
(_definedSetup.startsWith("!"))) {
_definedSetup = _definedSetup.substring(1);
_args.shift();
} else {
_definedSetup = null;
}
if (_args.hasOption("export") && (_args.getOption("export").isEmpty() || Boolean.parseBoolean(_args.getOption("export")))) {
export();
}
if (_args.hasOption("replyObject") && _args.getOpt("replyObject").equals("false")) {
setCommandExceptionEnabled(false);
}
addCommandListener(new FilterShell(_nucleus.getLoggingThresholds()));
addCommandListener(new HelpCommands());
if (startNow) {
start();
}
}
/**
* starts the delivery of messages to this cell and
* executes the auto and defined Setup context.
* (<cellName>Setup and "!<setupContextName>)
* This method has to be called if the
* contructor has been used with the startNow
* argument set to 'false'.
*
*/
public void start() {
executeSetupContext();
_startGate.open();
}
@Override
public Serializable command(Args args) throws CommandException {
if (args.argc() == 0) {
return "";
}
//
// check for the NOOP command.
//
if (args.argc() > 0 && args.argv(0).equals("xyzzy")) {
return "Nothing happens.";
}
return super.command(args);
}
/**
* Executes the ContextVariable :
* <cellName>Setup and "!<setupContextName>"
*
*/
public void executeSetupContext()
{
if (_autoSetup != null) {
executeDomainContext(_autoSetup);
}
_autoSetup = null;
if (_definedSetup != null) {
executeDomainContext(_definedSetup);
}
_definedSetup = null;
}
protected void executeDomainContext(String name)
{
if (name != null) {
try {
try (Reader in = _nucleus.getDomainContextReader(name)) {
CellShell shell = new CellShell(this);
shell.execute("context:" + name, in, new Args(""));
}
} catch (FileNotFoundException e) {
// Ignored: Context variable is not defined
} catch (CommandExitException | IOException e) {
_log.warn(e.getMessage());
}
}
}
/**
* Creates a Cell and the corresponding CellNucleus with the
* specified name.
*
* @param cellName is the name of the newly created cell. The name
* has to be unique within the context of this CellDomain.
* @exception IllegalArgumentException is thrown if the name is
* not unique within this CellDomain.
*/
public CellAdapter(String cellName) {
this(cellName, "", true);
}
/**
* Creates a Cell and the corresponding CellNucleus with the
* specified name and a set of arguments.
*
* @param cellName is the name of the newly created cell. The name
* has to be unique within the context of this CellDomain.
* @exception IllegalArgumentException is thrown if the name is
* not unique within this CellDomain.
*/
public CellAdapter(String cellName, String args) {
this(cellName, args, true);
}
//
// adapter to the nucleus
//
/**
* Adds a CellEventListener to the current CellNucleus.
* @param cel has to be an object which implements CellEventListener.
* @see CellEventListener
*/
public void addCellEventListener(CellEventListener cel) {
_nucleus.addCellEventListener(cel);
}
/**
* Declares this Cell to be a CellEventListener.
* All methods are implemented by the CellAdapter but
* don't perform any actions. The subclass has to
* overwrite all those methods, it is interested in.
*
* @see CellEventListener
*/
public void addCellEventListener() {
_nucleus.addCellEventListener(this);
}
/**
* returns an Args object created from the second
* argument of the constructor : this(String name, String args).
*
* @return a handle to an dmg.util.Args object.
*
* @see Args
*/
@Override
public Args getArgs() { return _args; }
/**
* enables or disables the return type of the buildin command interpreter.
*
* @param use enables the return of CommandExceptions.
*/
public void setCommandExceptionEnabled(boolean use) {
_returnCommandException = use;
}
/**
* enables or disables the buildin command interpreter.
* The default behaviour is to use the interpreter.
* @param use enables the interpreter if set to 'true' otherwise
* the interpreter is disabled.
*/
public void useInterpreter(boolean use) { _useInterpreter = use; }
/**
* enables or disables the ability to answer or to forward
* a ping request without calling 'messageArrived' or
* 'messageToForward'.
* The default behaviour is to answer or to forward a ping.
* @param ping instructs the CellAdapter to answer or forward ping requests.
*/
public void setAnswerPing(boolean ping) { _answerPing = ping; }
/**
* returns the CellNucleus assigned to this cell. This handle
* might be usefull to have access to the full nucleus functionallity.
*
* @return a handle to the CellNucleus connected to this cell.
*/
public CellNucleus getNucleus() { return _nucleus; }
/**
* Setup the logging context of the calling thread. Threads
* created from the calling thread automatically inherit this
* information.
*/
public void initLoggingContext() { CDC.reset(_nucleus); }
/**
* informs the CellCore to remove this cell.
* The cell kernel will start the kill sequence as soon as
* possible.
*/
protected void kill() { _nucleus.kill(); }
/**
* returns the name of this cell.
* @return the name of this cell.
*/
public String getCellName() { return _nucleus.getCellName(); }
/**
* returns the name of the domain this cell resides in.
* @return the name of this domain.
*/
public String getCellDomainName() { return _nucleus.getCellDomainName(); }
/**
* marks this cell to be exportable. This call triggers an
* CellExported event to be delivered to all CellEventListeners.
* The call should only be used for cells with a
* wellknown name because this name is distributed to
* all relevent domains as soon as a
* RoutingManager is
* running.
*
* @see RoutingManager
*/
public void export() { _nucleus.export(); }
/**
* Defines a pinboard for this CellAdapter.
*
* @param size maximum number of lines kept by the pinboard.
*
*/
public void createPinboard(int size)
{
_nucleus.setPinboard(new Pinboard(size <= 0 ? 200 : size));
}
/**
*
*
* @param className Name of the cellClass which should be created
* @param cellName Name of the cell instance
* @param args An array of Objects which are passed to the
* constructor of the specified cellClass.
*
*/
public Object createNewCell(String className,
String cellName,
String [] argsClassNames,
Object [] args)
throws ClassNotFoundException,
NoSuchMethodException,
SecurityException,
InstantiationException,
InvocationTargetException,
IllegalAccessException,
ClassCastException {
return _nucleus.createNewCell(className, cellName,
argsClassNames, args);
}
@Override
public Map<String,Object> getDomainContext()
{
return _nucleus.getDomainContext();
}
/**
*
* Returns a reader of the specified context Object.
* The method allows to read throw a 'context object'
* as if it was a file.
*
* @param contextName Name of the context Object.
*
*/
public Reader getDomainContextReader(String contextName)
throws FileNotFoundException {
return _nucleus.getDomainContextReader(contextName);
}
protected <T> Future<T> invokeOnMessageThread(Callable<T> task)
{
return _nucleus.invokeOnMessageThread(task);
}
/**
* sends a <code>CellMessage</code> along the specified path.
*
* @param msg the message to be sent.
* @exception SerializationException if the payload object of this
* message is not Serializable.
* @exception NoRouteToCellException if the destination <code>CellPath</code>
* couldn't be reached.
*
*/
@Override
public void sendMessage(CellMessage msg)
throws SerializationException, NoRouteToCellException
{
getNucleus().sendMessage(msg, true, true);
}
@Override
public void sendMessageWithRetryOnNoRouteToCell(CellMessage msg,
CellMessageAnswerable callback,
Executor executor,
long timeout)
throws SerializationException
{
CellMessageAnswerable retryingCallback =
new RetryingCellMessageAnswerable(msg, callback, executor, timeout);
sendMessage(msg, retryingCallback, executor, timeout);
}
@Override
public void sendMessage(CellMessage msg,
CellMessageAnswerable callback,
Executor executor,
long timeout)
throws SerializationException
{
getNucleus().sendMessage(msg, true, true, callback, executor, timeout);
}
/**
* Returns the message object which caused a
* Command Interpreter client method to trigger.
* The result object is only 'non-zero' inside
* a ac_xxx method.
*/
public final static CellMessage getThisMessage() {
return CURRENT_MESSAGE.get();
}
//
// methods which may be overwriten
//
/**
* should be overwrite to provide a more specific
* one line information about this cell.
*
* @return a one line information String.
*/
public String toString() { return _nucleus.getCellName(); }
/**
* should be overwrite to provide more specific
* information about this cell.
*
* @param printWriter the printWriter which has to be used to
* write the information to.
*
*/
public void getInfo(PrintWriter printWriter) {
printWriter.println(" CellName : "+_nucleus.getCellName());
printWriter.println(" CellClass : "+this.getClass().getName());
printWriter.println(" Arguments : "+_args);
}
@Override
public CellVersion getCellVersion()
{
return _version;
}
@Override
public CellInfo getCellInfo() { return _nucleus.getCellInfo(); }
/**
* has to be overwritten to receive arriving messages.
* The LastMessageEvent is filtered out and starts the
* kill sequence which calls 'cleanUp' at the end of the
* sequence. If the CommandInterpreter facility is enabled,
* all string messages are send to the command interpreter
* and answered without intervention of the callback.
* If the command could not be found by the CommandInterpreter,
* <link>dmg.cells.nucleus.CellAdapter#commandArrived(CellMessage)</link>
* is called if it is overwritten
* by one of the CellAdapters subclasses.
* This callback is only used to inform about messages of which
* the current cell is the final destination.
* Other messages are delivered throu <code>messageToForward</code>.
*
* @param msg the reference to message arrived.
*/
public void messageArrived(CellMessage msg) {
_log.info(" CellMessage From : " + msg.getSourcePath());
_log.info(" CellMessage To : " + msg.getDestinationPath());
_log.info(" CellMessage Object : " + msg.getMessageObject());
}
/**
* has to be overwritten to receive arriving messages which
* are not directly addressed to this cell. The default behaviour
* is to select the next destination and to resend the message.
*
* @param msg the reference to message arrived.
*
*/
public void messageToForward(CellMessage msg) {
msg.nextDestination();
try {
_nucleus.sendMessage(msg, true, true);
} catch (NoRouteToCellException nrtc) {
_log.warn("CellAdapter : NoRouteToCell in messageToForward : "+nrtc);
} catch (Exception eee) {
_log.warn("CellAdapter : Exception in messageToForward : "+eee);
}
}
public Class<?> loadClass(String className) throws ClassNotFoundException {
return _nucleus.loadClass(className);
}
/**
*
* If overwritten this method delivers commands which
* produced a syntax error which intereted by the
* CommandInterpreter. The original message string
* is provides together with a help text offered
* by the interpreter.
* If not overwritten this helptext is send back to the
* caller.
*
* @param str is the orginal command string.
* @param cse is the syntax error exception thrown by the
* command interpreter. cse.getHelpText offers
* the possible help text.
* @return the object which is send back to the caller.
* If <code>null</code> nothing is send back.
*/
public Serializable commandArrived(String str, CommandSyntaxException cse) {
StringBuilder sb = new StringBuilder();
sb.append("Syntax Error : ").append(cse.getMessage()).append("\n");
String help = cse.getHelpText();
if (help != null) {
sb.append("Help : \n");
sb.append(help);
}
return sb.toString();
}
protected void awaitStart()
{
_startGate.check();
}
/**
* has to be overwritten to perform any actions before this
* cell is destroyed. 'cleanUp' is called after the last
* message has arrived. The default behaviour is to do nothing.
*
*/
public void cleanUp() { }
//
// methods from the cellEventListener Interface
//
/**
* belongs to the CellEventListener Interface
*/
@Override
public void cellCreated(CellEvent ce) {}
/**
* belongs to the CellEventListener Interface
*/
@Override
public void cellDied(CellEvent ce) {}
/**
* belongs to the CellEventListener Interface
*/
@Override
public void cellExported(CellEvent ce) {}
/**
* belongs to the CellEventListener Interface
*/
@Override
public void routeAdded(CellEvent ce) {}
/**
* belongs to the CellEventListener Interface
*/
@Override
public void routeDeleted(CellEvent ce) {}
@Command(name = "xgetcellinfo")
public class GetCellInfoCommand implements Callable<CellInfo>
{
@Override
public CellInfo call()
{
return getCellInfo();
}
}
@Command(name = "info")
public class InfoCommand implements Callable<String>
{
@Option(name = "a", usage = "Display content of unanswered message requests.")
boolean full;
@Option(name = "l", usage = "Display unanswered message requests.")
boolean lng;
@Override
public String call()
{
if (lng || full) {
StringBuilder sb = new StringBuilder();
sb.append(getInfo()).append("\n");
Map<UOID,CellLock > map = _nucleus.getWaitQueue();
if (! map.isEmpty()) {
sb.append("\nWe are waiting for the following messages\n");
}
for (Map.Entry<UOID,CellLock > entry : map.entrySet()) {
Object key = entry.getKey();
CellLock lock = entry.getValue();
sb.append(key.toString()).append(" r=");
long res = subWithInfinity(lock.getTimeout(), System.currentTimeMillis());
sb.append(res/1000).append(" sec;");
CellMessage msg = lock.getMessage();
if (msg == null) {
sb.append("msg=none");
} else {
Object obj = msg.getMessageObject();
if (obj != null) {
sb.append("msg=").append(obj.getClass().getName());
if (full) {
sb.append("/").append(obj.toString());
}
}
}
sb.append("\n");
}
return sb.toString();
} else {
return getInfo();
}
}
}
@Command(name = "show pinboard",
hint = "display the most recent pinboard messages",
description = "The pinboard always stores the most recent log messages. It has " +
"a fixed capacity: once full appending a new message will eject the oldest " +
"stored message. See also the 'log set' command.")
public class ShowPinboardCommand implements Callable<String>
{
@Argument(required = false, metaVar = "lines",
usage = "How many pinboard entries to display.")
int lines = 20;
@Override
public String call()
{
Pinboard pinboard = _nucleus.getPinboard();
if (pinboard == null) {
return "No pinboard defined";
}
StringBuilder sb = new StringBuilder();
pinboard.dump(sb, lines);
return sb.toString();
}
}
@Command(name = "dump pinboard", hint = "write pinboard to file",
description = "Writes the pinboard log to FILE on the local file system of the service.")
public class DumpPinboardCommand implements Callable<String>
{
@Argument(metaVar = "file")
File file;
@Override
public String call() throws IOException
{
Pinboard pinboard = _nucleus.getPinboard();
if (pinboard == null) {
return "No pinboard defined.";
}
pinboard.dump(file);
return "Pinboard dumped to " + file;
}
}
/**
* belongs to the Cell Interface.
* If this method is overwritten, the 'cleanUp'
* method won't be called.
*/
@Override
public void prepareRemoval(KillEvent ce)
{
_log.info("CellAdapter : prepareRemoval : waiting for gate to open");
_startGate.check();
cleanUp();
dumpPinboard();
_log.info("CellAdapter : prepareRemoval : done");
}
//
// package private (we need it in CellShell)
//
void dumpPinboard()
{
Pinboard pinboard = _nucleus.getPinboard();
try {
Map<String,Object> context = getDomainContext();
String dumpDir = (String) context.get("dumpDirectory");
if (dumpDir == null) {
_log.info("Pinboard not dumped (dumpDirectory not sp.)");
return;
}
File dir = new File(dumpDir);
if (!dir.isDirectory()) {
_log.info("Pinboard not dumped (dumpDirectory {} not found)",
dumpDir);
return;
}
if (pinboard == null) {
_log.info("Pinboard not dumped (no pinboard defined)");
return;
}
File dump = new File(dir,
getCellDomainName()+"-"+
getCellName()+"-"+
Long.toHexString(System.currentTimeMillis()));
pinboard.dump(dump);
} catch (IOException e) {
_log.error("Dumping pinboard failed : {}", e.toString());
}
}
/**
* belongs to the Cell Interface.
* Is never called.
*/
@Override
public void exceptionArrived(ExceptionEvent ce) {
_log.info(" exceptionArrived "+ce);
}
/**
* belongs to the Cell Interface.
* If this method is overwritten, the getInfo(PrintWriter pw)
* is never called.
*/
@Override
public String getInfo() {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
getInfo(printWriter);
printWriter.flush();
return stringWriter.getBuffer().toString();
}
/**
* belongs to the Cell Interface.
* If this method is overwritten, the messageArrived(CellMessage cm)
* and the messageToForward(CellMessage) methods
* are never called.
*/
@Override
public void messageArrived(MessageEvent me) {
if (!_startGate.isOpen()) {
CellMessage msg = me.getMessage();
if (!msg.isReply()) {
try {
NoRouteToCellException e =
new NoRouteToCellException(msg.getUOID(),
msg.getDestinationPath(),
getCellName() + " is still initializing.");
msg.revertDirection();
msg.setMessageObject(e);
_nucleus.sendMessage(msg, true, true);
} catch (NoRouteToCellException e) {
_log.warn("PANIC : Problem returning answer : " + e);
}
}
} else {
CellMessage msg = me.getMessage();
Serializable obj = msg.getMessageObject();
if (msg.isFinalDestination()) {
if (!msg.isReply() && msg.getLocalAge() > msg.getAdjustedTtl()) {
_log.warn("Discarding {} because its age of {} ms exceeds its time to live of {} ms.",
(obj instanceof CharSequence) ? '\'' + Ascii.truncate((CharSequence) obj, 50, "...") + '\'' : obj.getClass().getSimpleName(),
msg.getLocalAge(), msg.getAdjustedTtl());
return;
}
if (_useInterpreter && (! msg.isReply()) &&
((obj instanceof String) ||
(obj instanceof AuthorizedString))) {
Serializable o;
UOID uoid = msg.getUOID();
EventLogger.deliverBegin(msg);
try {
CURRENT_MESSAGE.set(msg);
o = executeLocalCommand(obj);
if (o == null) {
return;
}
} catch (CommandThrowableException e) {
o = e.getCause();
} catch (CommandPanicException e) {
o = e;
_log.error("Command failed due to a bug, please contact support@dcache.org.", e);
} catch (CommandException ce) {
o = ce;
} finally {
EventLogger.deliverEnd(msg.getSession(), uoid);
CURRENT_MESSAGE.remove();
}
try {
msg.revertDirection();
if (o instanceof Reply) {
Reply reply = (Reply)o;
reply.deliver(this, msg);
} else {
msg.setMessageObject(o);
_nucleus.sendMessage(msg, true, true);
}
} catch (NoRouteToCellException e) {
_log.warn("PANIC : Problem returning answer : " + e);
}
} else if ((obj instanceof PingMessage) && _answerPing) {
PingMessage ping = (PingMessage)obj;
if (ping.isWayBack()) {
messageArrived(msg);
return;
}
ping.setWayBack();
msg.revertDirection();
try {
_nucleus.sendMessage(msg, true, true);
} catch (NoRouteToCellException ee) {
_log.warn("Couldn't revert PingMessage : "+ee);
}
} else {
UOID uoid = msg.getUOID();
EventLogger.deliverBegin(msg);
try {
messageArrived(msg);
} finally {
EventLogger.deliverEnd(msg.getSession(), uoid);
}
}
} else if (obj instanceof PingMessage) {
msg.nextDestination();
try {
_nucleus.sendMessage(msg, true, true);
} catch (NoRouteToCellException ee) {
_log.warn("Couldn't forward PingMessage : " + ee);
}
} else {
UOID uoid = msg.getUOID();
EventLogger.deliverBegin(msg);
try {
messageToForward(msg);
} finally {
EventLogger.deliverEnd(msg.getSession(), uoid);
}
}
}
}
private Serializable executeLocalCommand(Object command)
throws CommandException {
if (command instanceof Authorizable) {
if (_returnCommandException) {
AuthorizedArgs args = new AuthorizedArgs((Authorizable)command);
return command(args);
} else {
return autoCommand(command);
}
} else if (command instanceof String) {
if (_returnCommandException) {
Args args = new Args((String)command);
return command(args);
} else {
return autoCommand(command);
}
} else {
throw new CommandPanicException("Illegal CommandClass detected");
}
}
private Serializable autoCommand(Object command) {
try {
if (command instanceof String) {
Args args = new Args((String) command);
return command(new Args((String) command));
} else if (command instanceof AuthorizedString) {
AuthorizedArgs args = new AuthorizedArgs((AuthorizedString) command);
return command(args);
} else {
return "Panic : internal server error 14345";
}
} catch (CommandSyntaxException cse) {
return commandArrived(command.toString(), cse);
} catch (CommandExitException cee) {
return "Sorry, can't exit";
} catch (CommandThrowableException cte) {
StringBuilder sb = new StringBuilder();
sb.append(cte.getMessage()).append("\n");
Throwable t = cte.getTargetException();
sb.append(t.getClass().getName()).append(" : ")
.append(t.getMessage()).append("\n");
return sb.toString();
} catch (CommandPanicException cpe) {
StringBuilder sb = new StringBuilder();
sb.append("Panic : ").append(cpe.getMessage()).append("\n");
Throwable t = cpe.getTargetException();
sb.append(t.getClass().getName()).append(" : ")
.append(t.getMessage()).append("\n");
return sb.toString();
} catch (Exception e) {
return "??? : "+e.toString();
}
}
@Override
protected Serializable doExecute(CommandEntry entry, Args args,
String[] acls) throws CommandException
{
if (args instanceof Authorizable) {
checkAclPermission((Authorizable) args, args, acls);
}
return super.doExecute(entry, args, acls);
}
private CellPath _aclPath = new CellPath("acm");
private long _aclTimeout = 10000L;
protected void checkAclPermission(Authorizable auth, Object command, String [] acls) throws CommandException {
String user = auth.getAuthorizedPrincipal();
if (user.equals("admin") || acls.length == 0) {
return;
}
CommandException recentException = null;
for (String acl : acls) {
try {
checkAclPermission(user, command, acl);
return;
} catch (CommandAclException ce) {
recentException = ce;
}
}
throw recentException;
}
protected void checkAclPermission(String user, Object command, String acl) throws CommandException {
Object [] request = new Object[5];
request[0] = "request";
request[1] = "<nobody>";
request[2] = "check-permission";
request[3] = user;
request[4] = acl;
CellMessage reply;
try {
reply = _nucleus.sendAndWait(new CellMessage(_aclPath, request), _aclTimeout);
if (reply == null) {
throw new CommandException("Error in acl handling : Acl Request timed out (" + _aclPath + ")");
}
} catch (NoRouteToCellException | ExecutionException | InterruptedException e) {