public class Channel extends Object implements VirtualChannel, Closeable
A Channel is a mechanism for two JVMs to communicate over
bi-directional InputStream/OutputStream pair.
Channel represents an endpoint of the stream, and thus
two Channels are always used in a pair.
Communication is established as soon as two Channel instances
are created at the end fo the stream pair
until the stream is terminated via close().
The basic unit of remoting is an executable Callable object.
An application can create a Callable object, and execute it remotely
by using the call(Callable) method or callAsync(Callable) method.
In this sense, 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.
Callable object, as well as the return value / exceptions,
are transported by using Java serialization. All the necessary class files
are also shipped over Channel on-demand, so there's no need to
pre-deploy such classes on both JVMs.
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.
Command for more details. This is for higher-level features,
and not likely useful for applications directly.
Request for more details. This is for higher-level features,
and not likely useful for applications directly.
| Modifier and Type | Class and Description |
|---|---|
static class |
Channel.Listener
Callback "interface" for changes in the state of
Channel. |
static class |
Channel.Mode
Communication mode used in conjunction with
ClassicCommandTransport. |
| Modifier and Type | Field and Description |
|---|---|
AtomicInteger |
classLoadingCount
Total counts of remote classloading activities.
|
AtomicInteger |
classLoadingPrefetchCacheCount
Prefetch cache hits.
|
AtomicLong |
classLoadingTime
Total number of nanoseconds spent for remote class loading.
|
static int |
PIPE_WINDOW_SIZE
Default pipe window size.
|
Capability |
remoteCapability
Capability of the remote
Channel. |
AtomicInteger |
resourceLoadingCount
Total count of remote resource loading.
|
AtomicLong |
resourceLoadingTime
Total number of nanoseconds spent for remote resource loading.
|
| Modifier | Constructor and Description |
|---|---|
protected |
Channel(ChannelBuilder settings,
CommandTransport transport) |
|
Channel(String name,
ExecutorService exec,
Channel.Mode mode,
InputStream is,
OutputStream os)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
Channel.Mode mode,
InputStream is,
OutputStream os,
OutputStream header)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
Channel.Mode mode,
InputStream is,
OutputStream os,
OutputStream header,
boolean restricted)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
Channel.Mode mode,
InputStream is,
OutputStream os,
OutputStream header,
boolean restricted,
ClassLoader base)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
CommandTransport transport,
boolean restricted,
ClassLoader base)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
CommandTransport transport,
boolean restricted,
ClassLoader base,
JarCache jarCache)
Deprecated.
as of 2.38
|
|
Channel(String name,
ExecutorService exec,
InputStream is,
OutputStream os)
Deprecated.
as of 2.24
Use
ChannelBuilder |
|
Channel(String name,
ExecutorService exec,
InputStream is,
OutputStream os,
OutputStream header)
Deprecated.
as of 2.24
Use
ChannelBuilder |
| Modifier and Type | Method and Description |
|---|---|
void |
addListener(Channel.Listener l)
Registers a new
Channel.Listener. |
void |
addLocalExecutionInterceptor(CallableDecorator decorator)
Adds a
CallableFilter that gets a chance to decorate every Callables that run locally
sent by the other peer. |
void |
addLocalExecutionInterceptor(CallableFilter filter)
Deprecated.
|
<V,T extends Throwable> |
call(Callable<V,T> callable)
Makes a remote procedure call.
|
<V,T extends Throwable> |
callAsync(Callable<V,T> callable)
Makes an asynchronous remote procedure call.
|
void |
close()
Performs an orderly shut down of this channel (and the remote peer.)
|
void |
close(Throwable diagnosis)
Closes the channel.
|
ListeningPort |
createLocalToRemotePortForwarding(int recvPort,
String forwardHost,
int forwardPort)
Starts a local to remote port forwarding (the equivalent of "ssh -L").
|
ListeningPort |
createRemoteToLocalPortForwarding(int recvPort,
String forwardHost,
int forwardPort)
Starts a remote to local port forwarding (the equivalent of "ssh -R").
|
static Channel |
current()
This method can be invoked during the serialization/deserialization of
objects when they are transferred to the remote
Channel,
as well as during Callable.call() is invoked. |
void |
dumpDiagnostics(PrintWriter w)
Print the diagnostic information.
|
static void |
dumpDiagnosticsForAll(PrintWriter w)
Calls
dumpDiagnostics(PrintWriter) across all the active channels in this system. |
void |
dumpExportTable(PrintWriter w)
Dumps the list of exported objects and their allocation traces to the given output.
|
void |
dumpPerformanceCounters(PrintWriter w)
Print the performance counters.
|
<T> T |
export(Class<T> type,
T instance)
Exports an object for remoting to the other
Channel
by creating a remotable proxy. |
Throwable |
getCloseRequestCause()
Gets cause of the close request.
|
JarCache |
getJarCache()
If this channel is built with jar file caching, return the object that manages this cache.
|
long |
getLastHeard()
TODO: this is not safe against clock skew and is called from jenkins core (and potentially plugins)
|
String |
getName() |
<T> T |
getProperty(ChannelProperty<T> key) |
Object |
getProperty(Object key)
Gets the application specific property set by
setProperty(Object, Object). |
<T> T |
getRemoteProperty(ChannelProperty<T> key) |
Object |
getRemoteProperty(Object key)
Gets the property set on the remote peer.
|
Throwable |
getSenderCloseCause()
Get why the sender side of the channel has been closed.
|
OutputStream |
getUnderlyingOutput()
Deprecated.
Future version of the remoting module may add other modes of creating channel
that doesn't involve stream pair. Therefore, we aren't committing to this method.
This method isn't a part of the committed API of the channel class.
|
boolean |
isArbitraryCallableAllowed() |
boolean |
isClosingOrClosed()
Returns
true if the channel is either in the process of closing down or has closed down. |
boolean |
isInClosed()
If the receiving end of the channel is closed (that is, if we are guaranteed to receive nothing further),
this method returns true.
|
boolean |
isOutClosed()
Is the sender side of the transport already closed?
|
boolean |
isRemoteClassLoadingAllowed() |
boolean |
isRestricted()
Deprecated.
Use methods like
isRemoteClassLoadingAllowed() and isArbitraryCallableAllowed()
to test individual features. |
void |
join()
Waits for this
Channel to be closed down. |
void |
join(long timeout)
Waits for this
Channel to be closed down, but only up the given milliseconds. |
void |
pin(Object instance)
Increase reference count so much to effectively prevent de-allocation.
|
void |
pinClassLoader(ClassLoader cl)
Pin down the exported classloader.
|
boolean |
preloadJar(Callable<?,?> classLoaderRef,
Class... classesInJar)
Preloads jar files on the remote side.
|
boolean |
preloadJar(ClassLoader local,
Class... classesInJar) |
boolean |
preloadJar(ClassLoader local,
URL... jars) |
boolean |
removeListener(Channel.Listener l)
Removes a listener.
|
void |
removeLocalExecutionInterceptor(CallableDecorator decorator)
Removes the filter introduced by
addLocalExecutionInterceptor(CallableFilter). |
void |
removeLocalExecutionInterceptor(CallableFilter filter)
Deprecated.
|
void |
resetPerformanceCounters()
Resets all the performance counters.
|
void |
setArbitraryCallableAllowed(boolean b) |
void |
setJarCache(JarCache jarCache)
You can change the
JarCache while the channel is in operation,
but doing so doesn't impact RemoteClassLoaders that are already created. |
void |
setMaximumBytecodeLevel(short level)
Sets the maximum bytecode version (~ JDK) that we expect this channel to be able to load.
|
<T> T |
setProperty(ChannelProperty<T> key,
T value) |
Object |
setProperty(Object key,
Object value)
Sets the property value on this side of the channel.
|
void |
setRemoteClassLoadingAllowed(boolean b)
Controls whether or not this channel is willing to load classes from the other side.
|
void |
setRestricted(boolean b)
Deprecated.
Use methods like
setRemoteClassLoadingAllowed(boolean) and setArbitraryCallableAllowed(boolean)
to control individual features. |
hudson.remoting.ExportTable.ExportList |
startExportRecording() |
void |
syncIO()
Blocks until all the I/O packets sent before this gets fully executed by the remote side, then return.
|
void |
syncLocalIO()
Blocks until all the I/O packets sent from remote is fully locally executed, then return.
|
void |
terminate(IOException e)
Aborts the connection in response to an error.
|
String |
toString() |
<T> T |
waitForProperty(ChannelProperty<T> key) |
Object |
waitForProperty(Object key)
Works like
getProperty(Object) but wait until some value is set by someone. |
<T> T |
waitForRemoteProperty(ChannelProperty<T> key)
Deprecated.
Because
ChannelProperty is identity-equality, this method would never work.
This is a design error. |
Object |
waitForRemoteProperty(Object key)
Gets the property set on the remote peer.
|
public final AtomicLong classLoadingTime
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.)
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 AtomicInteger classLoadingCount
classLoadingTime.public final AtomicInteger classLoadingPrefetchCacheCount
classLoadingCount, how many times
were we able to resolve them by ourselves, saving a remote roundtrip call?public final AtomicLong resourceLoadingTime
classLoadingTimepublic final AtomicInteger resourceLoadingCount
classLoadingCountpublic final Capability remoteCapability
Channel.public static final int PIPE_WINDOW_SIZE
This controls the amount of bytes that can be in flight. Value too small would fail to efficiently utilize a high-latency/large-bandwidth network, but a value too large would cause the risk of a large memory consumption when a pipe clogs (that is, the receiver isn't consuming bytes we are sending fast enough.)
If we have a gigabit ethernet (with effective transfer rate of 100M bps) and 20ms latency, the pipe will hold (100M bits/sec * 0.02sec / 8 bits/byte = 0.25MB. So 1MB or so is big enough for most network, and hopefully this is an acceptable enough memory consumption in case of clogging.
PipeWindow@Deprecated public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, Channel.Mode mode, InputStream is, OutputStream os) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, Channel.Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, Channel.Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, Channel.Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException
ChannelBuilderrestricted - IOException@Deprecated public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base) throws IOException
ChannelBuilderIOException@Deprecated public Channel(String name, ExecutorService exec, CommandTransport transport, boolean restricted, ClassLoader base, JarCache jarCache) throws IOException
name - See Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)exec - See Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)transport - The transport that we run Channel on top of.base - See Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)restricted - See Channel(String, ExecutorService, Mode, InputStream, OutputStream, OutputStream, boolean, ClassLoader)jarCache - IOExceptionprotected Channel(@Nonnull ChannelBuilder settings, @Nonnull CommandTransport transport) throws IOException
IOExceptionpublic boolean isOutClosed()
@CheckForNull public final Throwable getSenderCloseCause()
null if the sender side is active.
null result does not guarantee that the channel is actually operational.public boolean isClosingOrClosed()
true if the channel is either in the process of closing down or has closed down.
If the result is true, it means that the channel will be closed at some point by Remoting,
and that it makes no sense to send any new UserRequests to the remote side.
Invocations like call(hudson.remoting.Callable) and callAsync(hudson.remoting.Callable)
will just fail as well.@CheckForNull public Throwable getCloseRequestCause()
outClosed if not null, value of the transient cache
closeRequestCause otherwise.
The latter one may show random cause in the case of race conditions.public <T> T export(Class<T> type, T instance)
Channel
by creating a remotable proxy.
The returned reference must be kept if there is ongoing operation on the remote side.
Once it is released, the exported object will be deallocated as well.
Please keep in mind that the object may be also released earlier than expected by JVM
(e.g. see JENKINS-23271).export in interface VirtualChannelT - Typetype - Interface to be remoted.instance - Instance to be exported.
null instances won't be exported to the remote instance.
All the parameters and return values must be serializable.
Channel, and calling methods on it from the remote side
will invoke the same method on the given local instance object.
null if the input instance is null.public void pin(@Nonnull Object instance)
instance - Instance to be pinnedpublic void pinClassLoader(ClassLoader cl)
public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException
This is a performance improvement method that can be safely ignored if your goal is just to make things working.
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.
Classes are loaded only once, so for long-running 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.
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.
Beware that this method is not useful in all configurations.
If a RemoteClassLoader has another RemoteClassLoader as a
parent, which would be typical, then preloading
a JAR in it will not reduce network round-trips: each class load still has to call
loadClass on the parent, which will
wind up checking the remote side just to get a negative answer.
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 Callable object is actually executed remote side.
RemoteClassLoaders are created wisely, one per local ClassLoader,
so this parameter doesn't have to be exactly the same Callable
to be executed later — it just has to be of the same class.
classesInJar - 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.IOException - if the preloading fails.InterruptedExceptionpublic boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException
IOExceptionInterruptedExceptionpublic boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException
IOExceptionInterruptedException@CheckForNull public JarCache getJarCache()
null if JAR caching is disabledpublic void setJarCache(@Nonnull JarCache jarCache)
JarCache while the channel is in operation,
but doing so doesn't impact RemoteClassLoaders 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.jarCache - New JAR Cache to be used.
Cannot be null, JAR Cache disabling on a running channel is not supported.public <V,T extends Throwable> V call(Callable<V,T> callable) throws IOException, T extends Throwable, InterruptedException
Sends Callable to the remote system, executes it, and returns its result.
Such calls will be considered as user-space requests.
If the channel cannot execute the requests (e.g. when it is being closed),
the operations may be rejected even if the channel is still active.
call in interface VirtualChannelcallable - Callable to be executedIOException - If there's any error in the communication between Channels.T - User exception defined by the callableInterruptedException - If the current thread is interrupted while waiting for the completion.T extends Throwablepublic <V,T extends Throwable> Future<V> callAsync(Callable<V,T> callable) throws IOException
Similar to VirtualChannel.call(Callable) but returns immediately.
The result of the Callable can be obtained through the Future object.
Such calls will be considered as user-space requests.
If the channel cannot execute the requests (e.g. when it is being closed),
the operations may be rejected even if the channel is still active.
callAsync in interface VirtualChannelFuture object that can be used to wait for the completion.IOException - If there's an error during the communication.public void terminate(@Nonnull IOException e)
CommandTransport implementation to notify
Channel when the underlying connection is severed.
Once the call is called closeRequested will be set immediately to prevent further executions
of UserRequests.e - The error that caused the connection to be aborted. Never null.public void addListener(Channel.Listener l)
Channel.Listener.removeListener(Listener)public boolean removeListener(Channel.Listener l)
public void addLocalExecutionInterceptor(CallableDecorator decorator)
CallableFilter that gets a chance to decorate every Callables that run locally
sent by the other peer.
This is useful to tweak the environment those closures are run, such as setting up the thread context
environment.public void removeLocalExecutionInterceptor(CallableDecorator decorator)
addLocalExecutionInterceptor(CallableFilter).@Deprecated public void addLocalExecutionInterceptor(CallableFilter filter)
addLocalExecutionInterceptor(CallableDecorator)@Deprecated public void removeLocalExecutionInterceptor(CallableFilter filter)
removeLocalExecutionInterceptor(CallableDecorator)public void join()
throws InterruptedException
Channel to be closed down.
The close-down of a Channel might be initiated locally or remotely.join in interface VirtualChannelInterruptedException - If the current thread is interrupted while waiting for the completion.public boolean isInClosed()
@Deprecated public boolean isRestricted()
isRemoteClassLoadingAllowed() and isArbitraryCallableAllowed()
to test individual features.@Deprecated public void setRestricted(boolean b)
setRemoteClassLoadingAllowed(boolean) and setArbitraryCallableAllowed(boolean)
to control individual features.public boolean isRemoteClassLoadingAllowed()
public void setRemoteClassLoadingAllowed(boolean b)
public boolean isArbitraryCallableAllowed()
public void setArbitraryCallableAllowed(boolean b)
ChannelBuilder.withArbitraryCallableAllowed(boolean)public void setMaximumBytecodeLevel(short level)
throws IOException,
InterruptedException
level - e.g. 5 for JDK 5 (the minimum sensible value)IOExceptionInterruptedExceptionpublic void join(long timeout)
throws InterruptedException
Channel to be closed down, but only up the given milliseconds.join in interface VirtualChanneltimeout - TImeout in millisecondsInterruptedException - If the current thread is interrupted while waiting for the completion.public void resetPerformanceCounters()
public void dumpPerformanceCounters(PrintWriter w) throws IOException
w - Output writerIOException@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public void dumpDiagnostics(@Nonnull PrintWriter w) throws IOException
Here's how you interpret these metrics:
Command objects sent to the other side. More specifically, number of commands
successfully passed to transport, which means data was written to socket with
ClassicCommandTransport but just buffered for write with NioChannelHub.
If you have access to the remoting diagnostics
of the other side of the channel, then you can compare this with "commandsReceived" metrics of the other
side to see how many commands are in transit in transport. If commandsSent==commandsReceived,
then no command is in transit.
Command objects received from the other side. More precisely, number
of commands reported from transport. So for example, if data is still buffered somewhere
in the networking stack, it won't be counted here.
lastCommandSentAt was updated.
lastCommandReceivedAt was updated.
w - Output destinationIOException - Error while creating or writing the channel informationpublic void close()
throws IOException
close in interface VirtualChannelclose in interface Closeableclose in interface AutoCloseableIOException - if the orderly shut-down failed.public void close(@CheckForNull Throwable diagnosis) throws IOException
closeRequested will be set immediately to prevent further executions
of UserRequests.diagnosis - If someone (either this side or the other side) tries to use a channel that's already closed,
they'll get a stack trace indicating that the channel has already been closed. This diagnosis,
if provided, will further chained to that exception, providing more contextual information
about why the channel was closed.IOExceptionpublic Object getProperty(Object key)
setProperty(Object, Object).
These properties are also accessible from the remote channel via getRemoteProperty(Object).
This mechanism can be used for one side to discover contextual objects created by the other JVM
(as opposed to executing Callable, which cannot have any reference to the context
of the remote Channel.
public <T> T getProperty(ChannelProperty<T> key)
public Object waitForProperty(Object key) throws InterruptedException
getProperty(Object) but wait until some value is set by someone.IllegalStateException - if the channel is closed. The idea is that channel properties are expected to be the coordination
mechanism between two sides of the channel, and this method in particular is a way of one side
to wait for the set by the other side of the channel (via waitForRemoteProperty(Object).
If we don't abort after the channel shutdown, this method will block forever.InterruptedExceptionpublic <T> T waitForProperty(ChannelProperty<T> key) throws InterruptedException
InterruptedExceptionpublic Object setProperty(Object key, Object value)
getProperty(Object)public <T> T setProperty(ChannelProperty<T> key, T value)
@CheckForNull public Object getRemoteProperty(Object key)
null
if the property of the said key isn't set.@CheckForNull public <T> T getRemoteProperty(ChannelProperty<T> key)
public Object waitForRemoteProperty(Object key) throws InterruptedException
InterruptedException@Deprecated public <T> T waitForRemoteProperty(ChannelProperty<T> key) throws InterruptedException
ChannelProperty is identity-equality, this method would never work.
This is a design error.InterruptedException@Deprecated public OutputStream getUnderlyingOutput()
Channel is not sitting on top of a stream pair.public ListeningPort createLocalToRemotePortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException
recvPort - The port on this local machine that we'll listen to. 0 to let
OS pick a random available port. If you specify 0, use
ListeningPort.getPort() to figure out the actual assigned port.forwardHost - The remote host that the connection will be forwarded to.
Connection to this host will be made from the other JVM that
this Channel represents.forwardPort - The remote port that the connection will be forwarded to.IOExceptionInterruptedExceptionpublic ListeningPort createRemoteToLocalPortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException
recvPort - The port on the remote JVM (represented by this Channel)
that we'll listen to. 0 to let
OS pick a random available port. If you specify 0, use
ListeningPort.getPort() to figure out the actual assigned port.forwardHost - The remote host that the connection will be forwarded to.
Connection to this host will be made from this JVM.forwardPort - The remote port that the connection will be forwarded to.IOExceptionInterruptedExceptionpublic void syncIO()
throws IOException,
InterruptedException
IOException - If the remote doesn't support this operation, or if sync fails for other reasons.InterruptedExceptionpublic void syncLocalIO()
throws InterruptedException
VirtualChannelsyncLocalIO in interface VirtualChannelInterruptedExceptionpublic String getName()
public void dumpExportTable(PrintWriter w) throws IOException
IOExceptionpublic hudson.remoting.ExportTable.ExportList startExportRecording()
public long getLastHeard()
lastCommandReceivedAt@CheckForNull public static Channel current()
Channel,
as well as during Callable.call() is invoked.null
if the calling thread is not performing serialization.@Restricted(value=org.kohsuke.accmod.restrictions.NoExternalUse.class) public static void dumpDiagnosticsForAll(@Nonnull PrintWriter w)
dumpDiagnostics(PrintWriter) across all the active channels in this system.
Used for diagnostics.w - Output destinationCopyright © 2004–2017. All rights reserved.