Skip to content

Commit

Permalink
[broker] Avoid unnecessary recalculation of maxSubscriptionsPerTopic …
Browse files Browse the repository at this point in the history
…in AbstractTopic (#12658)

### Motivation

Currently, `AbstractTopic#maxSubscriptionsPerTopic` stores the value of namespace level policy, but we have broker level setting in `org.apache.pulsar.broker.ServiceConfiguration#maxSubscriptionsPerTopic` and topic level setting in `org.apache.pulsar.common.policies.data.TopicPolicies#maxSubscriptionsPerTopic`.
And the real value we used of `maxSubscriptionsPerTopic` is calculated every time in `org.apache.pulsar.broker.service.persistent.PersistentTopic#checkMaxSubscriptionsPerTopicExceed`. It can be avoided by cache maxSubscriptionsPerTopic result locally.

As we have already registered listeners to namespace policy and topic policy updates, so we can cache the value locally in AbstractTopic to avoid the recalculation.

Finally, as some of other policies value have similar issues, I am introducing `PolicyHierarchyValue` to solve the hierarchy value storage and calculation.

### Modifications

Introduce `PolicyHierarchyValue` to store policy value in broker, namespace and topic level.
It provides corresponding `updateXX` methods, and recalculate real value in it.  And the `get()` method returns the policy value we should use directly.
  • Loading branch information
Jason918 authored Nov 8, 2021
1 parent 08d8e95 commit a60cdaa
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.bookkeeper.mledger.impl.ManagedLedgerMBeanImpl.ENTRY_LATENCY_BUCKETS_USEC;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -53,6 +54,7 @@
import org.apache.pulsar.common.policies.data.InactiveTopicDeleteMode;
import org.apache.pulsar.common.policies.data.InactiveTopicPolicies;
import org.apache.pulsar.common.policies.data.Policies;
import org.apache.pulsar.common.policies.data.PolicyHierarchyValue;
import org.apache.pulsar.common.policies.data.PublishRate;
import org.apache.pulsar.common.policies.data.SchemaCompatibilityStrategy;
import org.apache.pulsar.common.policies.data.TopicPolicies;
Expand Down Expand Up @@ -104,7 +106,9 @@ public abstract class AbstractTopic implements Topic {

protected volatile int maxUnackedMessagesOnConsumerAppilied = 0;

protected volatile Integer maxSubscriptionsPerTopic = null;
@VisibleForTesting
@Getter
protected volatile PolicyHierarchyValue<Integer> maxSubscriptionsPerTopic;

protected volatile PublishRateLimiter topicPublishRateLimiter;

Expand Down Expand Up @@ -148,6 +152,11 @@ public AbstractTopic(String topic, BrokerService brokerService) {
.getBrokerDeleteInactiveTopicsMode());
this.topicMaxMessageSizeCheckIntervalMs = TimeUnit.SECONDS.toMillis(brokerService.pulsar().getConfiguration()
.getMaxMessageSizeCheckIntervalInSeconds());

maxSubscriptionsPerTopic = new PolicyHierarchyValue<>();
maxSubscriptionsPerTopic.updateBrokerValue(brokerService.pulsar().getConfiguration()
.getMaxSubscriptionsPerTopic());

this.lastActive = System.nanoTime();
this.preciseTopicPublishRateLimitingEnable =
brokerService.pulsar().getConfiguration().isPreciseTopicPublishRateLimiterEnable();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2407,7 +2407,7 @@ public CompletableFuture<Void> onPoliciesUpdate(Policies data) {
schemaValidationEnforced = data.schema_validation_enforced;
updateUnackedMessagesAppliedOnSubscription(data);
updateUnackedMessagesExceededOnConsumer(data);
maxSubscriptionsPerTopic = data.max_subscriptions_per_topic;
maxSubscriptionsPerTopic.updateNamespaceValue(data.max_subscriptions_per_topic);

if (data.delayed_delivery_policies != null) {
delayedDeliveryTickTimeMillis = data.delayed_delivery_policies.getTickTime();
Expand Down Expand Up @@ -3096,6 +3096,8 @@ public void onUpdate(TopicPolicies policies) {
updateMaxPublishRate(namespacePolicies.orElse(null));
}

maxSubscriptionsPerTopic.updateTopicValue(policies.getMaxSubscriptionsPerTopic());

if (policies.isInactiveTopicPoliciesSet()) {
inactiveTopicPolicies = policies.getInactiveTopicPolicies();
} else if (namespacePolicies.isPresent() && namespacePolicies.get().inactive_topic_policies != null) {
Expand Down Expand Up @@ -3177,20 +3179,11 @@ private boolean checkMaxSubscriptionsPerTopicExceed(String subscriptionName) {
if (StringUtils.isNotEmpty(subscriptionName) && getSubscription(subscriptionName) != null) {
return false;
}
Integer maxSubsPerTopic = getTopicPolicies()
.map(TopicPolicies::getMaxSubscriptionsPerTopic)
.orElseGet(() -> {
if (maxSubscriptionsPerTopic != null) {
return maxSubscriptionsPerTopic;
} else {
return brokerService.pulsar().getConfig().getMaxSubscriptionsPerTopic();
}
});

if (maxSubsPerTopic > 0) {
if (subscriptions != null && subscriptions.size() >= maxSubsPerTopic) {
return true;
}
Integer maxSubsPerTopic = maxSubscriptionsPerTopic.get();

if (maxSubsPerTopic != null && maxSubsPerTopic > 0) {
return subscriptions != null && subscriptions.size() >= maxSubsPerTopic;
}

return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2145,9 +2145,8 @@ public void testMaxSubscriptionsPerTopic() throws Exception {
final int namespaceLevelMaxSub = 3;
admin.namespaces().setMaxSubscriptionsPerTopic(myNamespace, namespaceLevelMaxSub);
PersistentTopic persistentTopic = (PersistentTopic) pulsar.getBrokerService().getTopicIfExists(topic).get().get();
Field field = PersistentTopic.class.getSuperclass().getDeclaredField("maxSubscriptionsPerTopic");
field.setAccessible(true);
Awaitility.await().until(() -> (int) field.get(persistentTopic) == namespaceLevelMaxSub);
Awaitility.await().until(() -> Integer.valueOf(namespaceLevelMaxSub)
.equals(persistentTopic.getMaxSubscriptionsPerTopic().getNamespaceValue()));

try (PulsarClient client = PulsarClient.builder().operationTimeout(1000, TimeUnit.MILLISECONDS)
.serviceUrl(brokerUrl.toString()).build()) {
Expand All @@ -2174,7 +2173,7 @@ public void testMaxSubscriptionsPerTopic() throws Exception {
}
//Removed namespace-level policy, broker-level should take effect
admin.namespaces().removeMaxSubscriptionsPerTopic(myNamespace);
Awaitility.await().until(() -> field.get(persistentTopic) == null);
Awaitility.await().until(() -> persistentTopic.getMaxSubscriptionsPerTopic().getNamespaceValue() == null);
consumerList.add(pulsarClient.newConsumer(Schema.STRING)
.subscriptionName(UUID.randomUUID().toString()).topic(topic).subscribe());
assertEquals(consumerList.size(), brokerLevelMaxSub);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* 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.pulsar.common.policies.data;

import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import lombok.Getter;

/**
* Policy value holder for different hierarchy level.
* Currently, we have three hierarchy with priority : topic > namespace > broker.
*/
public class PolicyHierarchyValue<T> {
private static final AtomicReferenceFieldUpdater<PolicyHierarchyValue, Object> VALUE_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(PolicyHierarchyValue.class, Object.class, "value");

private volatile T brokerValue;

@VisibleForTesting
@Getter
private volatile T namespaceValue;

private volatile T topicValue;

private volatile T value;

public PolicyHierarchyValue() {
}

public void updateBrokerValue(T brokerValue) {
this.brokerValue = brokerValue;
updateValue();
}

public void updateNamespaceValue(T namespaceValue) {
this.namespaceValue = namespaceValue;
updateValue();
}

public void updateTopicValue(T topicValue) {
this.topicValue = topicValue;
updateValue();
}

private void updateValue() {
VALUE_UPDATER.updateAndGet(this, (preValue) -> {
if (topicValue != null) {
return topicValue;
} else if (namespaceValue != null) {
return namespaceValue;
} else {
return brokerValue;
}
});
}

public T get() {
return value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* 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.pulsar.common.policies.data;

import org.testng.Assert;
import org.testng.annotations.Test;


public class PolicyHierarchyValueTest {
@Test
public void testPolicyValue() {
PolicyHierarchyValue<Integer> value = new PolicyHierarchyValue<>();

value.updateBrokerValue(1);
Assert.assertEquals(value.get(), Integer.valueOf(1));

value.updateNamespaceValue(2);
Assert.assertEquals(value.get(), Integer.valueOf(2));

value.updateTopicValue(3);
Assert.assertEquals(value.get(), Integer.valueOf(3));

value.updateNamespaceValue(null);
Assert.assertEquals(value.get(), Integer.valueOf(3));

value.updateTopicValue(null);
Assert.assertEquals(value.get(), Integer.valueOf(1));
}
}

0 comments on commit a60cdaa

Please sign in to comment.