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 2021/10/08 20:10:08 UTC

[GitHub] [geode] jdeppe-pivotal commented on a change in pull request #6926: GEODE-9607 take2

jdeppe-pivotal commented on a change in pull request #6926:
URL: https://github.com/apache/geode/pull/6926#discussion_r725220888



##########
File path: geode-for-redis/src/main/java/org/apache/geode/redis/internal/pubsub/Publisher.java
##########
@@ -0,0 +1,480 @@
+/*
+ * 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.redis.internal.pubsub;
+
+import static org.apache.geode.internal.lang.utils.JavaWorkarounds.computeIfAbsent;
+import static org.apache.geode.logging.internal.executors.LoggingExecutors.newCachedThreadPool;
+import static org.apache.geode.redis.internal.netty.Coder.bytesToString;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bMESSAGE;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bPMESSAGE;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.util.ReferenceCountUtil;
+import org.apache.logging.log4j.Logger;
+
+import org.apache.geode.DataSerializer;
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.InternalDataSerializer;
+import org.apache.geode.internal.cache.execute.InternalFunction;
+import org.apache.geode.internal.serialization.DataSerializableFixedID;
+import org.apache.geode.internal.serialization.DeserializationContext;
+import org.apache.geode.internal.serialization.KnownVersion;
+import org.apache.geode.internal.serialization.SerializationContext;
+import org.apache.geode.logging.internal.log4j.api.LogService;
+import org.apache.geode.redis.internal.RegionProvider;
+import org.apache.geode.redis.internal.netty.Client;
+import org.apache.geode.redis.internal.netty.Coder;
+import org.apache.geode.redis.internal.pubsub.Subscriptions.PatternSubscriptions;
+
+/**
+ * This class deals with doing a redis pubsub publish operation.
+ * Since publish requests from the same client must have order
+ * preserved, and since publish requests myst be done in a thread
+ * other than the one the request arrived from, this class has an
+ * instance of ClientPublisher for any Client that does a publish.
+ * The ClientPublisher maintains an ordered queue of requests
+ * and is careful to process them in the order they arrived.
+ * It supports batching them which can be a significant win as
+ * soon as a second geode server is added to the cluster.
+ * WARNING: The queue on the ClientPublisher is unbounded
+ * which can cause the server to run out of memory if the
+ * client keeps sending publish requests faster than the server
+ * can process them. It would be nice for this queue to have
+ * a bound but that could cause a hang because of the way
+ * we use Netty.
+ */
+public class Publisher {
+  private static final Logger logger = LogService.getLogger();
+
+  private final ExecutorService executor;
+  private final RegionProvider regionProvider;
+  private final Subscriptions subscriptions;
+  private final Map<Client, ClientPublisher> clientPublishers = new ConcurrentHashMap<>();
+
+  public Publisher(RegionProvider regionProvider, Subscriptions subscriptions) {
+    this.executor = createExecutorService();
+    this.regionProvider = regionProvider;
+    this.subscriptions = subscriptions;
+    registerPublishFunction();
+  }
+
+  @VisibleForTesting
+  Publisher(RegionProvider regionProvider, Subscriptions subscriptions, ExecutorService executor) {
+    this.executor = executor;
+    this.regionProvider = regionProvider;
+    this.subscriptions = subscriptions;
+    // no need to register function in unit tests
+  }
+
+  public void publish(Client client, byte[] channel, byte[] message) {
+    ClientPublisher clientPublisher =
+        computeIfAbsent(clientPublishers, client, key -> new ClientPublisher());
+    clientPublisher.publish(channel, message);
+  }
+
+  public void disconnect(Client client) {
+    clientPublishers.remove(client);
+  }
+
+  public void close() {
+    executor.shutdown();
+    try {
+      if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
+        logger.warn("Timed out waiting for queued publish requests to be sent.");
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+    }
+  }
+
+  @VisibleForTesting
+  int getClientCount() {
+    return clientPublishers.size();
+  }
+
+
+  private static ExecutorService createExecutorService() {
+    // return newFixedThreadPool(2, "GeodeRedisServer-Publish-", true);

Review comment:
       This can be removed

##########
File path: geode-for-redis/src/main/java/org/apache/geode/redis/internal/pubsub/Publisher.java
##########
@@ -0,0 +1,480 @@
+/*
+ * 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.redis.internal.pubsub;
+
+import static org.apache.geode.internal.lang.utils.JavaWorkarounds.computeIfAbsent;
+import static org.apache.geode.logging.internal.executors.LoggingExecutors.newCachedThreadPool;
+import static org.apache.geode.redis.internal.netty.Coder.bytesToString;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bMESSAGE;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bPMESSAGE;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.util.ReferenceCountUtil;
+import org.apache.logging.log4j.Logger;
+
+import org.apache.geode.DataSerializer;
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.InternalDataSerializer;
+import org.apache.geode.internal.cache.execute.InternalFunction;
+import org.apache.geode.internal.serialization.DataSerializableFixedID;
+import org.apache.geode.internal.serialization.DeserializationContext;
+import org.apache.geode.internal.serialization.KnownVersion;
+import org.apache.geode.internal.serialization.SerializationContext;
+import org.apache.geode.logging.internal.log4j.api.LogService;
+import org.apache.geode.redis.internal.RegionProvider;
+import org.apache.geode.redis.internal.netty.Client;
+import org.apache.geode.redis.internal.netty.Coder;
+import org.apache.geode.redis.internal.pubsub.Subscriptions.PatternSubscriptions;
+
+/**
+ * This class deals with doing a redis pubsub publish operation.
+ * Since publish requests from the same client must have order
+ * preserved, and since publish requests myst be done in a thread
+ * other than the one the request arrived from, this class has an
+ * instance of ClientPublisher for any Client that does a publish.
+ * The ClientPublisher maintains an ordered queue of requests
+ * and is careful to process them in the order they arrived.
+ * It supports batching them which can be a significant win as
+ * soon as a second geode server is added to the cluster.
+ * WARNING: The queue on the ClientPublisher is unbounded
+ * which can cause the server to run out of memory if the
+ * client keeps sending publish requests faster than the server
+ * can process them. It would be nice for this queue to have
+ * a bound but that could cause a hang because of the way
+ * we use Netty.
+ */
+public class Publisher {
+  private static final Logger logger = LogService.getLogger();
+
+  private final ExecutorService executor;
+  private final RegionProvider regionProvider;
+  private final Subscriptions subscriptions;
+  private final Map<Client, ClientPublisher> clientPublishers = new ConcurrentHashMap<>();
+
+  public Publisher(RegionProvider regionProvider, Subscriptions subscriptions) {
+    this.executor = createExecutorService();
+    this.regionProvider = regionProvider;
+    this.subscriptions = subscriptions;
+    registerPublishFunction();
+  }
+
+  @VisibleForTesting
+  Publisher(RegionProvider regionProvider, Subscriptions subscriptions, ExecutorService executor) {
+    this.executor = executor;
+    this.regionProvider = regionProvider;
+    this.subscriptions = subscriptions;
+    // no need to register function in unit tests
+  }
+
+  public void publish(Client client, byte[] channel, byte[] message) {
+    ClientPublisher clientPublisher =
+        computeIfAbsent(clientPublishers, client, key -> new ClientPublisher());
+    clientPublisher.publish(channel, message);
+  }
+
+  public void disconnect(Client client) {
+    clientPublishers.remove(client);
+  }
+
+  public void close() {
+    executor.shutdown();
+    try {
+      if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
+        logger.warn("Timed out waiting for queued publish requests to be sent.");
+      }
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+    }
+  }
+
+  @VisibleForTesting
+  int getClientCount() {
+    return clientPublishers.size();
+  }
+
+
+  private static ExecutorService createExecutorService() {
+    // return newFixedThreadPool(2, "GeodeRedisServer-Publish-", true);
+    return newCachedThreadPool("GeodeRedisServer-Publish-", true);
+  }
+
+  private void registerPublishFunction() {
+    FunctionService.registerFunction(new PublishFunction(this));
+  }
+
+  @SuppressWarnings("unchecked")
+  private void internalPublish(PublishRequestBatch batch) {
+    Set<DistributedMember> remoteMembers = regionProvider.getRemoteRegionMembers();
+    List<PublishRequest> optimizedBatch = batch.optimize();
+    try {
+      ResultCollector<?, ?> resultCollector = null;
+      try {
+        if (!remoteMembers.isEmpty()) {
+          // send function to remotes
+          resultCollector = FunctionService
+              .onMembers(remoteMembers)
+              .setArguments(optimizedBatch)
+              .execute(PublishFunction.ID);
+        }
+      } finally {
+        // execute it locally
+        publishBatchToLocalSubscribers(optimizedBatch);
+        if (resultCollector != null) {
+          // block until remote execute completes
+          resultCollector.getResult();
+        }
+      }
+    } catch (Exception e) {
+      // the onMembers contract is for execute to throw an exception
+      // if one of the members goes down.
+      if (logger.isDebugEnabled()) {
+        logger.debug(
+            "Exception executing publish function on batch {}. If a server departed during the publish then an exception is expected.",
+            batch, e);
+      }
+    }
+  }
+
+  private void publishBatchToLocalSubscribers(List<PublishRequest> batch) {
+    batch.forEach(request -> {
+      publishRequestToLocalChannelSubscribers(request);
+      publishRequestToLocalPatternSubscribers(request);
+    });
+  }
+
+  private void publishRequestToLocalChannelSubscribers(PublishRequest request) {
+    Collection<Subscription> channelSubscriptions =
+        subscriptions.getChannelSubscriptions(request.getChannel());
+    if (channelSubscriptions.isEmpty()) {
+      return;
+    }
+    ByteBuf writeBuf = channelSubscriptions.iterator().next().getChannelWriteBuffer();
+    for (byte[] message : request.getMessages()) {
+      Coder.writeArrayResponse(writeBuf, bMESSAGE, request.getChannel(), message);
+    }
+    if (channelSubscriptions.size() == 1) {
+      Subscription singleSubscription = channelSubscriptions.iterator().next();
+      singleSubscription.waitUntilReadyToPublish();
+      singleSubscription.writeBufferToChannel(writeBuf);

Review comment:
       Seems like `waitUntilReadyToPublish`  is always being called before `writeBufferToChannel` - should these two methods be collapsed?

##########
File path: geode-for-redis/src/main/java/org/apache/geode/redis/internal/pubsub/Publisher.java
##########
@@ -0,0 +1,480 @@
+/*
+ * 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.redis.internal.pubsub;
+
+import static org.apache.geode.internal.lang.utils.JavaWorkarounds.computeIfAbsent;
+import static org.apache.geode.logging.internal.executors.LoggingExecutors.newCachedThreadPool;
+import static org.apache.geode.redis.internal.netty.Coder.bytesToString;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bMESSAGE;
+import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bPMESSAGE;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.util.ReferenceCountUtil;
+import org.apache.logging.log4j.Logger;
+
+import org.apache.geode.DataSerializer;
+import org.apache.geode.annotations.VisibleForTesting;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.InternalDataSerializer;
+import org.apache.geode.internal.cache.execute.InternalFunction;
+import org.apache.geode.internal.serialization.DataSerializableFixedID;
+import org.apache.geode.internal.serialization.DeserializationContext;
+import org.apache.geode.internal.serialization.KnownVersion;
+import org.apache.geode.internal.serialization.SerializationContext;
+import org.apache.geode.logging.internal.log4j.api.LogService;
+import org.apache.geode.redis.internal.RegionProvider;
+import org.apache.geode.redis.internal.netty.Client;
+import org.apache.geode.redis.internal.netty.Coder;
+import org.apache.geode.redis.internal.pubsub.Subscriptions.PatternSubscriptions;
+
+/**
+ * This class deals with doing a redis pubsub publish operation.
+ * Since publish requests from the same client must have order
+ * preserved, and since publish requests myst be done in a thread

Review comment:
       Minor typo: myst -> must




-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@geode.apache.org

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