/
Channel.java
2131 lines (1938 loc) · 81.3 KB
/
Channel.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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.remoting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.CommandTransport.CommandReceiver;
import hudson.remoting.PipeWindow.Key;
import hudson.remoting.PipeWindow.Real;
import hudson.remoting.forward.ForwarderFactory;
import hudson.remoting.forward.ListeningPort;
import hudson.remoting.forward.PortForwarder;
import org.jenkinsci.remoting.CallableDecorator;
import org.jenkinsci.remoting.nio.NioChannelHub;
import org.jenkinsci.remoting.util.LoggingChannelListener;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Represents a communication channel to the remote peer.
*
* <p>
* A {@link Channel} is a mechanism for two JVMs to communicate over
* bi-directional {@link InputStream}/{@link OutputStream} pair.
* {@link Channel} represents an endpoint of the stream, and thus
* two {@link Channel}s are always used in a pair.
*
* <p>
* Communication is established as soon as two {@link Channel} instances
* are created at the end fo the stream pair
* until the stream is terminated via {@link #close()}.
*
* <p>
* The basic unit of remoting is an executable {@link Callable} object.
* An application can create a {@link Callable} object, and execute it remotely
* by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method.
*
* <p>
* In this sense, {@link Channel} is a mechanism to delegate/offload computation
* to other JVMs and somewhat like an agent system. This is bit different from
* remoting technologies like CORBA or web services, where the server exposes a
* certain functionality that clients invoke.
*
* <p>
* {@link Callable} object, as well as the return value / exceptions,
* are transported by using Java serialization. All the necessary class files
* are also shipped over {@link Channel} on-demand, so there's no need to
* pre-deploy such classes on both JVMs.
*
*
* <h2>Implementor's Note</h2>
* <p>
* {@link Channel} builds its features in a layered model. Its higher-layer
* features are built on top of its lower-layer features, and they
* are called layer-0, layer-1, etc.
*
* <ul>
* <li>
* <b>Layer 0</b>:
* See {@link Command} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* <li>
* <b>Layer 1</b>:
* See {@link Request} for more details. This is for higher-level features,
* and not likely useful for applications directly.
* </ul>
*
* @author Kohsuke Kawaguchi
*/
public class Channel implements VirtualChannel, IChannel, Closeable {
private final CommandTransport transport;
/**
* {@link OutputStream} that's given to the constructor. This is the hand-off with the lower layer.
*
* @deprecated
* See {@link #getUnderlyingOutput()}.
*/
@Deprecated
private final OutputStream underlyingOutput;
/**
* Human readable description of where this channel is connected to. Used during diagnostic output
* and error reports.
*/
private final String name;
private volatile boolean remoteClassLoadingAllowed, arbitraryCallableAllowed;
/*package*/ final CallableDecoratorList decorators = new CallableDecoratorList();
@Restricted(NoExternalUse.class)
public final ExecutorService executor;
/**
* If non-null, the incoming link is already shut down,
* and reader is already terminated. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable inClosed = null;
/**
* If non-null, the outgoing link is already shut down,
* and no command can be sent. The {@link Throwable} object indicates why the outgoing channel
* was closed.
*/
private volatile Throwable outClosed = null;
/**
* Requests that are sent to the remote side for execution, yet we are waiting locally until
* we hear back their responses.
*/
/*package*/ final Map<Integer,Request<? extends Serializable,? extends Throwable>> pendingCalls = new ConcurrentHashMap<>();
/**
* Remembers last I/O ID issued from locally to the other side, per thread.
* int[1] is used as a holder of int.
*/
private final ThreadLocal<int[]> lastIoId = new ThreadLastIoId();
/**
* Records the {@link Request}s being executed on this channel, sent by the remote peer.
*/
/*package*/ final Map<Integer,Request<?,?>> executingCalls = new ConcurrentHashMap<>();
/**
* {@link ClassLoader}s that are proxies of the remote classloaders.
*/
/*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this);
/**
* Objects exported via {@link #export(Class, Object)}.
*/
/*package (for test)*/ final ExportTable exportedObjects = new ExportTable();
/**
* {@link PipeWindow}s keyed by their OIDs (of the OutputStream exported by the other side.)
*
* <p>
* To make the GC of {@link PipeWindow} automatic, the use of weak references here are tricky.
* A strong reference to {@link PipeWindow} is kept from {@link ProxyOutputStream}, and
* this is the only strong reference. Thus while {@link ProxyOutputStream} is alive,
* it keeps {@link PipeWindow} referenced, which in turn keeps its {@link PipeWindow.Real#key}
* referenced, hence this map can be looked up by the OID. When the {@link ProxyOutputStream}
* will be gone, the key is no longer strongly referenced, so it'll get cleaned up.
*
* <p>
* In some race condition situation, it might be possible for us to lose the tracking of the collect
* window size. But as long as we can be sure that there's only one {@link PipeWindow} instance
* per OID, it will only result in a temporary spike in the effective window size,
* and therefore should be OK.
*/
private final WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>> pipeWindows = new WeakHashMap<>();
/**
* There are cases where complex object cycles can cause a closed channel to fail to be garbage collected,
* these typically arrise when an {@link #export(Class, Object)} is {@link #setProperty(Object, Object)}
* (a supported and intended use case), the {@link Ref} allows us to break the object cycle on channel
* termination and simplify the circles into chains which can then be collected easily by the garbage collector.
* @since 2.52
*/
private final Ref reference;
/**
* Registered listeners.
*/
private final List<Listener> listeners = new CopyOnWriteArrayList<>();
private int gcCounter;
/**
* Number of {@link Command} objects sent to the other side.
*/
private final AtomicLong commandsSent = new AtomicLong();
/**
* Number of {@link Command} objects received from the other side.
*
* When a transport is functioning correctly, {@link #commandsSent} of one side
* and {@link #commandsReceived} of the other side should closely match.
*/
private final AtomicLong commandsReceived = new AtomicLong();
/**
* Timestamp of the last {@link Command} object sent/received, in
* {@link System#currentTimeMillis()} format.
* This can be used as a basis for detecting dead connections.
*
* <p>
* Note that {@link #lastCommandSentAt} doesn't mean
* anything in terms of whether the underlying network was able to send
* the data (for example, if the other end of a socket connection goes down
* without telling us anything, the {@link SocketOutputStream#write(int)} will
* return right away, and the socket only really times out after 10s of minutes.
*/
private final AtomicLong lastCommandSentAt = new AtomicLong();
private final AtomicLong lastCommandReceivedAt = new AtomicLong();
/**
* Timestamp of when this channel was connected/created, in
* {@link System#currentTimeMillis()} format.
*/
private final long createdAt = System.currentTimeMillis();
/**
* Total number of nanoseconds spent for remote class loading.
* <p>
* Remote code execution often results in classloading activity
* (more precisely, when the remote peer requests some computation
* on this channel, this channel often has to load necessary
* classes from the remote peer.)
* <p>
* This counter represents the total amount of time this channel
* had to spend loading classes from the remote peer. The time
* measurement doesn't include the time locally spent to actually
* define the class (as the local classloading would have incurred
* the same cost.)
*/
public final AtomicLong classLoadingTime = new AtomicLong();
/**
* Total counts of remote classloading activities. Used in a pair
* with {@link #classLoadingTime}.
*/
public final AtomicInteger classLoadingCount = new AtomicInteger();
/**
* Prefetch cache hits.
*
* Out of all the counts in {@link #classLoadingCount}, how many times
* were we able to resolve them by ourselves, saving a remote roundtrip call?
* @since 2.24
*/
public final AtomicInteger classLoadingPrefetchCacheCount = new AtomicInteger();
/**
* Total number of nanoseconds spent for remote resource loading.
* @see #classLoadingTime
*/
public final AtomicLong resourceLoadingTime = new AtomicLong();
/**
* Total count of remote resource loading.
* @see #classLoadingCount
*/
public final AtomicInteger resourceLoadingCount = new AtomicInteger();
private final AtomicInteger ioId = new AtomicInteger();
/**
* Property bag that contains application-specific stuff.
*/
private final ConcurrentHashMap<Object,Object> properties = new ConcurrentHashMap<>();
/**
* Proxy to the remote {@link Channel} object.
*/
private final IChannel remoteChannel;
/**
* Capability of the remote {@link Channel}.
*/
public final Capability remoteCapability;
/**
* Single-thread executor for running pipe I/O operations.
*
* It is executed in a separate thread to avoid blocking the channel reader thread
* in case read/write blocks. It is single thread to ensure FIFO; I/O needs to execute
* in the same order the remote peer told us to execute them.
*/
/*package*/ final PipeWriter pipeWriter;
/**
* ClassLaoder that remote classloaders should use as the basis.
*/
/*package*/ final ClassLoader baseClassLoader;
/**
* JAR Resolution Cache.
* Can be {@code null} if caching disabled for this channel.
* In such case some classloading operations may be rejected.
*/
@CheckForNull
private JarCache jarCache;
/*package*/ final JarLoaderImpl jarLoader;
short maximumBytecodeLevel = Short.MAX_VALUE;
/*package*/ @NonNull
final ClassFilter classFilter;
/**
* Indicates that close of the channel has been requested.
* When the value is {@code true}, it does not make sense to execute new user-space commands like {@link UserRequest}.
*/
private boolean closeRequested = false;
/**
* Stores cause of the close Request.
*
* In the case of race condition between multiple close operations,
* this field stores just one of them.
*/
@CheckForNull
private Throwable closeRequestCause = null;
/**
* Communication mode used in conjunction with {@link ClassicCommandTransport}.
*
* @since 1.161
*/
public enum Mode {
/**
* Send binary data over the stream. Most efficient.
*/
BINARY(new byte[]{0,0,0,0}),
/**
* Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%,
* but this is useful where stream is binary-unsafe, such as telnet.
*/
TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") {
@Override protected OutputStream wrap(OutputStream os) {
return BinarySafeStream.wrap(os);
}
@Override protected InputStream wrap(InputStream is) {
return BinarySafeStream.wrap(is);
}
},
/**
* Let the remote peer decide the transmission mode and follow that.
* Note that if both ends use NEGOTIATE, it will dead lock.
*/
NEGOTIATE(new byte[0]);
/**
* Preamble used to indicate the tranmission mode.
* Because of the algorithm we use to detect the preamble,
* the string cannot be any random string. For example,
* if the preamble is "AAB", we'll fail to find a preamble
* in "AAAB".
*/
/*package*/ final byte[] preamble;
Mode(String preamble) {
this.preamble = preamble.getBytes(StandardCharsets.US_ASCII);
}
Mode(byte[] preamble) {
this.preamble = preamble;
}
protected OutputStream wrap(OutputStream os) { return os; }
protected InputStream wrap(InputStream is) { return is; }
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(Channel.Mode.BINARY)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException {
this(name,exec,Mode.BINARY,is,os,null);
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(mode)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException {
this(name,exec,mode,is,os,null);
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(Channel.Mode.BINARY)
* .withHeaderStream(header)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,Mode.BINARY,is,os,header);
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(mode)
* .withHeaderStream(header)
* .withArbitraryCallableAllowed(true)
* .withRemoteClassLoadingAllowed(true)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException {
this(name,exec,mode,is,os,header,false);
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(mode)
* .withHeaderStream(header)
* .withArbitraryCallableAllowed(!restricted)
* .withRemoteClassLoadingAllowed(!restricted)
* .withBaseLoader(base)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException {
this(name,exec,mode,is,os,header,restricted,null);
}
/**
* Creates a new channel.
*
* @param restricted
* See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)}
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withMode(mode)
* .withHeaderStream(header)
* .withArbitraryCallableAllowed(!restricted)
* .withRemoteClassLoadingAllowed(!restricted)
* .withBaseLoader(base)
* .build(is, os)
*/
@Deprecated
public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException {
this(name,exec,mode,is,os,header,restricted,base,new Capability());
}
/*package*/ Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base, Capability capability) throws IOException {
this(new ChannelBuilder(name,exec)
.withMode(mode)
.withBaseLoader(base)
.withCapability(capability)
.withHeaderStream(header)
.withArbitraryCallableAllowed(!restricted)
.withRemoteClassLoadingAllowed(!restricted)
, is, os);
}
/**
* @deprecated as of 2.24
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withArbitraryCallableAllowed(!restricted)
* .withRemoteClassLoadingAllowed(!restricted)
* .withBaseLoader(base)
* .build(transport)
* @since 2.13
*/
@Deprecated
public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base) throws IOException {
this(new ChannelBuilder(name,exec)
.withBaseLoader(base)
.withArbitraryCallableAllowed(!restricted)
.withRemoteClassLoadingAllowed(!restricted)
, transport);
}
/*package*/ Channel(ChannelBuilder settings, InputStream is, OutputStream os) throws IOException {
this(settings, settings.negotiate(is,os));
}
/**
* Creates a new channel.
*
* @param name
* See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)}
* @param exec
* See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)}
* @param transport
* The transport that we run {@link Channel} on top of.
* @param base
* See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)}
* @param restricted
* See {@link #Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)}
*
* @since 2.24
* @deprecated as of 2.38
* Use {@link ChannelBuilder}
* ChannelBuilder(name, exec)
* .withArbitraryCallableAllowed(!restricted)
* .withRemoteClassLoadingAllowed(!restricted)
* .withBaseLoader(base)
* .withJarCache(jarCache)
* .build(transport)
*/
@Deprecated
public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base, JarCache jarCache) throws IOException {
this(new ChannelBuilder(name,exec)
.withBaseLoader(base)
.withRestricted(restricted)
.withJarCache(jarCache)
, transport);
}
/**
* @since 2.38
*/
protected Channel(@NonNull ChannelBuilder settings, @NonNull CommandTransport transport) throws IOException {
this.name = settings.getName();
this.reference = new Ref(this);
this.executor = new InterceptingExecutorService(settings.getExecutors(),decorators);
this.arbitraryCallableAllowed = settings.isArbitraryCallableAllowed();
this.remoteClassLoadingAllowed = settings.isRemoteClassLoadingAllowed();
this.underlyingOutput = transport.getUnderlyingStream();
// JAR Cache resolution
this.jarCache = settings.getJarCache();
if (this.jarCache == null) {
logger.log(Level.CONFIG, "JAR Cache is not defined for channel {0}", name);
}
this.baseClassLoader = settings.getBaseLoader();
this.classFilter = settings.getClassFilter();
if(internalExport(IChannel.class, this, false)!=1)
throw new AssertionError(); // export number 1 is reserved for the channel itself
remoteChannel = RemoteInvocationHandler.wrap(this, 1, IChannel.class, true, false, false, true);
this.remoteCapability = transport.getRemoteCapability();
this.pipeWriter = new PipeWriter(createPipeWriterExecutor());
this.transport = transport;
this.jarLoader = new JarLoaderImpl();
setProperty(JarLoader.OURS, jarLoader);
this.decorators.addAll(settings.getDecorators());
this.properties.putAll(settings.getProperties());
transport.setup(this, new CommandReceiver() {
@Override
public void handle(Command cmd) {
commandsReceived.incrementAndGet();
long receivedAt = System.currentTimeMillis();
lastCommandReceivedAt.set(receivedAt);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Received " + cmd);
} else if (logger.isLoggable(Level.FINER)) {
logger.log(Level.FINER, "Received command " + cmd, cmd.createdAt);
}
try {
cmd.execute(Channel.this);
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Completed command {0}. It took {1}ms", new Object[] {cmd, System.currentTimeMillis() - receivedAt});
}
} catch (Throwable t) {
logger.log(Level.SEVERE, "Failed to execute command " + cmd + " (channel " + Channel.this.name + ")", t);
if (cmd.createdAt != null) {
logger.log(Level.SEVERE, "This command is created here", cmd.createdAt);
}
}
}
@Override
public void terminate(IOException e) {
Channel.this.terminate(e);
}
});
ACTIVE_CHANNELS.put(this,ref());
}
/**
* Gets the {@link Ref} for this {@link Channel}. The {@link Ref} will be {@linkplain Ref#clear(Exception)}ed when
* the channel is terminated in order to break any complex object cycles.
* @return the {@link Ref} for this {@link Channel}
* @since 2.52
*/
@NonNull
/*package*/ Ref ref() {
return reference;
}
/**
* Callback "interface" for changes in the state of {@link Channel}.
* @see #addListener
* @see LoggingChannelListener
*/
public static abstract class Listener {
/**
* When the channel was closed normally or abnormally due to an error.
*
* @param cause
* if the channel is closed abnormally, this parameter
* represents an exception that has triggered it.
* Otherwise null.
*/
public void onClosed(Channel channel, IOException cause) {}
/**
* Called when a command is successfully received by a channel.
* @param channel a channel
* @param cmd a command
* @param blockSize the number of bytes used to read this command
* @since 3.17
*/
public void onRead(Channel channel, Command cmd, long blockSize) {}
/**
* Called when a command is successfully written to a channel.
* See {@link #onRead} for general usage guidelines.
* @param channel a channel
* @param cmd a command
* @param blockSize the number of bytes used to write this command
* @since 3.17
*/
public void onWrite(Channel channel, Command cmd, long blockSize) {}
/**
* Called when a response has been read from a channel.
* @param channel a channel
* @param req the original request
* @param rsp the resulting response
* @param totalTime the total time in nanoseconds taken to service the request
* @since 3.17
*/
public void onResponse(Channel channel, Request<?, ?> req, Response<?, ?> rsp, long totalTime) {}
/**
* Called when a JAR file is being sent to the remote side.
* @param channel a channel
* @param jar the JAR file from which code is being loaded remotely
* @see Capability#supportsPrefetch
* @since 3.17
*/
public void onJar(Channel channel, File jar) {}
}
/**
* Is the sender side of the transport already closed?
*/
public boolean isOutClosed() {
return outClosed!=null;
}
/**
* Get why the sender side of the channel has been closed.
* @return Close cause or {@code null} if the sender side is active.
* {@code null} result does not guarantee that the channel is actually operational.
* @since 3.11
*/
@CheckForNull
public final Throwable getSenderCloseCause() {
return outClosed;
}
/**
* Returns {@code true} if the channel is either in the process of closing down or has closed down.
*
* If the result is {@code true}, it means that the channel will be closed at some point by Remoting,
* and that it makes no sense to send any new {@link UserRequest}s to the remote side.
* Invocations like {@link #call(hudson.remoting.Callable)} and {@link #callAsync(hudson.remoting.Callable)}
* will just fail as well.
* @since 2.33
*/
public boolean isClosingOrClosed() {
return closeRequested || inClosed != null || outClosed != null;
}
/**
* Gets cause of the close request.
*
* @return {@link #outClosed} if not {@code null}, value of the transient cache
* {@link #closeRequestCause} otherwise.
* The latter one may show random cause in the case of race conditions.
* @since 3.11
*/
@CheckForNull
public Throwable getCloseRequestCause() {
return outClosed != null ? outClosed : closeRequestCause;
}
/**
* Creates the {@link ExecutorService} for writing to pipes.
*
* <p>
* If the throttling is supported, use a separate thread to free up the main channel
* reader thread (thus prevent blockage.) Otherwise let the channel reader thread do it,
* which is the historical behaviour.
*/
private ExecutorService createPipeWriterExecutor() {
if (remoteCapability.supportsPipeThrottling())
return new SingleLaneExecutorService(executor);
return new SynchronousExecutorService();
}
/**
* Sends a command to the remote end and executes it there.
*
* <p>
* This is the lowest layer of abstraction in {@link Channel}.
* {@link Command}s are executed on a remote system in the order they are sent.
*/
@SuppressFBWarnings(value = "VO_VOLATILE_INCREMENT", justification = "The method is synchronized, no other usages. See https://sourceforge.net/p/findbugs/bugs/1032/")
/*package*/ synchronized void send(Command cmd) throws IOException {
if(outClosed!=null)
throw new ChannelClosedException(this, outClosed);
if(logger.isLoggable(Level.FINE))
logger.fine("Send "+cmd);
transport.write(cmd, cmd instanceof CloseCommand);
commandsSent.incrementAndGet();
lastCommandSentAt.set(System.currentTimeMillis());
}
/**
* {@inheritDoc}
*/
@Override
public <T> T export(Class<T> type, T instance) {
return export(type, instance, true, true, true);
}
/**
* Exports the class instance to the remote side.
* @param userProxy
* If true, the returned proxy will be capable to handle classes
* defined in the user classloader as parameters and return values.
* Such proxy relies on {@link RemoteClassLoader} and related mechanism,
* so it's not usable for implementing lower-layer services that are
* used by {@link RemoteClassLoader}.
*
* To create proxies for objects inside remoting, pass in false.
* @param recordCreatedAt as in {@link Command#Command(boolean)}
* @return Reference to the exported instance wrapped by {@link RemoteInvocationHandler}.
* {@code null} if the input instance is {@code null}.
*/
@Nullable
/*package*/ <T> T export(Class<T> type, @CheckForNull T instance, boolean userProxy, boolean userScope, boolean recordCreatedAt) {
if(instance==null) {
return null;
}
// every so often perform GC on the remote system so that
// unused RemoteInvocationHandler get released, which triggers
// unexport operation.
if((++gcCounter)%10000==0)
try {
send(new GCCommand());
} catch (IOException e) {
// for compatibility reason we can't change the export method signature
logger.log(Level.WARNING, "Unable to send GC command",e);
}
// either local side will auto-unexport, or the remote side will unexport when it's GC-ed
boolean autoUnexportByCaller = exportedObjects.isRecording();
final int id = internalExport(type, instance, autoUnexportByCaller);
return RemoteInvocationHandler.wrap(null, id, type, userProxy, autoUnexportByCaller, userScope, recordCreatedAt);
}
/*package*/ <T> int internalExport(Class<T> clazz, T instance) {
return exportedObjects.export(clazz, instance);
}
/*package*/ <T> int internalExport(Class<T> clazz, T instance, boolean automaticUnexport) {
return exportedObjects.export(clazz, instance, automaticUnexport);
}
/*package*/ @NonNull Object getExportedObject(int oid) throws ExecutionException {
return exportedObjects.get(oid);
}
@CheckForNull
/*package*/ Object getExportedObjectOrNull(int oid) {
return exportedObjects.getOrNull(oid);
}
/*package*/ @NonNull Class<?>[] getExportedTypes(int oid) throws ExecutionException {
return exportedObjects.type(oid);
}
/*package*/ void unexport(int id, @CheckForNull Throwable cause) {
unexport(id, cause, false);
}
/**
* Unexports object.
* @param id Object ID
* @param cause Stacktrace pf the object creation call
* @param severeErrorIfMissing Consider missing object as {@code SEVERE} error. {@code FINE} otherwise
*/
/*package*/ void unexport(int id, @CheckForNull Throwable cause, boolean severeErrorIfMissing) {
exportedObjects.unexportByOid(id, cause, severeErrorIfMissing);
}
/**
* Increase reference count so much to effectively prevent de-allocation.
* @param instance Instance to be pinned
*/
public void pin(@NonNull Object instance) {
exportedObjects.pin(instance);
}
/**
* {@linkplain #pin(Object) Pin down} the exported classloader.
*/
public void pinClassLoader(ClassLoader cl) {
RemoteClassLoader.pin(cl,this);
}
/**
* Preloads jar files on the remote side.
*
* <p>
* This is a performance improvement method that can be safely
* ignored if your goal is just to make things working.
*
* <p>
* Normally, classes are transferred over the network one at a time,
* on-demand. This design is mainly driven by how Java classloading works
* — we can't predict what classes will be necessarily upfront very easily.
*
* <p>
* Classes are loaded only once, so for long-running {@link Channel},
* this is normally an acceptable overhead. But sometimes, for example
* when a channel is short-lived, or when you know that you'll need
* a majority of classes in certain jar files, then it is more efficient
* to send a whole jar file over the network upfront and thereby
* avoiding individual class transfer over the network.
*
* <p>
* That is what this method does. It ensures that a series of jar files
* are copied to the remote side (AKA "preloading.")
* Classloading will consult the preloaded jars before performing
* network transfer of class files.
*
* <p><strong>Beware</strong> that this method is not useful in all configurations.
* If a {@link RemoteClassLoader} has another {@link RemoteClassLoader} as a
* {@linkplain ClassLoader#getParent parent}, which would be typical, then preloading
* a JAR in it will not reduce network round-trips: each class load still has to call
* {@link ClassLoader#loadClass(String, boolean) loadClass} on the parent, which will
* wind up checking the remote side just to get a negative answer.
*
* @param classLoaderRef
* This parameter is used to identify the remote classloader
* that will prefetch the specified jar files. That is, prefetching
* will ensure that prefetched jars will kick in
* when this {@link Callable} object is actually executed remote side.
*
* <p>
* {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader},
* so this parameter doesn't have to be exactly the same {@link Callable}
* to be executed later — it just has to be of the same class.
* @param classesInJar
* {@link Class} objects that identify jar files to be preloaded.
* Jar files that contain the specified classes will be preloaded into the remote peer.
* You just need to specify one class per one jar.
* @return
* true if the preloading actually happened. false if all the jars
* are already preloaded. This method is implemented in such a way that
* unnecessary jar file transfer will be avoided, and the return value
* will tell you if this optimization kicked in. Under normal circumstances
* your program shouldn't depend on this return value. It's just a hint.
* @throws IOException
* if the preloading fails.
*/
public boolean preloadJar(Callable<?,?> classLoaderRef, Class<?>... classesInJar) throws IOException, InterruptedException {
return preloadJar(UserRequest.getClassLoader(classLoaderRef), classesInJar);
}
public boolean preloadJar(ClassLoader local, Class<?>... classesInJar) throws IOException, InterruptedException {
URL[] jars = new URL[classesInJar.length];
for (int i = 0; i < classesInJar.length; i++)
jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL();
return call(new PreloadJarTask(jars, local));
}
public boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException {
return call(new PreloadJarTask(jars,local));
}
/**
* If this channel is built with jar file caching, return the object that manages this cache.
* @return JAR Cache object. {@code null} if JAR caching is disabled
* @since 2.24
* @since 3.10 JAR Cache is Nonnull
* @since 3.12 JAR Cache made nullable again due to <a href="https://issues.jenkins-ci.org/browse/JENKINS-45755">JENKINS-45755</a>
*/
@CheckForNull
public JarCache getJarCache() {
return jarCache;
}
/**
* You can change the {@link JarCache} while the channel is in operation,
* but doing so doesn't impact {@link RemoteClassLoader}s that are already created.
*
* So to best avoid performance loss due to race condition, please set a JarCache in the constructor,
* unless your call sequence guarantees that you call this method before remote classes are loaded.
*
* @param jarCache New JAR Cache to be used.
* Cannot be {@code null}, JAR Cache disabling on a running channel is not supported.
* @since 2.24
*/
public void setJarCache(@NonNull JarCache jarCache) {
this.jarCache = jarCache;
}
/*package*/ PipeWindow getPipeWindow(int oid) {
synchronized (pipeWindows) {
Key k = new Key(oid);
WeakReference<PipeWindow> v = pipeWindows.get(k);
if (v!=null) {
PipeWindow w = v.get();
if (w!=null)
return w;
}
PipeWindow w;
if (remoteCapability.supportsPipeThrottling())
w = new Real(k, PIPE_WINDOW_SIZE);
else
w = new PipeWindow.Fake();
pipeWindows.put(k, new WeakReference<>(w));
return w;
}
}
/**
* {@inheritDoc}
*/
@Override
public <V,T extends Throwable>
V call(Callable<V,T> callable) throws IOException, T, InterruptedException {
if (isClosingOrClosed()) {
// No reason to even try performing a user request
throw new ChannelClosedException(this, "Remote call on " + name + " failed. "
+ "The channel is closing down or has closed down", getCloseRequestCause());
}
UserRequest<V,T> request=null;
try {
request = new UserRequest<>(this, callable);
UserRequest.ResponseToUserRequest<V, T> r = request.call(this);
return r.retrieve(this, UserRequest.getClassLoader(callable));