001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2016-2023 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.net; 020 021import java.io.IOException; 022import java.net.SocketAddress; 023import java.nio.ByteBuffer; 024import java.nio.channels.SelectionKey; 025import java.nio.channels.SocketChannel; 026import java.util.ArrayDeque; 027import java.util.HashSet; 028import java.util.Optional; 029import java.util.Queue; 030import java.util.Set; 031import java.util.concurrent.ExecutorService; 032import org.jgrapes.core.Channel; 033import org.jgrapes.core.Component; 034import org.jgrapes.core.Components; 035import org.jgrapes.core.EventPipeline; 036import org.jgrapes.core.Manager; 037import org.jgrapes.core.Subchannel; 038import org.jgrapes.core.annotation.Handler; 039import org.jgrapes.io.IOSubchannel.DefaultIOSubchannel; 040import org.jgrapes.io.NioHandler; 041import org.jgrapes.io.events.Closed; 042import org.jgrapes.io.events.HalfClosed; 043import org.jgrapes.io.events.Input; 044import org.jgrapes.io.events.NioRegistration; 045import org.jgrapes.io.events.NioRegistration.Registration; 046import org.jgrapes.io.events.OpenSocketConnection; 047import org.jgrapes.io.events.Output; 048import org.jgrapes.io.util.ManagedBuffer; 049import org.jgrapes.io.util.ManagedBufferPool; 050 051/** 052 * Provides a base class for the {@link SocketServer} and the 053 * {@link SocketConnector}. 054 */ 055@SuppressWarnings("PMD.AvoidSynchronizedStatement") 056public abstract class SocketConnectionManager extends Component { 057 058 private int bufferSize = 32_768; 059 protected final Set<SocketChannelImpl> channels = new HashSet<>(); 060 private ExecutorService executorService; 061 062 /** 063 * Creates a new server using the given channel. 064 * 065 * @param componentChannel the component's channel 066 */ 067 public SocketConnectionManager(Channel componentChannel) { 068 super(componentChannel); 069 } 070 071 /** 072 * Sets the buffer size for the send an receive buffers. 073 * If no size is set, a default value of 32768 will be used. 074 * 075 * @param bufferSize the size to use for the send and receive buffers 076 * @return the socket connection manager for easy chaining 077 */ 078 public SocketConnectionManager setBufferSize(int bufferSize) { 079 this.bufferSize = bufferSize; 080 return this; 081 } 082 083 /** 084 * Return the configured buffer size. 085 * 086 * @return the bufferSize 087 */ 088 public int bufferSize() { 089 return bufferSize; 090 } 091 092 /** 093 * Sets an executor service to be used by the event pipelines 094 * that process the data from the network. Setting this 095 * to an executor service with a limited number of threads 096 * allows to control the maximum load from the network. 097 * 098 * @param executorService the executorService to set 099 * @return the socket connection manager for easy chaining 100 * @see Manager#newEventPipeline(ExecutorService) 101 */ 102 public SocketConnectionManager 103 setExecutorService(ExecutorService executorService) { 104 this.executorService = executorService; 105 return this; 106 } 107 108 /** 109 * Returns the executor service. 110 * 111 * @return the executorService 112 */ 113 public ExecutorService executorService() { 114 return executorService; 115 } 116 117 /** 118 * Writes the data passed in the event. 119 * 120 * The end of record flag is used to determine if a channel is 121 * eligible for purging. If the flag is set and all output has 122 * been processed, the channel is purgeable until input is 123 * received or another output event causes the state to be 124 * reevaluated. 125 * 126 * @param event the event 127 * @param channel the channel 128 * @throws InterruptedException the interrupted exception 129 */ 130 @Handler 131 public void onOutput(Output<ByteBuffer> event, 132 SocketChannelImpl channel) throws InterruptedException { 133 if (channels.contains(channel)) { 134 channel.write(event); 135 } 136 } 137 138 /** 139 * Removes the channel from the set of registered channels. 140 * 141 * @param channel the channel 142 * @return true, if channel was registered 143 */ 144 protected boolean removeChannel(SocketChannelImpl channel) { 145 synchronized (channels) { 146 return channels.remove(channel); 147 } 148 } 149 150 /* 151 * (non-Javadoc) 152 * 153 * @see java.lang.Object#toString() 154 */ 155 @Override 156 public String toString() { 157 return Components.objectName(this); 158 } 159 160 /** 161 * The close state. 162 */ 163 private enum ConnectionState { 164 OPEN, DELAYED_EVENT, DELAYED_REQUEST, HALF_CLOSED, CLOSED 165 } 166 167 /** 168 * The purgeable state. 169 */ 170 @SuppressWarnings("PMD.ShortVariable") 171 private enum PurgeableState { 172 NO, PENDING, YES 173 } 174 175 /** 176 * The internal representation of a connection. 177 */ 178 @SuppressWarnings({ "PMD.GodClass", "PMD.PublicMemberInNonPublicType" }) 179 protected class SocketChannelImpl 180 extends DefaultIOSubchannel implements NioHandler, SocketIOChannel { 181 182 private final OpenSocketConnection openEvent; 183 private final SocketChannel nioChannel; 184 private final SocketAddress localAddress; 185 private final SocketAddress remoteAddress; 186 private final EventPipeline downPipeline; 187 private final ManagedBufferPool<ManagedBuffer<ByteBuffer>, 188 ByteBuffer> readBuffers; 189 private Registration registration; 190 private int selectionKeys; 191 private final Queue< 192 ManagedBuffer<ByteBuffer>.ByteBufferView> pendingWrites 193 = new ArrayDeque<>(); 194 private ConnectionState connState = ConnectionState.OPEN; 195 private PurgeableState purgeable = PurgeableState.NO; 196 private long becamePurgeableAt; 197 198 /** 199 * @param nioChannel the channel 200 * @throws IOException if an I/O error occurred 201 */ 202 @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") 203 public SocketChannelImpl(OpenSocketConnection openEvent, 204 SocketChannel nioChannel) throws IOException { 205 super(channel(), newEventPipeline()); 206 this.openEvent = openEvent; 207 this.nioChannel = nioChannel; 208 // Copy, because they are only available while channel is open. 209 localAddress = nioChannel.getLocalAddress(); 210 remoteAddress = nioChannel.getRemoteAddress(); 211 if (executorService == null) { 212 downPipeline = newEventPipeline(); 213 } else { 214 downPipeline = newEventPipeline(executorService); 215 } 216 String channelName 217 = Components.objectName(SocketConnectionManager.this) 218 + "." + Components.objectName(this); 219 220 // Prepare write buffers 221 int writeBufferSize = bufferSize < 1500 ? 1500 : bufferSize; 222 setByteBufferPool(new ManagedBufferPool<>(ManagedBuffer::new, 223 () -> { 224 return ByteBuffer.allocate(writeBufferSize); 225 }, 2) 226 .setName(channelName + ".upstream.buffers")); 227 228 // Prepare read buffers 229 int readBufferSize = bufferSize < 1500 ? 1500 : bufferSize; 230 readBuffers = new ManagedBufferPool<>(ManagedBuffer::new, 231 () -> { 232 return ByteBuffer.allocate(readBufferSize); 233 }, 2) 234 .setName(channelName + ".downstream.buffers"); 235 236 // Ready to use 237 channels.add(this); 238 239 // Register with dispatcher 240 nioChannel.configureBlocking(false); 241 SocketConnectionManager.this.fire( 242 new NioRegistration(this, nioChannel, 0, 243 SocketConnectionManager.this), 244 BROADCAST); 245 } 246 247 /** 248 * Returns the event that caused this connection to be opened. 249 * 250 * May be `null` if the channel was created in response to a 251 * client connecting to the server. 252 * 253 * @return the event 254 */ 255 public Optional<OpenSocketConnection> openEvent() { 256 return Optional.ofNullable(openEvent); 257 } 258 259 /** 260 * Gets the nio channel. 261 * 262 * @return the nioChannel 263 */ 264 public SocketChannel nioChannel() { 265 return nioChannel; 266 } 267 268 @Override 269 public SocketAddress localAddress() { 270 return localAddress; 271 } 272 273 @Override 274 public SocketAddress remoteAddress() { 275 return remoteAddress; 276 } 277 278 /** 279 * Gets the read buffers. 280 * 281 * @return the readBuffers 282 */ 283 public ManagedBufferPool<ManagedBuffer<ByteBuffer>, ByteBuffer> 284 readBuffers() { 285 return readBuffers; 286 } 287 288 /** 289 * Gets the down pipeline. 290 * 291 * @return the downPipeline 292 */ 293 public EventPipeline downPipeline() { 294 return downPipeline; 295 } 296 297 /** 298 * Invoked when registration has completed. 299 * 300 * @param registration the registration (result from the 301 * {@link NioRegistration} event) 302 */ 303 public void registrationComplete(Registration registration) { 304 this.registration = registration; 305 selectionKeys |= SelectionKey.OP_READ; 306 registration.updateInterested(selectionKeys); 307 } 308 309 /** 310 * Checks if is purgeable. 311 * 312 * @return true, if is purgeable 313 */ 314 @Override 315 public boolean isPurgeable() { 316 return purgeable == PurgeableState.YES; 317 } 318 319 /** 320 * Gets the the time when the connection became purgeable. 321 * 322 * @return the time 323 */ 324 @Override 325 public long purgeableSince() { 326 return becamePurgeableAt; 327 } 328 329 /** 330 * Write the data on this channel. 331 * 332 * @param event the event 333 */ 334 public void write(Output<ByteBuffer> event) 335 throws InterruptedException { 336 synchronized (pendingWrites) { 337 if (!nioChannel.isOpen()) { 338 return; 339 } 340 ManagedBuffer<ByteBuffer>.ByteBufferView reader 341 = event.buffer().newByteBufferView(); 342 if (!pendingWrites.isEmpty()) { 343 reader.managedBuffer().lockBuffer(); 344 purgeable = event.isEndOfRecord() ? PurgeableState.PENDING 345 : PurgeableState.NO; 346 pendingWrites.add(reader); 347 return; 348 } 349 try { 350 nioChannel.write(reader.get()); 351 } catch (IOException e) { 352 forceClose(e); 353 return; 354 } 355 if (!reader.get().hasRemaining()) { 356 if (event.isEndOfRecord()) { 357 becamePurgeableAt = System.currentTimeMillis(); 358 purgeable = PurgeableState.YES; 359 } else { 360 purgeable = PurgeableState.NO; 361 } 362 return; 363 } 364 reader.managedBuffer().lockBuffer(); 365 purgeable = event.isEndOfRecord() ? PurgeableState.PENDING 366 : PurgeableState.NO; 367 pendingWrites.add(reader); 368 selectionKeys |= SelectionKey.OP_WRITE; 369 registration.updateInterested(selectionKeys); 370 } 371 } 372 373 @Override 374 public void handleOps(int ops) throws InterruptedException { 375 if ((ops & SelectionKey.OP_READ) != 0) { 376 handleReadOp(); 377 } 378 if ((ops & SelectionKey.OP_WRITE) != 0) { 379 handleWriteOp(); 380 } 381 } 382 383 /** 384 * Gets a buffer from the pool and reads available data into it. 385 * Sends the result as event. 386 * 387 * @throws InterruptedException 388 * @throws IOException 389 */ 390 @SuppressWarnings("PMD.EmptyCatchBlock") 391 private void handleReadOp() throws InterruptedException { 392 ManagedBuffer<ByteBuffer> buffer; 393 buffer = readBuffers.acquire(); 394 try { 395 int bytes = buffer.fillFromChannel(nioChannel); 396 if (bytes == 0) { 397 buffer.unlockBuffer(); 398 return; 399 } 400 if (bytes > 0) { 401 purgeable = PurgeableState.NO; 402 downPipeline.fire(Input.fromSink(buffer, false), this); 403 return; 404 } 405 } catch (IOException e) { 406 // Buffer already unlocked by fillFromChannel 407 forceClose(e); 408 return; 409 } 410 // EOF (-1) from other end 411 buffer.unlockBuffer(); 412 synchronized (nioChannel) { 413 if (connState == ConnectionState.HALF_CLOSED) { 414 // Other end confirms our close, complete close 415 try { 416 nioChannel.close(); 417 } catch (IOException e) { 418 // Ignored for close 419 } 420 connState = ConnectionState.CLOSED; 421 downPipeline.fire(new Closed<>(), this); 422 return; 423 } 424 } 425 // Other end initiates close 426 selectionKeys &= ~SelectionKey.OP_READ; 427 registration.updateInterested(selectionKeys); 428 downPipeline.submit("SendHalfClosed", () -> { 429 try { 430 // Inform downstream and wait until everything has settled. 431 newEventPipeline().fire(new HalfClosed(), this).get(); 432 // All settled. 433 removeChannel(this); 434 downPipeline.fire(new Closed<>(), this); 435 // Close our end if everything has been written. 436 synchronized (pendingWrites) { 437 synchronized (nioChannel) { 438 try { 439 if (!pendingWrites.isEmpty()) { 440 // Pending writes, delay close 441 connState = ConnectionState.DELAYED_REQUEST; 442 return; 443 } 444 // Nothing left to do, close 445 nioChannel.close(); 446 connState = ConnectionState.CLOSED; 447 } catch (IOException e) { 448 // Ignored for close 449 } 450 } 451 } 452 } catch (InterruptedException e) { 453 // Nothing to do about this 454 } 455 }); 456 } 457 458 /** 459 * Checks if there is still data to be written. This may be 460 * a left over in an incompletely written buffer or a complete 461 * pending buffer. 462 * 463 * @throws IOException 464 * @throws InterruptedException 465 */ 466 @SuppressWarnings({ "PMD.EmptyCatchBlock", "PMD.CognitiveComplexity", 467 "PMD.AvoidBranchingStatementAsLastInLoop", 468 "PMD.AvoidDeeplyNestedIfStmts" }) 469 private void handleWriteOp() throws InterruptedException { 470 while (true) { 471 ManagedBuffer<ByteBuffer>.ByteBufferView head; 472 synchronized (pendingWrites) { 473 if (pendingWrites.isEmpty()) { 474 // Nothing left to write, stop getting ops 475 selectionKeys &= ~SelectionKey.OP_WRITE; 476 registration.updateInterested(selectionKeys); 477 // Was the connection closed while we were writing? 478 if (connState == ConnectionState.DELAYED_REQUEST 479 || connState == ConnectionState.DELAYED_EVENT) { 480 synchronized (nioChannel) { 481 try { 482 if (connState == ConnectionState.DELAYED_REQUEST) { 483 // Delayed close request from other end, 484 // complete 485 nioChannel.close(); 486 connState = ConnectionState.CLOSED; 487 } 488 if (connState == ConnectionState.DELAYED_EVENT) { 489 // Delayed close from this end, initiate 490 nioChannel.shutdownOutput(); 491 connState = ConnectionState.HALF_CLOSED; 492 } 493 } catch (IOException e) { 494 // Ignored for close 495 } 496 } 497 } else { 498 if (purgeable == PurgeableState.PENDING) { 499 purgeable = PurgeableState.YES; 500 } 501 } 502 break; // Nothing left to do 503 } 504 head = pendingWrites.peek(); 505 if (!head.get().hasRemaining()) { 506 // Nothing left in head buffer, try next 507 head.managedBuffer().unlockBuffer(); 508 pendingWrites.remove(); 509 continue; 510 } 511 } 512 try { 513 nioChannel.write(head.get()); // write... 514 } catch (IOException e) { 515 forceClose(e); 516 return; 517 } 518 break; // ... and wait for next op 519 } 520 } 521 522 /** 523 * Closes this channel. 524 * 525 * @throws IOException if an error occurs 526 * @throws InterruptedException if the execution was interrupted 527 */ 528 public void close() throws IOException, InterruptedException { 529 if (!removeChannel(this)) { 530 return; 531 } 532 synchronized (pendingWrites) { 533 if (!pendingWrites.isEmpty()) { 534 // Pending writes, delay close until done 535 connState = ConnectionState.DELAYED_EVENT; 536 return; 537 } 538 // Nothing left to do, proceed 539 synchronized (nioChannel) { 540 if (nioChannel.isOpen()) { 541 // Initiate close, must be confirmed by other end 542 nioChannel.shutdownOutput(); 543 connState = ConnectionState.HALF_CLOSED; 544 } 545 } 546 } 547 } 548 549 @SuppressWarnings("PMD.EmptyCatchBlock") 550 private void forceClose(Throwable error) throws InterruptedException { 551 try { 552 nioChannel.close(); 553 connState = ConnectionState.CLOSED; 554 } catch (IOException e) { 555 // Closed only to make sure, any failure can be ignored. 556 } 557 if (removeChannel(this)) { 558 var evt = new Closed<Void>(error); 559 downPipeline.fire(evt, this); 560 } 561 } 562 563 /* 564 * (non-Javadoc) 565 * 566 * @see org.jgrapes.io.IOSubchannel.DefaultSubchannel#toString() 567 */ 568 @Override 569 public String toString() { 570 return Subchannel.toString(this); 571 } 572 } 573 574}