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.embedded;
17  
18  import io.netty.channel.AbstractChannel;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelConfig;
21  import io.netty.channel.ChannelFuture;
22  import io.netty.channel.ChannelFutureListener;
23  import io.netty.channel.ChannelHandler;
24  import io.netty.channel.ChannelHandlerContext;
25  import io.netty.channel.ChannelId;
26  import io.netty.channel.ChannelInitializer;
27  import io.netty.channel.ChannelMetadata;
28  import io.netty.channel.ChannelOutboundBuffer;
29  import io.netty.channel.ChannelPipeline;
30  import io.netty.channel.ChannelPromise;
31  import io.netty.channel.DefaultChannelConfig;
32  import io.netty.channel.DefaultChannelPipeline;
33  import io.netty.channel.EventLoop;
34  import io.netty.channel.RecvByteBufAllocator;
35  import io.netty.util.ReferenceCountUtil;
36  import io.netty.util.concurrent.Ticker;
37  import io.netty.util.internal.PlatformDependent;
38  import io.netty.util.internal.RecyclableArrayList;
39  import io.netty.util.internal.logging.InternalLogger;
40  import io.netty.util.internal.logging.InternalLoggerFactory;
41  
42  import java.net.SocketAddress;
43  import java.nio.channels.ClosedChannelException;
44  import java.util.ArrayDeque;
45  import java.util.Objects;
46  import java.util.Queue;
47  import java.util.concurrent.TimeUnit;
48  
49  /**
50   * Base class for {@link Channel} implementations that are used in an embedded fashion.
51   */
52  public class EmbeddedChannel extends AbstractChannel {
53  
54      private static final SocketAddress LOCAL_ADDRESS = new EmbeddedSocketAddress();
55      private static final SocketAddress REMOTE_ADDRESS = new EmbeddedSocketAddress();
56  
57      private static final ChannelHandler[] EMPTY_HANDLERS = new ChannelHandler[0];
58      private enum State { OPEN, ACTIVE, CLOSED }
59  
60      private static final InternalLogger logger = InternalLoggerFactory.getInstance(EmbeddedChannel.class);
61  
62      private static final ChannelMetadata METADATA_NO_DISCONNECT = new ChannelMetadata(false);
63      private static final ChannelMetadata METADATA_DISCONNECT = new ChannelMetadata(true);
64  
65      private final EmbeddedEventLoop loop;
66      private final ChannelFutureListener recordExceptionListener = this::recordException;
67  
68      private final ChannelMetadata metadata;
69      private final ChannelConfig config;
70  
71      private Queue<Object> inboundMessages;
72      private Queue<Object> outboundMessages;
73      private Throwable lastException;
74      private State state;
75      private int executingStackCnt;
76      private boolean cancelRemainingScheduledTasks;
77  
78      /**
79       * Create a new instance with an {@link EmbeddedChannelId} and an empty pipeline.
80       */
81      public EmbeddedChannel() {
82          this(builder());
83      }
84  
85      /**
86       * Create a new instance with the specified ID and an empty pipeline.
87       *
88       * @param channelId the {@link ChannelId} that will be used to identify this channel
89       */
90      public EmbeddedChannel(ChannelId channelId) {
91          this(builder().channelId(channelId));
92      }
93  
94      /**
95       * Create a new instance with the pipeline initialized with the specified handlers.
96       *
97       * @param handlers the {@link ChannelHandler}s which will be add in the {@link ChannelPipeline}
98       */
99      public EmbeddedChannel(ChannelHandler... handlers) {
100         this(builder().handlers(handlers));
101     }
102 
103     /**
104      * Create a new instance with the pipeline initialized with the specified handlers.
105      *
106      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
107      *                      to {@link #close()}, {@code true} otherwise.
108      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
109      */
110     public EmbeddedChannel(boolean hasDisconnect, ChannelHandler... handlers) {
111         this(builder().hasDisconnect(hasDisconnect).handlers(handlers));
112     }
113 
114     /**
115      * Create a new instance with the pipeline initialized with the specified handlers.
116      *
117      * @param register {@code true} if this {@link Channel} is registered to the {@link EventLoop} in the
118      *                 constructor. If {@code false} the user will need to call {@link #register()}.
119      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
120      *                      to {@link #close()}, {@code true} otherwise.
121      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
122      */
123     public EmbeddedChannel(boolean register, boolean hasDisconnect, ChannelHandler... handlers) {
124         this(builder().register(register).hasDisconnect(hasDisconnect).handlers(handlers));
125     }
126 
127     /**
128      * Create a new instance with the channel ID set to the given ID and the pipeline
129      * initialized with the specified handlers.
130      *
131      * @param channelId the {@link ChannelId} that will be used to identify this channel
132      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
133      */
134     public EmbeddedChannel(ChannelId channelId, ChannelHandler... handlers) {
135         this(builder().channelId(channelId).handlers(handlers));
136     }
137 
138     /**
139      * Create a new instance with the channel ID set to the given ID and the pipeline
140      * initialized with the specified handlers.
141      *
142      * @param channelId the {@link ChannelId} that will be used to identify this channel
143      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
144      *                      to {@link #close()}, {@code true} otherwise.
145      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
146      */
147     public EmbeddedChannel(ChannelId channelId, boolean hasDisconnect, ChannelHandler... handlers) {
148         this(builder().channelId(channelId).hasDisconnect(hasDisconnect).handlers(handlers));
149     }
150 
151     /**
152      * Create a new instance with the channel ID set to the given ID and the pipeline
153      * initialized with the specified handlers.
154      *
155      * @param channelId the {@link ChannelId} that will be used to identify this channel
156      * @param register {@code true} if this {@link Channel} is registered to the {@link EventLoop} in the
157      *                 constructor. If {@code false} the user will need to call {@link #register()}.
158      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
159      *                      to {@link #close()}, {@code true} otherwise.
160      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
161      */
162     public EmbeddedChannel(ChannelId channelId, boolean register, boolean hasDisconnect,
163                            ChannelHandler... handlers) {
164         this(builder().channelId(channelId).register(register).hasDisconnect(hasDisconnect).handlers(handlers));
165     }
166 
167     /**
168      * Create a new instance with the channel ID set to the given ID and the pipeline
169      * initialized with the specified handlers.
170      *
171      * @param parent    the parent {@link Channel} of this {@link EmbeddedChannel}.
172      * @param channelId the {@link ChannelId} that will be used to identify this channel
173      * @param register {@code true} if this {@link Channel} is registered to the {@link EventLoop} in the
174      *                 constructor. If {@code false} the user will need to call {@link #register()}.
175      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
176      *                      to {@link #close()}, {@code true} otherwise.
177      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
178      */
179     public EmbeddedChannel(Channel parent, ChannelId channelId, boolean register, boolean hasDisconnect,
180                            final ChannelHandler... handlers) {
181         this(builder()
182                 .parent(parent)
183                 .channelId(channelId)
184                 .register(register)
185                 .hasDisconnect(hasDisconnect)
186                 .handlers(handlers));
187     }
188 
189     /**
190      * Create a new instance with the channel ID set to the given ID and the pipeline
191      * initialized with the specified handlers.
192      *
193      * @param channelId the {@link ChannelId} that will be used to identify this channel
194      * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()}
195      *                      to {@link #close()}, {@code true} otherwise.
196      * @param config the {@link ChannelConfig} which will be returned by {@link #config()}.
197      * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
198      */
199     public EmbeddedChannel(ChannelId channelId, boolean hasDisconnect, final ChannelConfig config,
200                            final ChannelHandler... handlers) {
201         this(builder().channelId(channelId).hasDisconnect(hasDisconnect).config(config).handlers(handlers));
202     }
203 
204     /**
205      * Create a new instance with the configuration from the given builder. This method is {@code protected} for use by
206      * subclasses; Otherwise, please use {@link Builder#build()}.
207      *
208      * @param builder The builder
209      */
210     protected EmbeddedChannel(Builder builder) {
211         super(builder.parent, builder.channelId);
212         loop = new EmbeddedEventLoop(builder.ticker == null ? new EmbeddedEventLoop.FreezableTicker() : builder.ticker);
213         metadata = metadata(builder.hasDisconnect);
214         config = builder.config == null ? new DefaultChannelConfig(this) : builder.config;
215         if (builder.handler == null) {
216             setup(builder.register, builder.handlers);
217         } else {
218             setup(builder.register, builder.handler);
219         }
220     }
221 
222     private static ChannelMetadata metadata(boolean hasDisconnect) {
223         return hasDisconnect ? METADATA_DISCONNECT : METADATA_NO_DISCONNECT;
224     }
225 
226     private void setup(boolean register, final ChannelHandler... handlers) {
227         ChannelPipeline p = pipeline();
228         p.addLast(new ChannelInitializer<Channel>() {
229             @Override
230             protected void initChannel(Channel ch) {
231                 ChannelPipeline pipeline = ch.pipeline();
232                 for (ChannelHandler h: handlers) {
233                     if (h == null) {
234                         break;
235                     }
236                     pipeline.addLast(h);
237                 }
238             }
239         });
240         if (register) {
241             ChannelFuture future = loop.register(this);
242             assert future.isDone();
243         }
244     }
245 
246     private void setup(boolean register, final ChannelHandler handler) {
247         ChannelPipeline p = pipeline();
248         p.addLast(handler);
249         if (register) {
250             ChannelFuture future = loop.register(this);
251             assert future.isDone();
252         }
253     }
254 
255     /**
256      * Register this {@code Channel} on its {@link EventLoop}.
257      */
258     public void register() throws Exception {
259         ChannelFuture future = loop.register(this);
260         assert future.isDone();
261         Throwable cause = future.cause();
262         if (cause != null) {
263             PlatformDependent.throwException(cause);
264         }
265     }
266 
267     @Override
268     protected final DefaultChannelPipeline newChannelPipeline() {
269         return new EmbeddedChannelPipeline(this);
270     }
271 
272     @Override
273     public ChannelMetadata metadata() {
274         return metadata;
275     }
276 
277     @Override
278     public ChannelConfig config() {
279         return config;
280     }
281 
282     @Override
283     public boolean isOpen() {
284         return state != State.CLOSED;
285     }
286 
287     @Override
288     public boolean isActive() {
289         return state == State.ACTIVE;
290     }
291 
292     /**
293      * Returns the {@link Queue} which holds all the {@link Object}s that were received by this {@link Channel}.
294      */
295     public Queue<Object> inboundMessages() {
296         if (inboundMessages == null) {
297             inboundMessages = new ArrayDeque<Object>();
298         }
299         return inboundMessages;
300     }
301 
302     /**
303      * @deprecated use {@link #inboundMessages()}
304      */
305     @Deprecated
306     public Queue<Object> lastInboundBuffer() {
307         return inboundMessages();
308     }
309 
310     /**
311      * Returns the {@link Queue} which holds all the {@link Object}s that were written by this {@link Channel}.
312      */
313     public Queue<Object> outboundMessages() {
314         if (outboundMessages == null) {
315             outboundMessages = new ArrayDeque<Object>();
316         }
317         return outboundMessages;
318     }
319 
320     /**
321      * @deprecated use {@link #outboundMessages()}
322      */
323     @Deprecated
324     public Queue<Object> lastOutboundBuffer() {
325         return outboundMessages();
326     }
327 
328     /**
329      * Return received data from this {@link Channel}
330      */
331     @SuppressWarnings("unchecked")
332     public <T> T readInbound() {
333         T message = (T) poll(inboundMessages);
334         if (message != null) {
335             ReferenceCountUtil.touch(message, "Caller of readInbound() will handle the message from this point");
336         }
337         return message;
338     }
339 
340     /**
341      * Read data from the outbound. This may return {@code null} if nothing is readable.
342      */
343     @SuppressWarnings("unchecked")
344     public <T> T readOutbound() {
345         T message =  (T) poll(outboundMessages);
346         if (message != null) {
347             ReferenceCountUtil.touch(message, "Caller of readOutbound() will handle the message from this point.");
348         }
349         return message;
350     }
351 
352     /**
353      * Write messages to the inbound of this {@link Channel}.
354      * <p>
355      * If this {@link Channel} is already closed, the messages are released and a
356      * {@link ClosedChannelException} is thrown.
357      *
358      * @param msgs the messages to be written
359      *
360      * @return {@code true} if the write operation did add something to the inbound buffer
361      */
362     public boolean writeInbound(Object... msgs) {
363         ensureOpen(msgs);
364         if (msgs.length == 0) {
365             return isNotEmpty(inboundMessages);
366         }
367 
368         executingStackCnt++;
369         try {
370             ChannelPipeline p = pipeline();
371             for (Object m : msgs) {
372                 p.fireChannelRead(m);
373             }
374 
375             flushInbound(false, voidPromise());
376         } finally {
377             executingStackCnt--;
378             maybeRunPendingTasks();
379         }
380         return isNotEmpty(inboundMessages);
381     }
382 
383     /**
384      * Writes one message to the inbound of this {@link Channel} and does not flush it. This
385      * method is conceptually equivalent to {@link #write(Object)}.
386      * <p>
387      * If this {@link Channel} is already closed, the message is released and the returned future is failed with a
388      * {@link ClosedChannelException}.
389      *
390      * @see #writeOneOutbound(Object)
391      */
392     public ChannelFuture writeOneInbound(Object msg) {
393         return writeOneInbound(msg, newPromise());
394     }
395 
396     /**
397      * Writes one message to the inbound of this {@link Channel} and does not flush it. This
398      * method is conceptually equivalent to {@link #write(Object, ChannelPromise)}.
399      * <p>
400      * If this {@link Channel} is already closed, the message is released and the promise is failed with a
401      * {@link ClosedChannelException} (thrown instead if the promise is a void promise).
402      *
403      * @see #writeOneOutbound(Object, ChannelPromise)
404      */
405     public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) {
406         executingStackCnt++;
407         try {
408             if (checkOpen(true)) {
409                 pipeline().fireChannelRead(msg);
410             } else {
411                 // The message never reached the pipeline, so nobody else will release it.
412                 ReferenceCountUtil.safeRelease(msg);
413             }
414         } finally {
415             executingStackCnt--;
416             maybeRunPendingTasks();
417         }
418         return checkException(promise);
419     }
420 
421     /**
422      * Flushes the inbound of this {@link Channel}. This method is conceptually equivalent to {@link #flush()}.
423      *
424      * @see #flushOutbound()
425      */
426     public EmbeddedChannel flushInbound() {
427         flushInbound(true, voidPromise());
428         return this;
429     }
430 
431     private ChannelFuture flushInbound(boolean recordException, ChannelPromise promise) {
432         executingStackCnt++;
433         try {
434             if (checkOpen(recordException)) {
435                 pipeline().fireChannelReadComplete();
436                 runPendingTasks();
437             }
438         } finally {
439             executingStackCnt--;
440             maybeRunPendingTasks();
441         }
442 
443       return checkException(promise);
444     }
445 
446     /**
447      * Write messages to the outbound of this {@link Channel}.
448      * <p>
449      * If this {@link Channel} is already closed, the messages are released and a
450      * {@link ClosedChannelException} is thrown.
451      *
452      * @param msgs              the messages to be written
453      * @return bufferReadable   returns {@code true} if the write operation did add something to the outbound buffer
454      */
455     public boolean writeOutbound(Object... msgs) {
456         ensureOpen(msgs);
457         if (msgs.length == 0) {
458             return isNotEmpty(outboundMessages);
459         }
460 
461         executingStackCnt++;
462         RecyclableArrayList futures = RecyclableArrayList.newInstance(msgs.length);
463         try {
464             try {
465                 for (Object m : msgs) {
466                     if (m == null) {
467                         break;
468                     }
469                     futures.add(write(m));
470                 }
471 
472                 flushOutbound0();
473 
474                 int size = futures.size();
475                 for (int i = 0; i < size; i++) {
476                     ChannelFuture future = (ChannelFuture) futures.get(i);
477                     if (future.isDone()) {
478                         recordException(future);
479                     } else {
480                         // The write may be delayed to run later by runPendingTasks()
481                         future.addListener(recordExceptionListener);
482                     }
483                 }
484             } finally {
485                 executingStackCnt--;
486                 maybeRunPendingTasks();
487             }
488             checkException();
489             return isNotEmpty(outboundMessages);
490         } finally {
491             futures.recycle();
492         }
493     }
494 
495     /**
496      * Writes one message to the outbound of this {@link Channel} and does not flush it. This
497      * method is conceptually equivalent to {@link #write(Object)}.
498      * <p>
499      * If this {@link Channel} is already closed, the message is released and the returned future is failed with a
500      * {@link ClosedChannelException}.
501      *
502      * @see #writeOneInbound(Object)
503      */
504     public ChannelFuture writeOneOutbound(Object msg) {
505         return writeOneOutbound(msg, newPromise());
506     }
507 
508     /**
509      * Writes one message to the outbound of this {@link Channel} and does not flush it. This
510      * method is conceptually equivalent to {@link #write(Object, ChannelPromise)}.
511      * <p>
512      * If this {@link Channel} is already closed, the message is released and the promise is failed with a
513      * {@link ClosedChannelException} (thrown instead if the promise is a void promise).
514      *
515      * @see #writeOneInbound(Object, ChannelPromise)
516      */
517     public ChannelFuture writeOneOutbound(Object msg, ChannelPromise promise) {
518         executingStackCnt++;
519         try {
520             if (checkOpen(true)) {
521                 return write(msg, promise);
522             }
523             // The message never reached the pipeline, so nobody else will release it.
524             ReferenceCountUtil.safeRelease(msg);
525         } finally {
526             executingStackCnt--;
527             maybeRunPendingTasks();
528         }
529 
530         return checkException(promise);
531     }
532 
533     /**
534      * Flushes the outbound of this {@link Channel}. This method is conceptually equivalent to {@link #flush()}.
535      *
536      * @see #flushInbound()
537      */
538     public EmbeddedChannel flushOutbound() {
539         executingStackCnt++;
540         try {
541             if (checkOpen(true)) {
542                 flushOutbound0();
543             }
544         } finally {
545             executingStackCnt--;
546             maybeRunPendingTasks();
547         }
548         checkException(voidPromise());
549         return this;
550     }
551 
552     private void flushOutbound0() {
553         // We need to call runPendingTasks first as a ChannelOutboundHandler may used eventloop.execute(...) to
554         // delay the write on the next eventloop run.
555         runPendingTasks();
556 
557         flush();
558     }
559 
560     /**
561      * Mark this {@link Channel} as finished. Any further try to write data to it will fail.
562      *
563      * @return bufferReadable returns {@code true} if any of the used buffers has something left to read
564      */
565     public boolean finish() {
566         return finish(false);
567     }
568 
569     /**
570      * Mark this {@link Channel} as finished and release all pending message in the inbound and outbound buffer.
571      * Any further try to write data to it will fail.
572      *
573      * @return bufferReadable returns {@code true} if any of the used buffers has something left to read
574      */
575     public boolean finishAndReleaseAll() {
576         return finish(true);
577     }
578 
579     /**
580      * Mark this {@link Channel} as finished. Any further try to write data to it will fail.
581      *
582      * @param releaseAll if {@code true} all pending message in the inbound and outbound buffer are released.
583      * @return bufferReadable returns {@code true} if any of the used buffers has something left to read
584      */
585     private boolean finish(boolean releaseAll) {
586         executingStackCnt++;
587         try {
588             close();
589         } finally {
590             executingStackCnt--;
591             maybeRunPendingTasks();
592         }
593         try {
594             checkException();
595             return isNotEmpty(inboundMessages) || isNotEmpty(outboundMessages);
596         } finally {
597             if (releaseAll) {
598                 releaseAll(inboundMessages);
599                 releaseAll(outboundMessages);
600             }
601         }
602     }
603 
604     /**
605      * Release all buffered inbound messages and return {@code true} if any were in the inbound buffer, {@code false}
606      * otherwise.
607      */
608     public boolean releaseInbound() {
609         return releaseAll(inboundMessages);
610     }
611 
612     /**
613      * Release all buffered outbound messages and return {@code true} if any were in the outbound buffer, {@code false}
614      * otherwise.
615      */
616     public boolean releaseOutbound() {
617         return releaseAll(outboundMessages);
618     }
619 
620     private static boolean releaseAll(Queue<Object> queue) {
621         if (isNotEmpty(queue)) {
622             for (;;) {
623                 Object msg = queue.poll();
624                 if (msg == null) {
625                     break;
626                 }
627                 ReferenceCountUtil.release(msg);
628             }
629             return true;
630         }
631         return false;
632     }
633 
634     @Override
635     public final ChannelFuture close() {
636         return close(newPromise());
637     }
638 
639     @Override
640     public final ChannelFuture disconnect() {
641         return disconnect(newPromise());
642     }
643 
644     @Override
645     public final ChannelFuture close(ChannelPromise promise) {
646         // We need to call runPendingTasks() before calling super.close() as there may be something in the queue
647         // that needs to be run before the actual close takes place.
648         executingStackCnt++;
649         ChannelFuture future;
650         try {
651             runPendingTasks();
652             future = super.close(promise);
653 
654             cancelRemainingScheduledTasks = true;
655         } finally {
656             executingStackCnt--;
657             maybeRunPendingTasks();
658         }
659         return future;
660     }
661 
662     @Override
663     public final ChannelFuture disconnect(ChannelPromise promise) {
664         executingStackCnt++;
665         ChannelFuture future;
666         try {
667             future = super.disconnect(promise);
668 
669             if (!metadata.hasDisconnect()) {
670                 cancelRemainingScheduledTasks = true;
671             }
672         } finally {
673             executingStackCnt--;
674             maybeRunPendingTasks();
675         }
676         return future;
677     }
678 
679     @Override
680     public ChannelFuture bind(SocketAddress localAddress) {
681         executingStackCnt++;
682         try {
683             return super.bind(localAddress);
684         } finally {
685             executingStackCnt--;
686             maybeRunPendingTasks();
687         }
688     }
689 
690     @Override
691     public ChannelFuture connect(SocketAddress remoteAddress) {
692         executingStackCnt++;
693         try {
694             return super.connect(remoteAddress);
695         } finally {
696             executingStackCnt--;
697             maybeRunPendingTasks();
698         }
699     }
700 
701     @Override
702     public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
703         executingStackCnt++;
704         try {
705             return super.connect(remoteAddress, localAddress);
706         } finally {
707             executingStackCnt--;
708             maybeRunPendingTasks();
709         }
710     }
711 
712     @Override
713     public ChannelFuture deregister() {
714         executingStackCnt++;
715         try {
716             return super.deregister();
717         } finally {
718             executingStackCnt--;
719             maybeRunPendingTasks();
720         }
721     }
722 
723     @Override
724     public Channel flush() {
725         executingStackCnt++;
726         try {
727             return super.flush();
728         } finally {
729             executingStackCnt--;
730             maybeRunPendingTasks();
731         }
732     }
733 
734     @Override
735     public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
736         executingStackCnt++;
737         try {
738             return super.bind(localAddress, promise);
739         } finally {
740             executingStackCnt--;
741             maybeRunPendingTasks();
742         }
743     }
744 
745     @Override
746     public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
747         executingStackCnt++;
748         try {
749             return super.connect(remoteAddress, promise);
750         } finally {
751             executingStackCnt--;
752             maybeRunPendingTasks();
753         }
754     }
755 
756     @Override
757     public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
758         executingStackCnt++;
759         try {
760             return super.connect(remoteAddress, localAddress, promise);
761         } finally {
762             executingStackCnt--;
763             maybeRunPendingTasks();
764         }
765     }
766 
767     @Override
768     public ChannelFuture deregister(ChannelPromise promise) {
769         executingStackCnt++;
770         try {
771             return super.deregister(promise);
772         } finally {
773             executingStackCnt--;
774             maybeRunPendingTasks();
775         }
776     }
777 
778     @Override
779     public Channel read() {
780         executingStackCnt++;
781         try {
782             return super.read();
783         } finally {
784             executingStackCnt--;
785             maybeRunPendingTasks();
786         }
787     }
788 
789     @Override
790     public ChannelFuture write(Object msg) {
791         executingStackCnt++;
792         try {
793             return super.write(msg);
794         } finally {
795             executingStackCnt--;
796             maybeRunPendingTasks();
797         }
798     }
799 
800     @Override
801     public ChannelFuture write(Object msg, ChannelPromise promise) {
802         executingStackCnt++;
803         try {
804             return super.write(msg, promise);
805         } finally {
806             executingStackCnt--;
807             maybeRunPendingTasks();
808         }
809     }
810 
811     @Override
812     public ChannelFuture writeAndFlush(Object msg) {
813         executingStackCnt++;
814         try {
815             return super.writeAndFlush(msg);
816         } finally {
817             executingStackCnt--;
818             maybeRunPendingTasks();
819         }
820     }
821 
822     @Override
823     public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
824         executingStackCnt++;
825         try {
826             return super.writeAndFlush(msg, promise);
827         } finally {
828             executingStackCnt--;
829             maybeRunPendingTasks();
830         }
831     }
832 
833     private static boolean isNotEmpty(Queue<Object> queue) {
834         return queue != null && !queue.isEmpty();
835     }
836 
837     private static Object poll(Queue<Object> queue) {
838         return queue != null ? queue.poll() : null;
839     }
840 
841     private void maybeRunPendingTasks() {
842         if (executingStackCnt == 0) {
843             runPendingTasks();
844 
845             if (cancelRemainingScheduledTasks) {
846                 // Cancel all scheduled tasks that are left.
847                 embeddedEventLoop().cancelScheduledTasks();
848             }
849         }
850     }
851 
852     /**
853      * Run all tasks (which also includes scheduled tasks) that are pending in the {@link EventLoop}
854      * for this {@link Channel}
855      */
856     public void runPendingTasks() {
857         try {
858             embeddedEventLoop().runTasks();
859         } catch (Exception e) {
860             recordException(e);
861         }
862 
863         try {
864             embeddedEventLoop().runScheduledTasks();
865         } catch (Exception e) {
866             recordException(e);
867         }
868     }
869 
870     /**
871      * Check whether this channel has any pending tasks that would be executed by a call to {@link #runPendingTasks()}.
872      * This includes normal tasks, and scheduled tasks where the deadline has expired. If this method returns
873      * {@code false}, a call to {@link #runPendingTasks()} would do nothing.
874      *
875      * @return {@code true} if there are any pending tasks, {@code false} otherwise.
876      */
877     public boolean hasPendingTasks() {
878         return embeddedEventLoop().hasPendingNormalTasks() ||
879                 embeddedEventLoop().nextScheduledTask() == 0;
880     }
881 
882     /**
883      * Run all pending scheduled tasks in the {@link EventLoop} for this {@link Channel} and return the
884      * {@code nanoseconds} when the next scheduled task is ready to run. If no other task was scheduled it will return
885      * {@code -1}.
886      */
887     public long runScheduledPendingTasks() {
888         try {
889             return embeddedEventLoop().runScheduledTasks();
890         } catch (Exception e) {
891             recordException(e);
892             return embeddedEventLoop().nextScheduledTask();
893         }
894     }
895 
896     private void recordException(ChannelFuture future) {
897         if (!future.isSuccess()) {
898             recordException(future.cause());
899         }
900     }
901 
902     private void recordException(Throwable cause) {
903         if (lastException == null) {
904             lastException = cause;
905         } else {
906             logger.warn(
907                     "More than one exception was raised. " +
908                             "Will report only the first one and log others.", cause);
909         }
910     }
911 
912     private EmbeddedEventLoop.FreezableTicker freezableTicker() {
913         Ticker ticker = eventLoop().ticker();
914         if (ticker instanceof EmbeddedEventLoop.FreezableTicker) {
915             return (EmbeddedEventLoop.FreezableTicker) ticker;
916         } else {
917             throw new IllegalStateException(
918                     "EmbeddedChannel constructed with custom ticker, time manipulation methods are unavailable.");
919         }
920     }
921 
922     /**
923      * Advance the clock of the event loop of this channel by the given duration. Any scheduled tasks will execute
924      * sooner by the given time (but {@link #runScheduledPendingTasks()} still needs to be called).
925      */
926     public void advanceTimeBy(long duration, TimeUnit unit) {
927         freezableTicker().advance(duration, unit);
928     }
929 
930     /**
931      * Freeze the clock of this channel's event loop. Any scheduled tasks that are not already due will not run on
932      * future {@link #runScheduledPendingTasks()} calls. While the event loop is frozen, it is still possible to
933      * {@link #advanceTimeBy(long, TimeUnit) advance time} manually so that scheduled tasks execute.
934      */
935     public void freezeTime() {
936         freezableTicker().freezeTime();
937     }
938 
939     /**
940      * Unfreeze an event loop that was {@link #freezeTime() frozen}. Time will continue at the point where
941      * {@link #freezeTime()} stopped it: if a task was scheduled ten minutes in the future and {@link #freezeTime()}
942      * was called, it will run ten minutes after this method is called again (assuming no
943      * {@link #advanceTimeBy(long, TimeUnit)} calls, and assuming pending scheduled tasks are run at that time using
944      * {@link #runScheduledPendingTasks()}).
945      */
946     public void unfreezeTime() {
947         freezableTicker().unfreezeTime();
948     }
949 
950     /**
951      * Checks for the presence of an {@link Exception}.
952      */
953     private ChannelFuture checkException(ChannelPromise promise) {
954       Throwable t = lastException;
955       if (t != null) {
956         lastException = null;
957 
958         if (promise.isVoid()) {
959             PlatformDependent.throwException(t);
960         }
961 
962         return promise.setFailure(t);
963       }
964 
965       return promise.setSuccess();
966     }
967 
968     /**
969      * Check if there was any {@link Throwable} received and if so rethrow it.
970      */
971     public void checkException() {
972       checkException(voidPromise());
973     }
974 
975     /**
976      * Returns {@code true} if the {@link Channel} is open and records optionally
977      * an {@link Exception} if it isn't.
978      */
979     private boolean checkOpen(boolean recordException) {
980         if (!isOpen()) {
981           if (recordException) {
982               recordException(new ClosedChannelException());
983           }
984           return false;
985       }
986 
987       return true;
988     }
989 
990     private EmbeddedEventLoop embeddedEventLoop() {
991         if (isRegistered()) {
992             return (EmbeddedEventLoop) super.eventLoop();
993         }
994 
995         return loop;
996     }
997 
998     /**
999      * Ensure the {@link Channel} is open and if not release the given messages, which never reached the pipeline,
1000      * and throw an exception.
1001      */
1002     private void ensureOpen(Object[] msgs) {
1003         if (!checkOpen(true)) {
1004             for (Object msg : msgs) {
1005                 ReferenceCountUtil.safeRelease(msg);
1006             }
1007             checkException();
1008         }
1009     }
1010 
1011     /**
1012      * Ensure the {@link Channel} is open and if not throw an exception.
1013      */
1014     protected final void ensureOpen() {
1015         if (!checkOpen(true)) {
1016             checkException();
1017         }
1018     }
1019 
1020     @Override
1021     protected boolean isCompatible(EventLoop loop) {
1022         return loop instanceof EmbeddedEventLoop;
1023     }
1024 
1025     @Override
1026     protected SocketAddress localAddress0() {
1027         return isActive()? LOCAL_ADDRESS : null;
1028     }
1029 
1030     @Override
1031     protected SocketAddress remoteAddress0() {
1032         return isActive()? REMOTE_ADDRESS : null;
1033     }
1034 
1035     @Override
1036     protected void doRegister() throws Exception {
1037         state = State.ACTIVE;
1038     }
1039 
1040     @Override
1041     protected void doBind(SocketAddress localAddress) throws Exception {
1042         // NOOP
1043     }
1044 
1045     @Override
1046     protected void doDisconnect() throws Exception {
1047         if (!metadata.hasDisconnect()) {
1048             doClose();
1049         }
1050     }
1051 
1052     @Override
1053     protected void doClose() throws Exception {
1054         state = State.CLOSED;
1055     }
1056 
1057     @Override
1058     protected void doBeginRead() throws Exception {
1059         // NOOP
1060     }
1061 
1062     @Override
1063     protected AbstractUnsafe newUnsafe() {
1064         return new EmbeddedUnsafe();
1065     }
1066 
1067     @Override
1068     public Unsafe unsafe() {
1069         return ((EmbeddedUnsafe) super.unsafe()).wrapped;
1070     }
1071 
1072     @Override
1073     protected void doWrite(ChannelOutboundBuffer in) throws Exception {
1074         for (;;) {
1075             Object msg = in.current();
1076             if (msg == null) {
1077                 break;
1078             }
1079 
1080             ReferenceCountUtil.retain(msg);
1081             handleOutboundMessage(msg);
1082             in.remove();
1083         }
1084     }
1085 
1086     /**
1087      * Called for each outbound message.
1088      *
1089      * @see #doWrite(ChannelOutboundBuffer)
1090      */
1091     protected void handleOutboundMessage(Object msg) {
1092         outboundMessages().add(msg);
1093     }
1094 
1095     /**
1096      * Called for each inbound message.
1097      */
1098     protected void handleInboundMessage(Object msg) {
1099         inboundMessages().add(msg);
1100     }
1101 
1102     public static Builder builder() {
1103         return new Builder();
1104     }
1105 
1106     public static final class Builder {
1107         Channel parent;
1108         ChannelId channelId = EmbeddedChannelId.INSTANCE;
1109         boolean register = true;
1110         boolean hasDisconnect;
1111         //you should use either handlers or handler variable, but not both.
1112         ChannelHandler[] handlers = EMPTY_HANDLERS;
1113         ChannelHandler handler;
1114         ChannelConfig config;
1115         Ticker ticker;
1116 
1117         private Builder() {
1118         }
1119 
1120         /**
1121          * The parent {@link Channel} of this {@link EmbeddedChannel}.
1122          *
1123          * @param parent the parent {@link Channel} of this {@link EmbeddedChannel}.
1124          * @return This builder
1125          */
1126         public Builder parent(Channel parent) {
1127             this.parent = parent;
1128             return this;
1129         }
1130 
1131         /**
1132          * The {@link ChannelId} that will be used to identify this channel.
1133          *
1134          * @param channelId the {@link ChannelId} that will be used to identify this channel
1135          * @return This builder
1136          */
1137         public Builder channelId(ChannelId channelId) {
1138             this.channelId = Objects.requireNonNull(channelId, "channelId");
1139             return this;
1140         }
1141 
1142         /**
1143          * {@code true} if this {@link Channel} is registered to the {@link EventLoop} in the constructor. If
1144          * {@code false} the user will need to call {@link #register()}.
1145          *
1146          * @param register {@code true} if this {@link Channel} is registered to the {@link EventLoop} in the
1147          *                 constructor. If {@code false} the user will need to call {@link #register()}.
1148          * @return This builder
1149          */
1150         public Builder register(boolean register) {
1151             this.register = register;
1152             return this;
1153         }
1154 
1155         /**
1156          * {@code false} if this {@link Channel} will delegate {@link #disconnect()} to {@link #close()}, {@code true}
1157          * otherwise.
1158          *
1159          * @param hasDisconnect {@code false} if this {@link Channel} will delegate {@link #disconnect()} to
1160          *                      {@link #close()}, {@code true} otherwise
1161          * @return This builder
1162          */
1163         public Builder hasDisconnect(boolean hasDisconnect) {
1164             this.hasDisconnect = hasDisconnect;
1165             return this;
1166         }
1167 
1168         /**
1169          * The {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}.
1170          *
1171          * @param handlers the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
1172          * @return This builder
1173          */
1174         public Builder handlers(ChannelHandler... handlers) {
1175             this.handlers = Objects.requireNonNull(handlers, "handlers");
1176             this.handler = null;
1177             return this;
1178         }
1179 
1180         /**
1181          * The {@link ChannelHandler} which will be added to the {@link ChannelPipeline}.
1182          *
1183          * @param handler the {@link ChannelHandler}s which will be added to the {@link ChannelPipeline}
1184          * @return This builder
1185          */
1186         public Builder handlers(ChannelHandler handler) {
1187             this.handler = Objects.requireNonNull(handler, "handler");
1188             this.handlers = null;
1189             return this;
1190         }
1191 
1192         /**
1193          * The {@link ChannelConfig} which will be returned by {@link #config()}.
1194          *
1195          * @param config the {@link ChannelConfig} which will be returned by {@link #config()}
1196          * @return This builder
1197          */
1198         public Builder config(ChannelConfig config) {
1199             this.config = Objects.requireNonNull(config, "config");
1200             return this;
1201         }
1202 
1203         /**
1204          * Configure a custom ticker for this event loop.
1205          *
1206          * @param ticker The custom ticker
1207          * @return This builder
1208          */
1209         public Builder ticker(Ticker ticker) {
1210             this.ticker = ticker;
1211             return this;
1212         }
1213 
1214         /**
1215          * Create the channel. If you wish to extend {@link EmbeddedChannel}, please use the
1216          * {@link #EmbeddedChannel(Builder)} constructor instead.
1217          *
1218          * @return The channel
1219          */
1220         public EmbeddedChannel build() {
1221             return new EmbeddedChannel(this);
1222         }
1223     }
1224 
1225     private final class EmbeddedUnsafe extends AbstractUnsafe {
1226 
1227         // Delegates to the EmbeddedUnsafe instance but ensures runPendingTasks() is called after each operation
1228         // that may change the state of the Channel and may schedule tasks for later execution.
1229         final Unsafe wrapped = new Unsafe() {
1230             @Override
1231             public RecvByteBufAllocator.Handle recvBufAllocHandle() {
1232                 return EmbeddedUnsafe.this.recvBufAllocHandle();
1233             }
1234 
1235             @Override
1236             public SocketAddress localAddress() {
1237                 return EmbeddedUnsafe.this.localAddress();
1238             }
1239 
1240             @Override
1241             public SocketAddress remoteAddress() {
1242                 return EmbeddedUnsafe.this.remoteAddress();
1243             }
1244 
1245             @Override
1246             public void register(EventLoop eventLoop, ChannelPromise promise) {
1247                 executingStackCnt++;
1248                 try {
1249                     EmbeddedUnsafe.this.register(eventLoop, promise);
1250                 } finally {
1251                     executingStackCnt--;
1252                     maybeRunPendingTasks();
1253                 }
1254             }
1255 
1256             @Override
1257             public void bind(SocketAddress localAddress, ChannelPromise promise) {
1258                 executingStackCnt++;
1259                 try {
1260                     EmbeddedUnsafe.this.bind(localAddress, promise);
1261                 } finally {
1262                     executingStackCnt--;
1263                     maybeRunPendingTasks();
1264                 }
1265             }
1266 
1267             @Override
1268             public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
1269                 executingStackCnt++;
1270                 try {
1271                     EmbeddedUnsafe.this.connect(remoteAddress, localAddress, promise);
1272                 } finally {
1273                     executingStackCnt--;
1274                     maybeRunPendingTasks();
1275                 }
1276             }
1277 
1278             @Override
1279             public void disconnect(ChannelPromise promise) {
1280                 executingStackCnt++;
1281                 try {
1282                     EmbeddedUnsafe.this.disconnect(promise);
1283                 } finally {
1284                     executingStackCnt--;
1285                     maybeRunPendingTasks();
1286                 }
1287             }
1288 
1289             @Override
1290             public void close(ChannelPromise promise) {
1291                 executingStackCnt++;
1292                 try {
1293                     EmbeddedUnsafe.this.close(promise);
1294                 } finally {
1295                     executingStackCnt--;
1296                     maybeRunPendingTasks();
1297                 }
1298             }
1299 
1300             @Override
1301             public void closeForcibly() {
1302                 executingStackCnt++;
1303                 try {
1304                     EmbeddedUnsafe.this.closeForcibly();
1305                 } finally {
1306                     executingStackCnt--;
1307                     maybeRunPendingTasks();
1308                 }
1309             }
1310 
1311             @Override
1312             public void deregister(ChannelPromise promise) {
1313                 executingStackCnt++;
1314                 try {
1315                     EmbeddedUnsafe.this.deregister(promise);
1316                 } finally {
1317                     executingStackCnt--;
1318                     maybeRunPendingTasks();
1319                 }
1320             }
1321 
1322             @Override
1323             public void beginRead() {
1324                 executingStackCnt++;
1325                 try {
1326                     EmbeddedUnsafe.this.beginRead();
1327                 } finally {
1328                     executingStackCnt--;
1329                     maybeRunPendingTasks();
1330                 }
1331             }
1332 
1333             @Override
1334             public void write(Object msg, ChannelPromise promise) {
1335                 executingStackCnt++;
1336                 try {
1337                     EmbeddedUnsafe.this.write(msg, promise);
1338                 } finally {
1339                     executingStackCnt--;
1340                     maybeRunPendingTasks();
1341                 }
1342             }
1343 
1344             @Override
1345             public void flush() {
1346                 executingStackCnt++;
1347                 try {
1348                     EmbeddedUnsafe.this.flush();
1349                 } finally {
1350                     executingStackCnt--;
1351                     maybeRunPendingTasks();
1352                 }
1353             }
1354 
1355             @Override
1356             public ChannelPromise voidPromise() {
1357                 return EmbeddedUnsafe.this.voidPromise();
1358             }
1359 
1360             @Override
1361             public ChannelOutboundBuffer outboundBuffer() {
1362                 return EmbeddedUnsafe.this.outboundBuffer();
1363             }
1364         };
1365 
1366         @Override
1367         public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
1368             safeSetSuccess(promise);
1369         }
1370     }
1371 
1372     private final class EmbeddedChannelPipeline extends DefaultChannelPipeline {
1373         EmbeddedChannelPipeline(EmbeddedChannel channel) {
1374             super(channel);
1375         }
1376 
1377         @Override
1378         protected void onUnhandledInboundException(Throwable cause) {
1379             recordException(cause);
1380         }
1381 
1382         @Override
1383         protected void onUnhandledInboundMessage(ChannelHandlerContext ctx, Object msg) {
1384             handleInboundMessage(msg);
1385         }
1386     }
1387 }