View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.local;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.AbstractChannel;
20  import io.netty.channel.Channel;
21  import io.netty.channel.ChannelConfig;
22  import io.netty.channel.ChannelMetadata;
23  import io.netty.channel.ChannelOutboundBuffer;
24  import io.netty.channel.ChannelPipeline;
25  import io.netty.channel.ChannelPromise;
26  import io.netty.channel.DefaultChannelConfig;
27  import io.netty.channel.EventLoop;
28  import io.netty.channel.IoEvent;
29  import io.netty.channel.IoEventLoop;
30  import io.netty.channel.IoRegistration;
31  import io.netty.channel.PreferHeapByteBufAllocator;
32  import io.netty.channel.RecvByteBufAllocator;
33  import io.netty.channel.SingleThreadEventLoop;
34  import io.netty.util.ReferenceCountUtil;
35  import io.netty.util.concurrent.Future;
36  import io.netty.util.concurrent.SingleThreadEventExecutor;
37  import io.netty.util.internal.InternalThreadLocalMap;
38  import io.netty.util.internal.PlatformDependent;
39  import io.netty.util.internal.logging.InternalLogger;
40  import io.netty.util.internal.logging.InternalLoggerFactory;
41  
42  import java.net.ConnectException;
43  import java.net.SocketAddress;
44  import java.nio.channels.AlreadyConnectedException;
45  import java.nio.channels.ClosedChannelException;
46  import java.nio.channels.ConnectionPendingException;
47  import java.nio.channels.NotYetConnectedException;
48  import java.util.Queue;
49  import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
50  
51  /**
52   * A {@link Channel} for the local transport.
53   */
54  public class LocalChannel extends AbstractChannel {
55      private static final InternalLogger logger = InternalLoggerFactory.getInstance(LocalChannel.class);
56      @SuppressWarnings({ "rawtypes" })
57      private static final AtomicReferenceFieldUpdater<LocalChannel, Future> FINISH_READ_FUTURE_UPDATER =
58              AtomicReferenceFieldUpdater.newUpdater(LocalChannel.class, Future.class, "finishReadFuture");
59      private static final AtomicReferenceFieldUpdater<LocalChannel, State> STATE_UPDATER =
60              AtomicReferenceFieldUpdater.newUpdater(LocalChannel.class, State.class, "state");
61      private static final ChannelMetadata METADATA = new ChannelMetadata(false);
62      private static final int MAX_READER_STACK_DEPTH = 8;
63  
64      private enum State { OPEN, BOUND, CONNECTED, CLOSED }
65  
66      private final ChannelConfig config = new DefaultChannelConfig(this);
67      // To further optimize this we could write our own SPSC queue.
68      final Queue<Object> inboundBuffer = PlatformDependent.newSpscQueue();
69      private final Runnable readTask = new Runnable() {
70          @Override
71          public void run() {
72              // Ensure the inboundBuffer is not empty as readInbound() will always call fireChannelReadComplete()
73              if (!inboundBuffer.isEmpty()) {
74                  readInbound();
75              }
76          }
77      };
78  
79      private final Runnable finishReadTask = new Runnable() {
80          @Override
81          public void run() {
82              finishPeerRead0(LocalChannel.this);
83          }
84      };
85  
86      private IoRegistration registration;
87  
88      private volatile State state;
89      private volatile LocalChannel peer;
90      private volatile LocalAddress localAddress;
91      private volatile LocalAddress remoteAddress;
92      private volatile ChannelPromise connectPromise;
93      private volatile boolean readInProgress;
94      private volatile boolean writeInProgress;
95      private volatile Future<?> finishReadFuture;
96  
97      public LocalChannel() {
98          super(null);
99          config().setAllocator(new PreferHeapByteBufAllocator(config.getAllocator()));
100     }
101 
102     protected LocalChannel(LocalServerChannel parent, LocalChannel peer) {
103         super(parent);
104         config().setAllocator(new PreferHeapByteBufAllocator(config.getAllocator()));
105         this.peer = peer;
106         localAddress = parent.localAddress();
107         remoteAddress = peer.localAddress();
108     }
109 
110     @Override
111     public ChannelMetadata metadata() {
112         return METADATA;
113     }
114 
115     @Override
116     public ChannelConfig config() {
117         return config;
118     }
119 
120     @Override
121     public LocalServerChannel parent() {
122         return (LocalServerChannel) super.parent();
123     }
124 
125     @Override
126     public LocalAddress localAddress() {
127         return (LocalAddress) super.localAddress();
128     }
129 
130     @Override
131     public LocalAddress remoteAddress() {
132         return (LocalAddress) super.remoteAddress();
133     }
134 
135     @Override
136     public boolean isOpen() {
137         return state != State.CLOSED;
138     }
139 
140     @Override
141     public boolean isActive() {
142         return state == State.CONNECTED;
143     }
144 
145     @Override
146     protected AbstractUnsafe newUnsafe() {
147         return new LocalUnsafe();
148     }
149 
150     @Override
151     protected boolean isCompatible(EventLoop loop) {
152         return loop instanceof SingleThreadEventLoop ||
153                 (loop instanceof IoEventLoop && ((IoEventLoop) loop).isCompatible(LocalUnsafe.class));
154     }
155 
156     @Override
157     protected SocketAddress localAddress0() {
158         return localAddress;
159     }
160 
161     @Override
162     protected SocketAddress remoteAddress0() {
163         return remoteAddress;
164     }
165 
166     @Override
167     protected void doRegister(ChannelPromise promise) {
168         EventLoop loop = eventLoop();
169         if (loop instanceof IoEventLoop) {
170             assert registration == null;
171             ((IoEventLoop) loop).register((LocalUnsafe) unsafe()).addListener(f -> {
172                if (f.isSuccess()) {
173                    registration = (IoRegistration) f.getNow();
174                    promise.setSuccess();
175                } else {
176                    promise.setFailure(f.cause());
177                }
178             });
179         } else {
180             try {
181                 ((LocalUnsafe) unsafe()).registered();
182             } catch (Throwable cause) {
183                 promise.setFailure(cause);
184             }
185             promise.setSuccess();
186         }
187     }
188 
189     @Override
190     protected void doDeregister() throws Exception {
191         EventLoop loop = eventLoop();
192         if (loop instanceof IoEventLoop) {
193             IoRegistration registration = this.registration;
194             if (registration != null) {
195                 this.registration = null;
196                 registration.cancel();
197             }
198         } else {
199             ((LocalUnsafe) unsafe()).unregistered();
200         }
201     }
202 
203     @Override
204     protected void doBind(SocketAddress localAddress) throws Exception {
205         this.localAddress =
206                 LocalChannelRegistry.register(this, this.localAddress,
207                         localAddress);
208         state = State.BOUND;
209     }
210 
211     @Override
212     protected void doDisconnect() throws Exception {
213         doClose();
214     }
215 
216     @Override
217     protected void doClose() throws Exception {
218         final LocalChannel peer = this.peer;
219         State oldState = state;
220         State closedFrom = oldState;
221         try {
222             if (oldState != State.CLOSED) {
223                 // Update all internal state before the closeFuture is notified.
224                 if (localAddress != null) {
225                     if (parent() == null) {
226                         LocalChannelRegistry.unregister(localAddress);
227                     }
228                     localAddress = null;
229                 }
230 
231                 // State change must happen before finishPeerRead to ensure writes are released either in doWrite or
232                 // channelRead.
233                 // Use getAndSet() as an accepted channel may concurrently move this channel from BOUND to CONNECTED
234                 // when it is registered. See LocalUnsafe.registered().
235                 closedFrom = STATE_UPDATER.getAndSet(this, State.CLOSED);
236 
237                 // Preserve order of event and force a read operation now before the close operation is processed.
238                 if (writeInProgress && peer != null) {
239                     finishPeerRead(peer);
240                 }
241 
242                 ChannelPromise promise = connectPromise;
243                 if (promise != null) {
244                     // Use tryFailure() instead of setFailure() to avoid the race against cancel().
245                     promise.tryFailure(new ClosedChannelException());
246                     connectPromise = null;
247                 }
248             }
249 
250             if (peer != null && parent() == null && closedFrom != State.CONNECTED) {
251                 // The accepted channel did not complete the connection. Don't touch it: it may not have an event
252                 // loop yet and is owned by the server channel or its own event loop. When it is registered it sees
253                 // that this channel is closed and closes itself. If it was closed already, its close has notified
254                 // this channel or will do so.
255                 this.peer = null;
256             } else if (peer != null) {
257                 this.peer = null;
258                 // Always call peer.eventLoop().execute() even if peer.eventLoop().inEventLoop() is true.
259                 // This ensures that if both channels are on the same event loop, the peer's channelInActive
260                 // event is triggered *after* this peer's channelInActive event
261                 EventLoop peerEventLoop = peer.eventLoop();
262                 final boolean peerIsActive = peer.isActive();
263                 try {
264                     peerEventLoop.execute(new Runnable() {
265                         @Override
266                         public void run() {
267                             peer.tryClose(peerIsActive);
268                         }
269                     });
270                 } catch (Throwable cause) {
271                     logger.warn("Releasing Inbound Queues for channels {}-{} because exception occurred!",
272                             this, peer, cause);
273                     if (peerEventLoop.inEventLoop()) {
274                         peer.releaseInboundBuffers();
275                     } else {
276                         // inboundBuffers is a SPSC so we may leak if the event loop is shutdown prematurely or
277                         // rejects the close Runnable but give a best effort.
278                         peer.close();
279                     }
280                     PlatformDependent.throwException(cause);
281                 }
282             }
283         } finally {
284             // Release all buffers if the Channel was already registered in the past and if it was not closed before.
285             if (oldState != null && oldState != State.CLOSED) {
286                 // We need to release all the buffers that may be put into our inbound queue since we closed the Channel
287                 // to ensure we not leak any memory. This is fine as it basically gives the same guarantees as TCP which
288                 // means even if the promise was notified before its not really guaranteed that the "remote peer" will
289                 // see the buffer at all.
290                 releaseInboundBuffers();
291             }
292         }
293     }
294 
295     private void tryClose(boolean isActive) {
296         if (isActive) {
297             // Data the peer wrote before it closed must be delivered before we close, like TCP does for data that
298             // arrived before the FIN. The finishReadTask may have been re-queued behind this task by
299             // finishPeerRead0(...) if we were writing while the peer wrote, and a read may still be pending in a
300             // readTask (see doBeginRead()) if more was queued than one read delivers. In both cases the data would
301             // otherwise be dropped by releaseInboundBuffers(), so read everything that is left now.
302             finishPeerRead0(this);
303             readInboundBeforeClose();
304             unsafe().close(unsafe().voidPromise());
305         } else if (connectPromise != null) {
306             // The accepted channel was closed before the connection was established, for example because the server
307             // channel was closed. It is closed already, so don't notify it again. Fail the connect like a refused
308             // connection and close this channel.
309             ChannelPromise promise = connectPromise;
310             connectPromise = null;
311             peer = null;
312             promise.tryFailure(new ConnectException("connection refused: the accepted channel was closed"));
313             unsafe().close(unsafe().voidPromise());
314         } else {
315             releaseInboundBuffers();
316         }
317     }
318 
319     private void readInboundBeforeClose() {
320         // The peer is closed, so nothing is added to the inboundBuffer anymore. Stop if a handler closed this
321         // channel, in which case the inboundBuffer was released.
322         while (!inboundBuffer.isEmpty() && isOpen()) {
323             readInProgress = false;
324             readInbound();
325         }
326     }
327 
328     private void readInbound() {
329         RecvByteBufAllocator.Handle handle = unsafe().recvBufAllocHandle();
330         handle.reset(config());
331         ChannelPipeline pipeline = pipeline();
332         do {
333             Object received = inboundBuffer.poll();
334             if (received == null) {
335                 break;
336             }
337             if (received instanceof ByteBuf && inboundBuffer.peek() instanceof ByteBuf) {
338                 ByteBuf msg = (ByteBuf) received;
339                 ByteBuf output = handle.allocate(alloc());
340                 if (msg.readableBytes() < output.writableBytes()) {
341                     // We have an opportunity to coalesce buffers.
342                     output.writeBytes(msg, msg.readerIndex(), msg.readableBytes());
343                     msg.release();
344                     while ((received = inboundBuffer.peek()) instanceof ByteBuf &&
345                             ((ByteBuf) received).readableBytes() < output.writableBytes()) {
346                         inboundBuffer.poll();
347                         msg = (ByteBuf) received;
348                         output.writeBytes(msg, msg.readerIndex(), msg.readableBytes());
349                         msg.release();
350                     }
351                     handle.lastBytesRead(output.readableBytes());
352                     received = output; // Send the coalesced buffer down the pipeline.
353                 } else {
354                     // It won't be profitable to coalesce buffers this time around.
355                     handle.lastBytesRead(output.capacity());
356                     output.release();
357                 }
358             }
359             handle.incMessagesRead(1);
360             pipeline.fireChannelRead(received);
361         } while (handle.continueReading());
362         handle.readComplete();
363         pipeline.fireChannelReadComplete();
364     }
365 
366     @Override
367     protected void doBeginRead() throws Exception {
368         if (readInProgress) {
369             return;
370         }
371 
372         Queue<Object> inboundBuffer = this.inboundBuffer;
373         if (inboundBuffer.isEmpty()) {
374             readInProgress = true;
375             return;
376         }
377 
378         final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get();
379         final int stackDepth = threadLocals.localChannelReaderStackDepth();
380         if (stackDepth < MAX_READER_STACK_DEPTH) {
381             threadLocals.setLocalChannelReaderStackDepth(stackDepth + 1);
382             try {
383                 readInbound();
384             } finally {
385                 threadLocals.setLocalChannelReaderStackDepth(stackDepth);
386             }
387         } else {
388             try {
389                 eventLoop().execute(readTask);
390             } catch (Throwable cause) {
391                 logger.warn("Closing Local channels {}-{} because exception occurred!", this, peer, cause);
392                 close();
393                 peer.close();
394                 PlatformDependent.throwException(cause);
395             }
396         }
397     }
398 
399     @Override
400     protected void doWrite(ChannelOutboundBuffer in) throws Exception {
401         switch (state) {
402         case OPEN:
403         case BOUND:
404             throw new NotYetConnectedException();
405         case CLOSED:
406             throw new ClosedChannelException();
407         case CONNECTED:
408             break;
409         }
410 
411         final LocalChannel peer = this.peer;
412 
413         writeInProgress = true;
414         try {
415             ClosedChannelException exception = null;
416             for (;;) {
417                 Object msg = in.current();
418                 if (msg == null) {
419                     break;
420                 }
421                 try {
422                     // It is possible the peer could have closed while we are writing, and in this case we should
423                     // simulate real socket behavior and ensure the write operation is failed.
424                     if (peer.state == State.CONNECTED) {
425                         peer.inboundBuffer.add(ReferenceCountUtil.retain(msg));
426                         in.remove();
427                     } else {
428                         if (exception == null) {
429                             exception = new ClosedChannelException();
430                         }
431                         in.remove(exception);
432                     }
433                 } catch (Throwable cause) {
434                     in.remove(cause);
435                 }
436             }
437         } finally {
438             // The following situation may cause trouble:
439             // 1. Write (with promise X)
440             // 2. promise X is completed when in.remove() is called, and a listener on this promise calls close()
441             // 3. Then the close event will be executed for the peer before the write events, when the write events
442             // actually happened before the close event.
443             writeInProgress = false;
444         }
445 
446         finishPeerRead(peer);
447     }
448 
449     private void finishPeerRead(final LocalChannel peer) {
450         // If the peer is also writing, then we must schedule the event on the event loop to preserve read order.
451         if (peer.eventLoop() == eventLoop() && !peer.writeInProgress) {
452             finishPeerRead0(peer);
453         } else {
454             runFinishPeerReadTask(peer);
455         }
456     }
457 
458     private void runFinishTask0() {
459         // If the peer is writing, we must wait until after reads are completed for that peer before we can read. So
460         // we keep track of the task, and coordinate later that our read can't happen until the peer is done.
461         if (writeInProgress) {
462             finishReadFuture = eventLoop().submit(finishReadTask);
463         } else {
464             eventLoop().execute(finishReadTask);
465         }
466     }
467 
468     private void runFinishPeerReadTask(final LocalChannel peer) {
469         try {
470             peer.runFinishTask0();
471         } catch (Throwable cause) {
472             logger.warn("Closing Local channels {}-{} because exception occurred!", this, peer, cause);
473             close();
474             peer.close();
475             PlatformDependent.throwException(cause);
476         }
477     }
478 
479     private void releaseInboundBuffers() {
480         assert eventLoop() == null || eventLoop().inEventLoop();
481         readInProgress = false;
482         Queue<Object> inboundBuffer = this.inboundBuffer;
483         Object msg;
484         while ((msg = inboundBuffer.poll()) != null) {
485             ReferenceCountUtil.release(msg);
486         }
487     }
488 
489     private void finishPeerRead0(LocalChannel peer) {
490         Future<?> peerFinishReadFuture = peer.finishReadFuture;
491         if (peerFinishReadFuture != null) {
492             if (!peerFinishReadFuture.isDone()) {
493                 runFinishPeerReadTask(peer);
494                 return;
495             } else {
496                 // Lazy unset to make sure we don't prematurely unset it while scheduling a new task.
497                 FINISH_READ_FUTURE_UPDATER.compareAndSet(peer, peerFinishReadFuture, null);
498             }
499         }
500         // We should only set readInProgress to false if there is any data that was read as otherwise we may miss to
501         // forward data later on.
502         if (peer.readInProgress && !peer.inboundBuffer.isEmpty()) {
503             peer.readInProgress = false;
504             peer.readInbound();
505         }
506     }
507 
508     private class LocalUnsafe extends AbstractUnsafe implements LocalIoHandle {
509 
510         private final Runnable shutdownHook = this::closeNow;
511 
512         @Override
513         public void close() {
514             close(voidPromise());
515         }
516 
517         @Override
518         public void handle(IoRegistration registration, IoEvent event) {
519             // NOOP
520         }
521 
522         @Override
523         public void registered() {
524             // Check if both peer and parent are non-null because this channel was created by a LocalServerChannel.
525             // This is needed as a peer may not be null also if a LocalChannel was connected before and
526             // deregistered / registered later again.
527             //
528             // See https://github.com/netty/netty/issues/2400
529             //
530             // Store the peer in a local variable as it may be set to null if doClose() is called.
531             // See https://github.com/netty/netty/issues/2144
532             final LocalChannel peer = LocalChannel.this.peer;
533             if (peer != null && parent() != null) {
534                 // Set our state before the peer's, so the peer sees this channel as active once it is connected.
535                 State oldState = state;
536                 state = State.CONNECTED;
537 
538                 // Move the peer from BOUND to CONNECTED atomically, as it may be closed concurrently on its own
539                 // event loop. If this channel was connected before and is registered again, the peer is CONNECTED
540                 // already.
541                 if (STATE_UPDATER.compareAndSet(peer, State.BOUND, State.CONNECTED) ||
542                         peer.state == State.CONNECTED) {
543                     peer.remoteAddress = parent().localAddress();
544 
545                     // Always call peer.eventLoop().execute() even if peer.eventLoop().inEventLoop() is true.
546                     // This ensures that if both channels are on the same event loop, the peer's channelActive
547                     // event is triggered *after* this channel's channelRegistered event, so that this channel's
548                     // pipeline is fully initialized by ChannelInitializer before any channelRead events.
549                     peer.eventLoop().execute(new Runnable() {
550                         @Override
551                         public void run() {
552                             ChannelPromise promise = peer.connectPromise;
553 
554                             // Only trigger fireChannelActive() if the promise was not null and was not completed
555                             // yet. connectPromise may be set to null if doClose() was called in the meantime.
556                             if (promise != null && promise.trySuccess()) {
557                                 peer.pipeline().fireChannelActive();
558                             }
559                         }
560                     });
561                 } else {
562                     // The peer was closed before this channel was registered, so it never uses this channel.
563                     // Close this channel once the registration is complete.
564                     LocalChannel.this.peer = null;
565                     state = oldState;
566                     eventLoop().execute(this::closeNow);
567                 }
568             }
569             EventLoop loop = eventLoop();
570             if (!(loop instanceof IoEventLoop) && loop instanceof SingleThreadEventExecutor) {
571                 ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook);
572             }
573         }
574 
575         @Override
576         public void unregistered() {
577             EventLoop loop = eventLoop();
578             if (!(loop instanceof IoEventLoop) && loop instanceof SingleThreadEventExecutor) {
579                 ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook);
580             }
581         }
582 
583         @Override
584         public void closeNow() {
585             close(voidPromise());
586         }
587 
588         @Override
589         public void connect(final SocketAddress remoteAddress,
590                 SocketAddress localAddress, final ChannelPromise promise) {
591             if (!promise.setUncancellable() || !ensureOpen(promise)) {
592                 return;
593             }
594 
595             if (state == State.CONNECTED) {
596                 Exception cause = new AlreadyConnectedException();
597                 safeSetFailure(promise, cause);
598                 return;
599             }
600 
601             if (connectPromise != null) {
602                 throw new ConnectionPendingException();
603             }
604 
605             connectPromise = promise;
606 
607             if (state != State.BOUND) {
608                 // Not bound yet and no localAddress specified - get one.
609                 if (localAddress == null) {
610                     localAddress = new LocalAddress(LocalChannel.this);
611                 }
612             }
613 
614             if (localAddress != null) {
615                 try {
616                     doBind(localAddress);
617                 } catch (Throwable t) {
618                     safeSetFailure(promise, t);
619                     close(voidPromise());
620                     return;
621                 }
622             }
623 
624             Channel boundChannel = LocalChannelRegistry.get(remoteAddress);
625             if (!(boundChannel instanceof LocalServerChannel)) {
626                 Exception cause = new ConnectException("connection refused: " + remoteAddress);
627                 safeSetFailure(promise, cause);
628                 close(voidPromise());
629                 return;
630             }
631 
632             LocalServerChannel serverChannel = (LocalServerChannel) boundChannel;
633             peer = serverChannel.serve(LocalChannel.this);
634         }
635     }
636 }