You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@geode.apache.org by GitBox <gi...@apache.org> on 2020/10/27 17:17:51 UTC

[GitHub] [geode] bschuchardt commented on a change in pull request #5666: GEODE-8652: Allow NioSslEngine.close() to Bypass Locks

bschuchardt commented on a change in pull request #5666:
URL: https://github.com/apache/geode/pull/5666#discussion_r512813580



##########
File path: geode-core/src/main/java/org/apache/geode/internal/net/NioSslEngine.java
##########
@@ -315,50 +317,48 @@ public ByteBuffer ensureWrappedCapacity(int amount, ByteBuffer wrappedBuffer,
   }
 
   @Override
-  public ByteBuffer readAtLeast(SocketChannel channel, int bytes,
+  public ByteBufferSharing readAtLeast(SocketChannel channel, int bytes,
       ByteBuffer wrappedBuffer) throws IOException {
-    if (peerAppData.capacity() > bytes) {
-      // we already have a buffer that's big enough
-      if (peerAppData.capacity() - peerAppData.position() < bytes) {
-        peerAppData.compact();
-        peerAppData.flip();
-      }
-    }
+    try (final ByteBufferSharing inputSharing = shareInputBuffer()) {
 
-    while (peerAppData.remaining() < bytes) {
-      wrappedBuffer.limit(wrappedBuffer.capacity());
-      int amountRead = channel.read(wrappedBuffer);
-      if (amountRead < 0) {
-        throw new EOFException();
+      ByteBuffer peerAppData = inputSharing.getBuffer();
+
+      if (peerAppData.capacity() > bytes) {
+        // we already have a buffer that's big enough
+        if (peerAppData.capacity() - peerAppData.position() < bytes) {
+          peerAppData.compact();
+          peerAppData.flip();
+        }
       }
-      if (amountRead > 0) {
-        wrappedBuffer.flip();
-        // prep the decoded buffer for writing
-        peerAppData.compact();
-        peerAppData = unwrap(wrappedBuffer);
-        // done writing to the decoded buffer - prep it for reading again
-        peerAppData.flip();
+
+      while (peerAppData.remaining() < bytes) {
+        wrappedBuffer.limit(wrappedBuffer.capacity());
+        int amountRead = channel.read(wrappedBuffer);
+        if (amountRead < 0) {
+          throw new EOFException();
+        }
+        if (amountRead > 0) {
+          wrappedBuffer.flip();
+          // prep the decoded buffer for writing
+          peerAppData.compact();
+          try (final ByteBufferSharing inputSharing2 = unwrap(wrappedBuffer)) {
+            // done writing to the decoded buffer - prep it for reading again
+            final ByteBuffer peerAppDataNew = inputSharing2.getBuffer();
+            peerAppDataNew.flip();
+            peerAppData = peerAppDataNew; // loop needs new reference!
+          }
+        }
       }
+      return shareInputBuffer();
     }
-    return peerAppData;
   }
 
   @Override
-  public ByteBuffer getUnwrappedBuffer(ByteBuffer wrappedBuffer) {
-    return peerAppData;
-  }
-
-  /**
-   * ensures that the unwrapped buffer associated with the given wrapped buffer has
-   * sufficient capacity for the given amount of bytes. This may compact the
-   * buffer or it may return a new buffer.
-   */
-  public ByteBuffer ensureUnwrappedCapacity(int amount) {
-    // for TTLS the app-data buffers do not need to be tracked direct-buffers since we
-    // do not use them for I/O operations
-    peerAppData =
-        bufferPool.expandReadBufferIfNeeded(TRACKED_RECEIVER, peerAppData, amount);
-    return peerAppData;
+  public ByteBufferSharing getUnwrappedBuffer(ByteBuffer wrappedBuffer) {
+    /*
+     * TODO: it can't be right that we ignore the wrappedBuffer parameter here!

Review comment:
       please address this new TODO

##########
File path: geode-core/src/main/java/org/apache/geode/internal/net/ByteBufferSharingImpl.java
##########
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.internal.net;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.internal.net.BufferPool.BufferType;
+
+/**
+ * An {@link AutoCloseable} meant to be acquired in a try-with-resources statement. The resource (a
+ * {@link ByteBuffer}) is available (for reading and modification) in the scope of the
+ * try-with-resources.
+ */
+class ByteBufferSharingImpl implements ByteBufferSharing {
+
+  static class LockAttemptTimedOut extends Exception {
+  }
+
+  private final Lock lock;
+  private final AtomicBoolean isClosed;
+  // mutable because in general our ByteBuffer may need to be resized (grown or compacted)
+  private ByteBuffer buffer;
+  private final BufferType bufferType;
+  private final AtomicInteger counter;
+  private final BufferPool bufferPool;
+
+  /**
+   * This constructor is for use only by the owner of the shared resource (a {@link ByteBuffer}).
+   *
+   * A resource owner must invoke {@link #alias()} once for each reference that escapes (is passed
+   * to an external object or is returned to an external caller.)
+   *
+   * This constructor acquires no lock. The reference count will be 1 after this constructor
+   * completes.
+   */
+  ByteBufferSharingImpl(final ByteBuffer buffer, final BufferType bufferType,
+      final BufferPool bufferPool) {
+    this.buffer = buffer;
+    this.bufferType = bufferType;
+    this.bufferPool = bufferPool;
+    lock = new ReentrantLock();
+    counter = new AtomicInteger(1);
+    isClosed = new AtomicBoolean(false);
+  }
+
+  /**
+   * The destructor. Called by the resource owner to undo the work of the constructor.
+   */
+  void destruct() {
+    if (isClosed.compareAndSet(false, true)) {
+      dropReference();
+    }
+  }
+
+  /**
+   * This method is for use only by the owner of the shared resource. It's used for handing out
+   * references to the shared resource. So it does reference counting and also acquires a lock.
+   *
+   * Resource owners call this method as the last thing before returning a reference to the caller.
+   * That caller binds that reference to a variable in a try-with-resources statement and relies on
+   * the AutoCloseable protocol to invoke close() on the object at the end of the block.
+   */
+  ByteBufferSharing alias() {
+    lock.lock();
+    addReference();
+    return this;
+  }
+
+  /**
+   * This variant throws {@link LockAttemptTimedOut} if it can't acquire the lock in time.
+   */
+  ByteBufferSharing alias(final long time, final TimeUnit unit) throws LockAttemptTimedOut {
+    try {
+      if (!lock.tryLock(time, unit)) {
+        throw new LockAttemptTimedOut();
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new LockAttemptTimedOut();
+    }
+    addReference();
+    return this;
+  }
+
+  @Override
+  public ByteBuffer getBuffer() throws IOException {
+    if (isClosed.get()) {
+      throw new IOException("NioSslEngine has been closed");
+    } else {
+      return buffer;
+    }
+  }
+
+  @Override
+  public ByteBuffer expandWriteBufferIfNeeded(final int newCapacity) throws IOException {
+    return buffer = bufferPool.expandWriteBufferIfNeeded(bufferType, getBuffer(), newCapacity);
+  }
+
+  @Override
+  public void close() {
+    dropReference();
+    lock.unlock();
+  }
+
+  private int addReference() {
+    return counter.incrementAndGet();
+  }
+
+  private int dropReference() {

Review comment:
       If the buffer is released to the BufferPool shouldn't this impl be marked as "closed"?

##########
File path: geode-core/src/main/java/org/apache/geode/internal/net/ByteBufferSharingImpl.java
##########
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.internal.net;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.internal.net.BufferPool.BufferType;
+
+/**
+ * An {@link AutoCloseable} meant to be acquired in a try-with-resources statement. The resource (a
+ * {@link ByteBuffer}) is available (for reading and modification) in the scope of the
+ * try-with-resources.
+ */
+class ByteBufferSharingImpl implements ByteBufferSharing {
+
+  static class LockAttemptTimedOut extends Exception {
+  }
+
+  private final Lock lock;
+  private final AtomicBoolean isClosed;
+  // mutable because in general our ByteBuffer may need to be resized (grown or compacted)
+  private ByteBuffer buffer;
+  private final BufferType bufferType;
+  private final AtomicInteger counter;
+  private final BufferPool bufferPool;
+
+  /**
+   * This constructor is for use only by the owner of the shared resource (a {@link ByteBuffer}).
+   *
+   * A resource owner must invoke {@link #alias()} once for each reference that escapes (is passed
+   * to an external object or is returned to an external caller.)
+   *
+   * This constructor acquires no lock. The reference count will be 1 after this constructor
+   * completes.
+   */
+  ByteBufferSharingImpl(final ByteBuffer buffer, final BufferType bufferType,
+      final BufferPool bufferPool) {
+    this.buffer = buffer;
+    this.bufferType = bufferType;
+    this.bufferPool = bufferPool;
+    lock = new ReentrantLock();
+    counter = new AtomicInteger(1);
+    isClosed = new AtomicBoolean(false);
+  }
+
+  /**
+   * The destructor. Called by the resource owner to undo the work of the constructor.
+   */
+  void destruct() {
+    if (isClosed.compareAndSet(false, true)) {
+      dropReference();
+    }
+  }
+
+  /**
+   * This method is for use only by the owner of the shared resource. It's used for handing out
+   * references to the shared resource. So it does reference counting and also acquires a lock.
+   *
+   * Resource owners call this method as the last thing before returning a reference to the caller.
+   * That caller binds that reference to a variable in a try-with-resources statement and relies on
+   * the AutoCloseable protocol to invoke close() on the object at the end of the block.
+   */
+  ByteBufferSharing alias() {
+    lock.lock();
+    addReference();
+    return this;
+  }
+
+  /**
+   * This variant throws {@link LockAttemptTimedOut} if it can't acquire the lock in time.
+   */
+  ByteBufferSharing alias(final long time, final TimeUnit unit) throws LockAttemptTimedOut {
+    try {
+      if (!lock.tryLock(time, unit)) {
+        throw new LockAttemptTimedOut();
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new LockAttemptTimedOut();
+    }
+    addReference();
+    return this;
+  }
+
+  @Override
+  public ByteBuffer getBuffer() throws IOException {
+    if (isClosed.get()) {
+      throw new IOException("NioSslEngine has been closed");
+    } else {
+      return buffer;
+    }
+  }
+
+  @Override
+  public ByteBuffer expandWriteBufferIfNeeded(final int newCapacity) throws IOException {
+    return buffer = bufferPool.expandWriteBufferIfNeeded(bufferType, getBuffer(), newCapacity);
+  }
+
+  @Override
+  public void close() {
+    dropReference();
+    lock.unlock();
+  }
+
+  private int addReference() {
+    return counter.incrementAndGet();
+  }
+
+  private int dropReference() {

Review comment:
       the return value from this method is never used

##########
File path: geode-core/src/main/java/org/apache/geode/internal/net/ByteBufferSharingImpl.java
##########
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License. You may obtain a
+ * copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package org.apache.geode.internal.net;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.internal.net.BufferPool.BufferType;
+
+/**
+ * An {@link AutoCloseable} meant to be acquired in a try-with-resources statement. The resource (a
+ * {@link ByteBuffer}) is available (for reading and modification) in the scope of the
+ * try-with-resources.
+ */
+class ByteBufferSharingImpl implements ByteBufferSharing {
+
+  static class LockAttemptTimedOut extends Exception {
+  }
+
+  private final Lock lock;
+  private final AtomicBoolean isClosed;
+  // mutable because in general our ByteBuffer may need to be resized (grown or compacted)
+  private ByteBuffer buffer;
+  private final BufferType bufferType;
+  private final AtomicInteger counter;
+  private final BufferPool bufferPool;
+
+  /**
+   * This constructor is for use only by the owner of the shared resource (a {@link ByteBuffer}).
+   *
+   * A resource owner must invoke {@link #alias()} once for each reference that escapes (is passed
+   * to an external object or is returned to an external caller.)
+   *
+   * This constructor acquires no lock. The reference count will be 1 after this constructor
+   * completes.
+   */
+  ByteBufferSharingImpl(final ByteBuffer buffer, final BufferType bufferType,
+      final BufferPool bufferPool) {
+    this.buffer = buffer;
+    this.bufferType = bufferType;
+    this.bufferPool = bufferPool;
+    lock = new ReentrantLock();
+    counter = new AtomicInteger(1);
+    isClosed = new AtomicBoolean(false);
+  }
+
+  /**
+   * The destructor. Called by the resource owner to undo the work of the constructor.
+   */
+  void destruct() {
+    if (isClosed.compareAndSet(false, true)) {
+      dropReference();
+    }
+  }
+
+  /**
+   * This method is for use only by the owner of the shared resource. It's used for handing out
+   * references to the shared resource. So it does reference counting and also acquires a lock.
+   *
+   * Resource owners call this method as the last thing before returning a reference to the caller.
+   * That caller binds that reference to a variable in a try-with-resources statement and relies on
+   * the AutoCloseable protocol to invoke close() on the object at the end of the block.
+   */
+  ByteBufferSharing alias() {

Review comment:
       Can we name this something more pertinent, like "createReference"?  The name "alias" doesn't tell me that this method is creating a reference that needs to be released.

##########
File path: geode-core/src/main/java/org/apache/geode/internal/net/NioSslEngine.java
##########
@@ -368,17 +368,15 @@ public void doneReadingDirectAck(ByteBuffer unwrappedBuffer) {
     // read-operations
   }
 
-  @Override

Review comment:
       I like how you've removed the need for this method




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org