View Javadoc
1   /*
2    * Copyright 2019 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.testsuite.transport;
17  
18  import io.netty.bootstrap.ServerBootstrap;
19  import io.netty.channel.Channel;
20  import io.netty.channel.ChannelFuture;
21  import io.netty.channel.ChannelInboundHandlerAdapter;
22  import io.netty.channel.EventLoop;
23  import io.netty.channel.EventLoopGroup;
24  import io.netty.channel.ServerChannel;
25  import io.netty.channel.SingleThreadEventLoop;
26  import io.netty.channel.local.LocalAddress;
27  import io.netty.channel.local.LocalServerChannel;
28  import io.netty.util.concurrent.EventExecutor;
29  import io.netty.util.concurrent.Future;
30  import io.netty.util.concurrent.Promise;
31  import io.netty.util.concurrent.ScheduledFuture;
32  import io.netty.util.internal.PlatformDependent;
33  import org.junit.jupiter.api.Test;
34  import org.junit.jupiter.api.Timeout;
35  import org.junit.jupiter.api.function.Executable;
36  
37  import java.util.ArrayList;
38  import java.util.HashSet;
39  import java.util.Iterator;
40  import java.util.List;
41  import java.util.NoSuchElementException;
42  import java.util.Set;
43  import java.util.concurrent.Callable;
44  import java.util.concurrent.CountDownLatch;
45  import java.util.concurrent.RejectedExecutionException;
46  import java.util.concurrent.TimeUnit;
47  
48  import static java.util.concurrent.TimeUnit.MILLISECONDS;
49  import static org.junit.jupiter.api.Assertions.assertEquals;
50  import static org.junit.jupiter.api.Assertions.assertFalse;
51  import static org.junit.jupiter.api.Assertions.assertNotNull;
52  import static org.junit.jupiter.api.Assertions.assertThrows;
53  import static org.junit.jupiter.api.Assertions.assertTrue;
54  import static org.junit.jupiter.api.Assumptions.assumeTrue;
55  
56  public abstract class AbstractSingleThreadEventLoopTest {
57      @Test
58      @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
59      public void testChannelsRegistered() throws Exception {
60          EventLoopGroup group = newEventLoopGroup();
61          final SingleThreadEventLoop loop = (SingleThreadEventLoop) group.next();
62  
63          try {
64              final Channel ch1 = newChannel();
65              final Channel ch2 = newChannel();
66  
67              int rc = registeredChannels(loop);
68              boolean channelCountSupported = rc != -1;
69  
70              if (channelCountSupported) {
71                  assertEquals(0, registeredChannels(loop));
72              }
73  
74              assertTrue(loop.register(ch1).syncUninterruptibly().isSuccess());
75              assertTrue(loop.register(ch2).syncUninterruptibly().isSuccess());
76              if (channelCountSupported) {
77                  checkNumRegisteredChannels(loop, 2);
78              }
79  
80              assertTrue(ch1.deregister().syncUninterruptibly().isSuccess());
81              if (channelCountSupported) {
82                  checkNumRegisteredChannels(loop, 1);
83              }
84          } finally {
85              group.shutdownGracefully();
86          }
87      }
88  
89      private static void checkNumRegisteredChannels(SingleThreadEventLoop loop, int numChannels) throws Exception {
90          // We need to loop as some EventLoop implementations may need some time to update the counter correctly.
91          while (registeredChannels(loop) != numChannels) {
92              Thread.sleep(50);
93          }
94      }
95  
96      // Only reliable if run from event loop
97      private static int registeredChannels(final SingleThreadEventLoop loop) throws Exception {
98          return loop.submit(new Callable<Integer>() {
99              @Override
100             public Integer call() {
101                 return loop.registeredChannels();
102             }
103         }).get(1, TimeUnit.SECONDS);
104     }
105 
106     @Test
107     @SuppressWarnings("deprecation")
108     public void shutdownBeforeStart() throws Exception {
109         EventLoopGroup group = newEventLoopGroup();
110         assertFalse(group.awaitTermination(2, TimeUnit.MILLISECONDS));
111         group.shutdown();
112         assertTrue(group.awaitTermination(200, TimeUnit.MILLISECONDS));
113     }
114 
115     @Test
116     public void shutdownGracefullyZeroQuietBeforeStart() throws Exception {
117         EventLoopGroup group = newEventLoopGroup();
118         assertTrue(group.shutdownGracefully(0L, 2L, TimeUnit.SECONDS).await(200L));
119     }
120 
121     // Copied from AbstractEventLoopTest
122     @Test
123     @Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
124     public void testShutdownGracefullyNoQuietPeriod() throws Exception {
125         EventLoopGroup loop = newEventLoopGroup();
126         ServerBootstrap b = new ServerBootstrap();
127         b.group(loop)
128         .channel(serverChannelClass())
129         .childHandler(new ChannelInboundHandlerAdapter());
130 
131         // Not close the Channel to ensure the EventLoop is still shutdown in time.
132         ChannelFuture cf = serverChannelClass() == LocalServerChannel.class
133                 ? b.bind(new LocalAddress(AbstractSingleThreadEventLoopTest.class)) : b.bind(0);
134         cf.sync().channel();
135 
136         Future<?> f = loop.shutdownGracefully(0, 1, TimeUnit.MINUTES);
137         assertTrue(loop.awaitTermination(600, TimeUnit.MILLISECONDS));
138         assertTrue(f.syncUninterruptibly().isSuccess());
139         assertTrue(loop.isShutdown());
140         assertTrue(loop.isTerminated());
141     }
142 
143     @Test
144     public void shutdownGracefullyBeforeStart() throws Exception {
145         EventLoopGroup group = newEventLoopGroup();
146         assertTrue(group.shutdownGracefully(200L, 1000L, TimeUnit.MILLISECONDS).await(500L));
147     }
148 
149     @Test
150     public void gracefulShutdownAfterStart() throws Exception {
151         EventLoop loop = newEventLoopGroup().next();
152         final CountDownLatch latch = new CountDownLatch(1);
153         loop.execute(new Runnable() {
154             @Override
155             public void run() {
156                 latch.countDown();
157             }
158         });
159 
160         // Wait for the event loop thread to start.
161         latch.await();
162 
163         // Request the event loop thread to stop.
164         loop.shutdownGracefully(200L, 3000L, TimeUnit.MILLISECONDS);
165 
166         // Wait until the event loop is terminated.
167         assertTrue(loop.awaitTermination(500L, TimeUnit.MILLISECONDS));
168 
169         assertRejection(loop);
170     }
171 
172     @Test
173     @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
174     public void testChannelsIteratorEmpty() throws Exception {
175         assumeTrue(supportsChannelIteration());
176         EventLoopGroup group = newEventLoopGroup();
177         final SingleThreadEventLoop loop = (SingleThreadEventLoop) group.next();
178         try {
179             runBlockingOn(loop, new Runnable() {
180                 @Override
181                 public void run() {
182                     final Iterator<Channel> iterator = loop.registeredChannelsIterator();
183 
184                     assertFalse(iterator.hasNext());
185                     assertThrows(NoSuchElementException.class, new Executable() {
186                         @Override
187                         public void execute() {
188                             iterator.next();
189                         }
190                     });
191                 }
192             });
193         } finally {
194             group.shutdownGracefully();
195         }
196     }
197 
198     @Test
199     @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
200     public void testChannelsIterator() throws Exception {
201         assumeTrue(supportsChannelIteration());
202         EventLoopGroup group = newEventLoopGroup();
203         final SingleThreadEventLoop loop = (SingleThreadEventLoop) group.next();
204         try {
205             final Channel ch1 = newChannel();
206             final Channel ch2 = newChannel();
207             loop.register(ch1).syncUninterruptibly();
208             loop.register(ch2).syncUninterruptibly();
209             assertEquals(2, registeredChannels(loop));
210 
211             runBlockingOn(loop, new Runnable() {
212                 @Override
213                 public void run() {
214                     final Iterator<Channel> iterator = loop.registeredChannelsIterator();
215 
216                     assertTrue(iterator.hasNext());
217                     Channel actualCh1 = iterator.next();
218                     assertNotNull(actualCh1);
219 
220                     assertTrue(iterator.hasNext());
221                     Channel actualCh2 = iterator.next();
222                     assertNotNull(actualCh2);
223 
224                     Set<Channel> expected = new HashSet<Channel>(4);
225                     expected.add(ch1);
226                     expected.add(ch2);
227                     expected.remove(actualCh1);
228                     expected.remove(actualCh2);
229                     assertTrue(expected.isEmpty());
230 
231                     assertFalse(iterator.hasNext());
232                     assertThrows(NoSuchElementException.class, new Executable() {
233                         @Override
234                         public void execute() {
235                             iterator.next();
236                         }
237                     });
238                 }
239             });
240         } finally {
241             group.shutdownGracefully();
242         }
243     }
244 
245     @Test
246     @Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
247     public void testChannelsIteratorRemoveThrows() throws Exception {
248         assumeTrue(supportsChannelIteration());
249         EventLoopGroup group = newEventLoopGroup();
250         final SingleThreadEventLoop loop = (SingleThreadEventLoop) group.next();
251 
252         try {
253             final Channel ch = newChannel();
254             loop.register(ch).syncUninterruptibly();
255             assertEquals(1, registeredChannels(loop));
256 
257             runBlockingOn(loop, new Runnable() {
258                 @Override
259                 public void run() {
260                     assertThrows(UnsupportedOperationException.class, new Executable() {
261                         @Override
262                         public void execute() {
263                             loop.registeredChannelsIterator().remove();
264                         }
265                     });
266                 }
267             });
268         } finally {
269             group.shutdownGracefully();
270         }
271     }
272 
273     @Test
274     void schedulingAndCancellingTasks() throws Exception {
275         Runnable runnable = new Runnable() {
276             @Override
277             public void run() {
278             }
279         };
280         List<ScheduledFuture<?>> tasks = new ArrayList<ScheduledFuture<?>>();
281         EventLoopGroup group = newEventLoopGroup();
282         try {
283             EventLoop eventLoop = group.next();
284             for (int i = 0; i < 5000; i++) {
285                 tasks.add(eventLoop.scheduleAtFixedRate(runnable, 1, 1, MILLISECONDS));
286                 if (tasks.size() > 500) {
287                     tasks.get(PlatformDependent.threadLocalRandom().nextInt(tasks.size())).cancel(false);
288                 }
289             }
290             for (ScheduledFuture<?> task : tasks) {
291                 task.cancel(false);
292             }
293             for (ScheduledFuture<?> task : tasks) {
294                 task.await();
295             }
296             for (ScheduledFuture<?> task : tasks) {
297                 if (!task.isCancelled()) {
298                     task.sync();
299                 }
300             }
301         } finally {
302             group.shutdownGracefully();
303         }
304     }
305 
306     private static void runBlockingOn(EventLoop eventLoop, final Runnable action) {
307         final Promise<Void> promise = eventLoop.newPromise();
308             eventLoop.execute(new Runnable() {
309                 @Override
310                 public void run() {
311                     try {
312                         action.run();
313                         promise.setSuccess(null);
314                     } catch (Throwable t) {
315                         promise.tryFailure(t);
316                     }
317                 }
318             });
319         try {
320             promise.await();
321         } catch (InterruptedException e) {
322             throw new RuntimeException(e);
323         }
324         Throwable cause = promise.cause();
325         if (cause != null) {
326             if (cause instanceof RuntimeException) {
327                 throw (RuntimeException) cause;
328             }
329             throw new RuntimeException(cause);
330         }
331     }
332 
333     private static final Runnable NOOP = new Runnable() {
334         @Override
335         public void run() { }
336     };
337 
338     private static void assertRejection(final EventExecutor loop) {
339         assertThrows(RejectedExecutionException.class, new Executable() {
340             @Override
341             public void execute() throws Throwable {
342                 loop.execute(NOOP);
343             }
344         });
345     }
346 
347     protected boolean supportsChannelIteration() {
348         return false;
349     }
350     protected abstract EventLoopGroup newEventLoopGroup();
351     protected abstract Channel newChannel();
352     protected abstract Class<? extends ServerChannel> serverChannelClass();
353 }