1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.testsuite.transport.socket;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.buffer.ByteBuf;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelHandlerContext;
23 import io.netty.channel.ChannelInboundHandler;
24 import io.netty.channel.ChannelInboundHandlerAdapter;
25 import io.netty.channel.ChannelOption;
26 import io.netty.channel.DefaultFileRegion;
27 import io.netty.channel.FileRegion;
28 import io.netty.channel.SimpleChannelInboundHandler;
29 import io.netty.channel.socket.oio.OioSocketChannel;
30 import io.netty.util.AbstractReferenceCounted;
31 import io.netty.util.concurrent.ImmediateEventExecutor;
32 import io.netty.util.concurrent.Promise;
33 import io.netty.util.internal.ObjectUtil;
34 import io.netty.util.internal.PlatformDependent;
35 import org.junit.jupiter.api.Test;
36 import org.junit.jupiter.api.TestInfo;
37 import org.junit.jupiter.api.Timeout;
38 import org.junit.jupiter.api.io.TempDir;
39
40 import java.io.File;
41 import java.io.FileOutputStream;
42 import java.io.IOException;
43 import java.io.RandomAccessFile;
44 import java.net.URI;
45 import java.nio.ByteBuffer;
46 import java.nio.channels.FileChannel;
47 import java.nio.channels.WritableByteChannel;
48 import java.nio.charset.StandardCharsets;
49 import java.nio.file.FileSystem;
50 import java.nio.file.FileSystems;
51 import java.nio.file.Files;
52 import java.nio.file.Path;
53 import java.nio.file.StandardOpenOption;
54 import java.util.Arrays;
55 import java.util.Collections;
56 import java.util.Random;
57 import java.util.concurrent.BlockingQueue;
58 import java.util.concurrent.LinkedBlockingQueue;
59 import java.util.concurrent.ThreadLocalRandom;
60 import java.util.concurrent.TimeUnit;
61 import java.util.concurrent.atomic.AtomicInteger;
62 import java.util.concurrent.atomic.AtomicReference;
63
64 import static io.netty.testsuite.transport.TestsuitePermutation.randomBufferType;
65 import static org.assertj.core.api.Assertions.assertThat;
66 import static org.junit.jupiter.api.Assertions.assertEquals;
67 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
68 import static org.junit.jupiter.api.Assertions.assertNotEquals;
69 import static org.junit.jupiter.api.Assertions.assertTrue;
70 import static org.junit.jupiter.api.Assumptions.assumeFalse;
71 import static org.junit.jupiter.api.Assumptions.assumeTrue;
72
73 public class SocketFileRegionTest extends AbstractSocketTest {
74
75 static final byte[] data = new byte[1048576 * 10];
76
77 static {
78 ThreadLocalRandom.current().nextBytes(data);
79 }
80
81 @Test
82 public void testFileRegion(TestInfo testInfo) throws Throwable {
83 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
84 @Override
85 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
86 testFileRegion(serverBootstrap, bootstrap);
87 }
88 });
89 }
90
91 protected boolean supportsCustomFileRegion() {
92 return true;
93 }
94
95 @Test
96 public void testCustomFileRegion(TestInfo testInfo) throws Throwable {
97 assumeTrue(supportsCustomFileRegion());
98 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
99 @Override
100 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
101 testCustomFileRegion(serverBootstrap, bootstrap);
102 }
103 });
104 }
105
106 @Test
107 public void testFileRegionNotAutoRead(TestInfo testInfo) throws Throwable {
108 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
109 @Override
110 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
111 testFileRegionNotAutoRead(serverBootstrap, bootstrap);
112 }
113 });
114 }
115
116 @Test
117 public void testFileRegionVoidPromise(TestInfo testInfo) throws Throwable {
118 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
119 @Override
120 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
121 testFileRegionVoidPromise(serverBootstrap, bootstrap);
122 }
123 });
124 }
125
126 @Test
127 public void testFileRegionVoidPromiseNotAutoRead(TestInfo testInfo) throws Throwable {
128 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
129 @Override
130 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
131 testFileRegionVoidPromiseNotAutoRead(serverBootstrap, bootstrap);
132 }
133 });
134 }
135
136 private static void write(FileChannel channel, String value, long position) throws IOException {
137 ByteBuffer buffer = ByteBuffer.wrap(value.getBytes(StandardCharsets.US_ASCII));
138 while (buffer.hasRemaining()) {
139 position += channel.write(buffer, position);
140 }
141 }
142
143 @Test
144 public void testFileRegionCountLargerThenFile(TestInfo testInfo) throws Throwable {
145 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
146 @Override
147 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
148 testFileRegionCountLargerThenFile(serverBootstrap, bootstrap);
149 }
150 });
151 }
152
153 @Test
154 @Timeout(value = 30, unit = TimeUnit.SECONDS)
155 public void testFileRegionDrainStopsAtCompletion(TestInfo testInfo) throws Throwable {
156 assumeTrue(supportsCustomFileRegion());
157 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
158 @Override
159 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
160 testFileRegionDrainStopsAtCompletion(serverBootstrap, bootstrap);
161 }
162 });
163 }
164
165 @Test
166 @Timeout(value = 30, unit = TimeUnit.SECONDS)
167 public void testFileRegionBeyond2GiB(TestInfo testInfo) throws Throwable {
168 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
169 @Override
170 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
171 testFileRegionBeyond2GiB(serverBootstrap, bootstrap);
172 }
173 });
174 }
175
176 @Test
177 @Timeout(value = 30, unit = TimeUnit.SECONDS)
178 public void testZipFileRegion(TestInfo testInfo, @TempDir final File archive) throws Throwable {
179 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
180 @Override
181 public void run(ServerBootstrap sb, Bootstrap cb) throws Throwable {
182 final byte[] data = new byte[256 * 1024 + 73];
183 new Random(0).nextBytes(data);
184 final byte[] expected = Arrays.copyOfRange(data, 37, data.length - 19);
185 URI uri = URI.create("jar:" + new File(archive, "file.zip").toURI());
186 Channel server = null;
187 Channel client = null;
188 final Promise<byte[]> received = ImmediateEventExecutor.INSTANCE.newPromise();
189 final AtomicReference<Channel> child =
190 new AtomicReference<Channel>();
191 FileSystem zip = null;
192 try {
193 zip = FileSystems.newFileSystem(uri, Collections.singletonMap("create", "true"));
194 Path path = zip.getPath("/file");
195 Files.write(path, data);
196 sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
197 private final byte[] bytes = new byte[expected.length];
198 private int offset;
199
200 @Override
201 public void channelActive(ChannelHandlerContext ctx) {
202 child.set(ctx.channel());
203 }
204
205 @Override
206 protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
207 int length = msg.readableBytes();
208 msg.readBytes(bytes, offset, length);
209 offset += length;
210 if (offset == bytes.length) {
211 received.trySuccess(bytes);
212 }
213 }
214
215 @Override
216 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
217 received.tryFailure(cause);
218 ctx.close();
219 }
220 });
221 cb.handler(new ChannelInboundHandlerAdapter());
222 server = sb.bind().sync().channel();
223 client = cb.connect(server.localAddress()).sync().channel();
224 DefaultFileRegion region = new DefaultFileRegion(
225 FileChannel.open(path, StandardOpenOption.READ), 37, expected.length);
226 client.writeAndFlush(region).sync();
227 assertThat(received.get(10, TimeUnit.SECONDS))
228 .containsExactly(expected);
229 assertThat(region.refCnt()).isZero();
230 } finally {
231 if (client != null) {
232 client.close().syncUninterruptibly();
233 }
234 if (child.get() != null) {
235 child.get().close().syncUninterruptibly();
236 }
237 if (server != null) {
238 server.close().syncUninterruptibly();
239 }
240 if (zip != null) {
241 zip.close();
242 }
243 }
244 }
245 });
246 }
247
248 public void testFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
249 testFileRegion0(sb, cb, false, true, true);
250 }
251
252 public void testCustomFileRegion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
253 testFileRegion0(sb, cb, false, true, false);
254 }
255
256 public void testFileRegionVoidPromise(ServerBootstrap sb, Bootstrap cb) throws Throwable {
257 testFileRegion0(sb, cb, true, true, true);
258 }
259
260 public void testFileRegionNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
261 testFileRegion0(sb, cb, false, false, true);
262 }
263
264 public void testFileRegionVoidPromiseNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
265 testFileRegion0(sb, cb, true, false, true);
266 }
267
268
269
270
271
272 public void testFileRegionBeyond2GiB(ServerBootstrap sb, Bootstrap cb) throws Throwable {
273 final String wrong = "wrong file offset";
274 final String beyond2GiB = "beyond 2 GiB !!!!";
275 final String beyond4GiB = "beyond 4 GiB !!!!";
276 final int length = wrong.length();
277 final long position2GiB = (1L << 31) + 100;
278 final long position4GiB = (1L << 32) + 100;
279
280 File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
281 file.deleteOnExit();
282
283
284
285 assertTrue(file.delete());
286 try (FileChannel channel = FileChannel.open(file.toPath(),
287 StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.SPARSE)) {
288
289 write(channel, wrong, position4GiB & 0xFFFFFFFFL);
290 write(channel, beyond2GiB, position2GiB);
291 write(channel, beyond4GiB, position4GiB);
292 }
293
294 final BlockingQueue<String> received = new LinkedBlockingQueue<String>();
295 sb.childHandler(new ChannelInboundHandlerAdapter() {
296 private final StringBuilder builder = new StringBuilder();
297
298 @Override
299 public void channelRead(ChannelHandlerContext ctx, Object msg) {
300 ByteBuf buf = (ByteBuf) msg;
301 try {
302 builder.append(buf.toString(StandardCharsets.US_ASCII));
303 } finally {
304 buf.release();
305 }
306 while (builder.length() >= length) {
307 received.add(builder.substring(0, length));
308 builder.delete(0, length);
309 }
310 }
311 });
312 cb.handler(new ChannelInboundHandlerAdapter());
313
314 Channel sc = sb.bind().sync().channel();
315 Channel cc = cb.connect(sc.localAddress()).sync().channel();
316 try {
317 cc.writeAndFlush(new DefaultFileRegion(file, position4GiB, length)).sync();
318 assertEquals(beyond4GiB, received.poll(10, TimeUnit.SECONDS));
319 cc.writeAndFlush(new DefaultFileRegion(file, position2GiB, length)).sync();
320 assertEquals(beyond2GiB, received.poll(10, TimeUnit.SECONDS));
321 } finally {
322 cc.close().sync();
323 sc.close().sync();
324 file.delete();
325 }
326 }
327
328 public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
329 File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
330 file.deleteOnExit();
331
332 final FileOutputStream out = new FileOutputStream(file);
333 out.write(data);
334 out.close();
335
336 sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
337 @Override
338 protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
339
340 }
341 });
342 cb.handler(new ChannelInboundHandlerAdapter());
343
344 Channel sc = sb.bind().sync().channel();
345 Channel cc = cb.connect(sc.localAddress()).sync().channel();
346
347
348 FileRegion region = new DefaultFileRegion(
349 new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
350
351 assertInstanceOf(IOException.class, cc.writeAndFlush(region).await().cause());
352 cc.close().sync();
353 sc.close().sync();
354 }
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369 public void testFileRegionDrainStopsAtCompletion(ServerBootstrap sb, Bootstrap cb) throws Throwable {
370
371
372
373
374 final int regionSize = 16;
375
376 sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {
377 @Override
378 protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
379
380 }
381 });
382 cb.handler(new ChannelInboundHandlerAdapter());
383
384 Channel sc = sb.bind().sync().channel();
385 Channel cc = cb.connect(sc.localAddress()).sync().channel();
386 try {
387
388
389
390
391
392
393 assumeFalse(cc instanceof OioSocketChannel,
394 "OIO transport does not honour transferred() for drain-loop termination");
395
396 OvershootDetectingFileRegion region = new OvershootDetectingFileRegion(regionSize);
397
398
399
400
401
402 cc.writeAndFlush(region).sync();
403 int overshoot = region.transferToCallsPastCompletion.get();
404 assertEquals(0, overshoot,
405 "transferTo() invoked " + overshoot
406 + " time(s) after region.transferred() reached region.count()="
407 + regionSize);
408 } finally {
409 cc.close().sync();
410 sc.close().sync();
411 }
412 }
413
414 private static void testFileRegion0(
415 ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion)
416 throws Throwable {
417 sb.childOption(ChannelOption.AUTO_READ, autoRead);
418 cb.option(ChannelOption.AUTO_READ, autoRead);
419
420 final int bufferSize = 1024;
421 final File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
422 file.deleteOnExit();
423
424 final FileOutputStream out = new FileOutputStream(file);
425 final Random random = ThreadLocalRandom.current();
426
427
428 final int startOffset = random.nextInt(8192);
429 for (int i = 0; i < startOffset; i ++) {
430 out.write(random.nextInt());
431 }
432
433
434 out.write(data, bufferSize, data.length - bufferSize);
435
436
437 for (int i = random.nextInt(8192); i > 0; i --) {
438 out.write(random.nextInt());
439 }
440
441 out.close();
442
443 ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {
444 @Override
445 public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
446 }
447
448 @Override
449 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
450 if (!autoRead) {
451 ctx.read();
452 }
453 }
454
455 @Override
456 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
457 ctx.close();
458 }
459 };
460 TestHandler sh = new TestHandler(autoRead);
461
462 sb.childHandler(sh);
463 cb.handler(ch);
464
465 Channel sc = sb.bind().sync().channel();
466
467 Channel cc = cb.connect(sc.localAddress()).sync().channel();
468 FileRegion region = new DefaultFileRegion(
469 new RandomAccessFile(file, "r").getChannel(), startOffset, data.length - bufferSize);
470 FileRegion emptyRegion = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, 0);
471
472 if (!defaultFileRegion) {
473 region = new FileRegionWrapper(region);
474 emptyRegion = new FileRegionWrapper(emptyRegion);
475 }
476
477
478
479
480
481 if (voidPromise) {
482 assertEquals(cc.voidPromise(), cc.write(
483 randomBufferType(cc.alloc(), data, 0, bufferSize), cc.voidPromise()));
484 assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
485 assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
486 } else {
487 assertNotEquals(cc.voidPromise(), cc.write(
488 randomBufferType(cc.alloc(), data, 0, bufferSize)));
489 assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
490 assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
491 }
492
493 while (sh.counter < data.length) {
494 if (sh.exception.get() != null) {
495 break;
496 }
497
498 Thread.sleep(50);
499 }
500
501 sh.channel.close().sync();
502 cc.close().sync();
503 sc.close().sync();
504
505 if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
506 throw sh.exception.get();
507 }
508
509 if (sh.exception.get() != null) {
510 throw sh.exception.get();
511 }
512
513
514 assertEquals(data.length, sh.counter);
515 }
516
517 private static class TestHandler extends SimpleChannelInboundHandler<ByteBuf> {
518 private final boolean autoRead;
519 volatile Channel channel;
520 final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
521 volatile int counter;
522
523 TestHandler(boolean autoRead) {
524 this.autoRead = autoRead;
525 }
526
527 @Override
528 public void channelActive(ChannelHandlerContext ctx)
529 throws Exception {
530 channel = ctx.channel();
531 if (!autoRead) {
532 ctx.read();
533 }
534 }
535
536 @Override
537 public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
538 byte[] actual = new byte[in.readableBytes()];
539 in.readBytes(actual);
540
541 int lastIdx = counter;
542 for (int i = 0; i < actual.length; i ++) {
543 assertEquals(data[i + lastIdx], actual[i]);
544 }
545 counter += actual.length;
546 }
547
548 @Override
549 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
550 if (!autoRead) {
551 ctx.read();
552 }
553 }
554
555 @Override
556 public void exceptionCaught(ChannelHandlerContext ctx,
557 Throwable cause) throws Exception {
558 if (exception.compareAndSet(null, cause)) {
559 ctx.close();
560 }
561 }
562 }
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586 private static final class OvershootDetectingFileRegion extends AbstractReferenceCounted
587 implements FileRegion {
588 private final long count;
589 private long transferred;
590 final AtomicInteger transferToCallsPastCompletion = new AtomicInteger();
591
592 OvershootDetectingFileRegion(long count) {
593
594
595 this.count = ObjectUtil.checkInRange(count, 2L, Long.MAX_VALUE, "count");
596 }
597
598 @Override
599 public long position() {
600 return 0;
601 }
602
603 @Override
604 public long count() {
605 return count;
606 }
607
608 @Override
609 public long transferred() {
610 return transferred;
611 }
612
613 @Override
614 @Deprecated
615 public long transfered() {
616 return transferred;
617 }
618
619 @Override
620 public long transferTo(WritableByteChannel target, long position) throws IOException {
621
622
623
624
625 if (position != transferred) {
626 throw new IOException("transferTo position " + position + " != transferred() "
627 + transferred);
628 }
629 if (transferred < count) {
630 int n = target.write(ByteBuffer.wrap(new byte[] { 0x42 }));
631 if (n > 0) {
632 transferred = count;
633 }
634 return n;
635 }
636 transferToCallsPastCompletion.incrementAndGet();
637 return target.write(ByteBuffer.wrap(new byte[] { (byte) 0xFF }));
638 }
639
640 @Override
641 protected void deallocate() {
642
643
644 }
645
646 @Override
647 public FileRegion retain() {
648 super.retain();
649 return this;
650 }
651
652 @Override
653 public FileRegion retain(int increment) {
654 super.retain(increment);
655 return this;
656 }
657
658 @Override
659 public FileRegion touch() {
660 return this;
661 }
662
663 @Override
664 public FileRegion touch(Object hint) {
665 return this;
666 }
667 }
668
669 private static final class FileRegionWrapper implements FileRegion {
670 private final FileRegion region;
671
672 FileRegionWrapper(FileRegion region) {
673 this.region = region;
674 }
675
676 @Override
677 public int refCnt() {
678 return region.refCnt();
679 }
680
681 @Override
682 public long position() {
683 return region.position();
684 }
685
686 @Override
687 @Deprecated
688 public long transfered() {
689 return region.transferred();
690 }
691
692 @Override
693 public boolean release() {
694 return region.release();
695 }
696
697 @Override
698 public long transferred() {
699 return region.transferred();
700 }
701
702 @Override
703 public long count() {
704 return region.count();
705 }
706
707 @Override
708 public boolean release(int decrement) {
709 return region.release(decrement);
710 }
711
712 @Override
713 public long transferTo(WritableByteChannel target, long position) throws IOException {
714 return region.transferTo(target, position);
715 }
716
717 @Override
718 public FileRegion retain() {
719 region.retain();
720 return this;
721 }
722
723 @Override
724 public FileRegion retain(int increment) {
725 region.retain(increment);
726 return this;
727 }
728
729 @Override
730 public FileRegion touch() {
731 region.touch();
732 return this;
733 }
734
735 @Override
736 public FileRegion touch(Object hint) {
737 region.touch(hint);
738 return this;
739 }
740 }
741 }