1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
68 final Queue<Object> inboundBuffer = PlatformDependent.newSpscQueue();
69 private final Runnable readTask = new Runnable() {
70 @Override
71 public void run() {
72
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
224 if (localAddress != null) {
225 if (parent() == null) {
226 LocalChannelRegistry.unregister(localAddress);
227 }
228 localAddress = null;
229 }
230
231
232
233
234
235 closedFrom = STATE_UPDATER.getAndSet(this, State.CLOSED);
236
237
238 if (writeInProgress && peer != null) {
239 finishPeerRead(peer);
240 }
241
242 ChannelPromise promise = connectPromise;
243 if (promise != null) {
244
245 promise.tryFailure(new ClosedChannelException());
246 connectPromise = null;
247 }
248 }
249
250 if (peer != null && parent() == null && closedFrom != State.CONNECTED) {
251
252
253
254
255 this.peer = null;
256 } else if (peer != null) {
257 this.peer = null;
258
259
260
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
277
278 peer.close();
279 }
280 PlatformDependent.throwException(cause);
281 }
282 }
283 } finally {
284
285 if (oldState != null && oldState != State.CLOSED) {
286
287
288
289
290 releaseInboundBuffers();
291 }
292 }
293 }
294
295 private void tryClose(boolean isActive) {
296 if (isActive) {
297
298
299
300
301
302 finishPeerRead0(this);
303 readInboundBeforeClose();
304 unsafe().close(unsafe().voidPromise());
305 } else if (connectPromise != null) {
306
307
308
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
321
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
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;
353 } else {
354
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
423
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
439
440
441
442
443 writeInProgress = false;
444 }
445
446 finishPeerRead(peer);
447 }
448
449 private void finishPeerRead(final LocalChannel peer) {
450
451 if (peer.eventLoop() == eventLoop() && !peer.writeInProgress) {
452 finishPeerRead0(peer);
453 } else {
454 runFinishPeerReadTask(peer);
455 }
456 }
457
458 private void runFinishTask0() {
459
460
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
497 FINISH_READ_FUTURE_UPDATER.compareAndSet(peer, peerFinishReadFuture, null);
498 }
499 }
500
501
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
520 }
521
522 @Override
523 public void registered() {
524
525
526
527
528
529
530
531
532 final LocalChannel peer = LocalChannel.this.peer;
533 if (peer != null && parent() != null) {
534
535 State oldState = state;
536 state = State.CONNECTED;
537
538
539
540
541 if (STATE_UPDATER.compareAndSet(peer, State.BOUND, State.CONNECTED) ||
542 peer.state == State.CONNECTED) {
543 peer.remoteAddress = parent().localAddress();
544
545
546
547
548
549 peer.eventLoop().execute(new Runnable() {
550 @Override
551 public void run() {
552 ChannelPromise promise = peer.connectPromise;
553
554
555
556 if (promise != null && promise.trySuccess()) {
557 peer.pipeline().fireChannelActive();
558 }
559 }
560 });
561 } else {
562
563
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
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 }