You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by GitBox <gi...@apache.org> on 2018/07/13 13:55:20 UTC
[GitHub] merlimat closed pull request #2148: Fix schema initialization
merlimat closed pull request #2148: Fix schema initialization
URL: https://github.com/apache/incubator-pulsar/pull/2148
This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:
As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/schema/BookkeeperSchemaStorage.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/schema/BookkeeperSchemaStorage.java
index c07217c9b8..b8d9a27fe7 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/schema/BookkeeperSchemaStorage.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/schema/BookkeeperSchemaStorage.java
@@ -27,8 +27,8 @@
import static org.apache.pulsar.broker.service.schema.BookkeeperSchemaStorage.Functions.newSchemaEntry;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Charsets;
import com.google.protobuf.ByteString;
+
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -36,7 +36,11 @@
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
import javax.validation.constraints.NotNull;
+
import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.client.LedgerEntry;
@@ -64,6 +68,11 @@
private final ServiceConfiguration config;
private BookKeeper bookKeeper;
+
+ private final ConcurrentMap<String, CompletableFuture<LocatorEntry>> locatorEntries = new ConcurrentHashMap<>();
+
+ private final ConcurrentMap<String, CompletableFuture<StoredSchema>> readSchemaOperations = new ConcurrentHashMap<>();
+
@VisibleForTesting
BookkeeperSchemaStorage(PulsarService pulsar) {
this.pulsar = pulsar;
@@ -113,20 +122,31 @@ public void start() throws IOException {
@NotNull
private CompletableFuture<StoredSchema> getSchema(String schemaId) {
- return getSchemaLocator(getSchemaPath(schemaId)).thenCompose(locator -> {
+ // There's already a schema read operation in progress. Just piggyback on that
+ return readSchemaOperations.computeIfAbsent(schemaId, key -> {
+ CompletableFuture<StoredSchema> future = new CompletableFuture<>();
- if (!locator.isPresent()) {
- return completedFuture(null);
- }
+ getSchemaLocator(getSchemaPath(schemaId)).thenCompose(locator -> {
+ if (!locator.isPresent()) {
+ return completedFuture(null);
+ }
- SchemaStorageFormat.SchemaLocator schemaLocator = locator.get().locator;
- return readSchemaEntry(schemaLocator.getInfo().getPosition())
- .thenApply(entry ->
- new StoredSchema(
- entry.getSchemaData().toByteArray(),
- new LongSchemaVersion(schemaLocator.getInfo().getVersion())
- )
- );
+ SchemaStorageFormat.SchemaLocator schemaLocator = locator.get().locator;
+ return readSchemaEntry(schemaLocator.getInfo().getPosition())
+ .thenApply(entry -> new StoredSchema(entry.getSchemaData().toByteArray(),
+ new LongSchemaVersion(schemaLocator.getInfo().getVersion())));
+ }).handleAsync((res, ex) -> {
+ // Cleanup the pending ops from the map
+ readSchemaOperations.remove(schemaId, future);
+ if (ex != null) {
+ future.completeExceptionally(ex);
+ } else {
+ future.complete(res);
+ }
+ return null;
+ });
+
+ return future;
});
}
@@ -331,34 +351,46 @@ private String getSchemaPath(String schemaId) {
@NotNull
private CompletableFuture<LocatorEntry> getOrCreateSchemaLocator(String schema) {
- return getSchemaLocator(schema).thenCompose(schemaLocatorStatEntry -> {
- if (schemaLocatorStatEntry.isPresent()) {
- return completedFuture(schemaLocatorStatEntry.get());
- } else {
- SchemaStorageFormat.SchemaLocator locator = SchemaStorageFormat.SchemaLocator.newBuilder()
- .setInfo(SchemaStorageFormat.IndexEntry.newBuilder()
- .setVersion(-1L)
- .setHash(ByteString.EMPTY)
- .setPosition(SchemaStorageFormat.PositionInfo.newBuilder()
- .setEntryId(-1L)
- .setLedgerId(-1L)
- )
- ).build();
-
- CompletableFuture<LocatorEntry> future = new CompletableFuture<>();
-
- ZkUtils.asyncCreateFullPathOptimistic(zooKeeper, schema, locator.toByteArray(), Acl, CreateMode.PERSISTENT,
- (rc, path, ctx, name) -> {
- Code code = Code.get(rc);
- if (code != Code.OK) {
- future.completeExceptionally(KeeperException.create(code));
- } else {
- future.complete(new LocatorEntry(locator, -1));
- }
- }, null);
-
- return future;
- }
+ // Protect from concurrent schema locator creation
+ return locatorEntries.computeIfAbsent(schema, key -> {
+ CompletableFuture<LocatorEntry> future = new CompletableFuture<>();
+
+ getSchemaLocator(schema).thenCompose(schemaLocatorStatEntry -> {
+ if (schemaLocatorStatEntry.isPresent()) {
+ return completedFuture(schemaLocatorStatEntry.get());
+ } else {
+ SchemaStorageFormat.SchemaLocator locator = SchemaStorageFormat.SchemaLocator.newBuilder()
+ .setInfo(SchemaStorageFormat.IndexEntry.newBuilder().setVersion(-1L)
+ .setHash(ByteString.EMPTY).setPosition(SchemaStorageFormat.PositionInfo.newBuilder()
+ .setEntryId(-1L).setLedgerId(-1L)))
+ .build();
+
+ CompletableFuture<LocatorEntry> zkFuture = new CompletableFuture<>();
+
+ ZkUtils.asyncCreateFullPathOptimistic(zooKeeper, schema, locator.toByteArray(), Acl,
+ CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
+ Code code = Code.get(rc);
+ if (code != Code.OK) {
+ zkFuture.completeExceptionally(KeeperException.create(code));
+ } else {
+ zkFuture.complete(new LocatorEntry(locator, -1));
+ }
+ }, null);
+
+ return zkFuture;
+ }
+ }).handleAsync((res, ex) -> {
+ // Cleanup the pending ops from the map
+ locatorEntries.remove(schema, future);
+ if (ex != null) {
+ future.completeExceptionally(ex);
+ } else {
+ future.complete(res);
+ }
+ return null;
+ });
+
+ return future;
});
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PartitionedTopicsSchemaTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PartitionedTopicsSchemaTest.java
new file mode 100644
index 0000000000..6e9b1220a5
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/PartitionedTopicsSchemaTest.java
@@ -0,0 +1,107 @@
+/**
+ * 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.broker.service.schema;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.CompletableFuture;
+
+import org.apache.pulsar.broker.service.BrokerBkEnsemblesTests;
+import org.apache.pulsar.client.api.Consumer;
+import org.apache.pulsar.client.api.Message;
+import org.apache.pulsar.client.api.Producer;
+import org.apache.pulsar.client.api.PulsarClient;
+import org.apache.pulsar.client.api.Schema;
+import org.testng.annotations.Test;
+
+public class PartitionedTopicsSchemaTest extends BrokerBkEnsemblesTests {
+
+ /**
+ * Test that sequence id from a producer is correct when there are send errors
+ */
+ @Test
+ public void partitionedTopicWithSchema() throws Exception {
+ admin.namespaces().createNamespace("prop/my-test", Collections.singleton("usc"));
+
+ String topicName = "prop/my-test/my-topic";
+
+ admin.topics().createPartitionedTopic(topicName, 16);
+
+ int N = 10;
+
+ PulsarClient client = PulsarClient.builder().serviceUrl("pulsar://localhost:" + BROKER_SERVICE_PORT).build();
+
+ CompletableFuture<Producer<String>> producerFuture = client.newProducer(Schema.STRING).topic(topicName)
+ .createAsync();
+ CompletableFuture<Consumer<String>> consumerFuture = client.newConsumer(Schema.STRING).topic(topicName)
+ .subscriptionName("sub").subscribeAsync();
+
+ CompletableFuture.allOf(producerFuture, consumerFuture).get();
+
+ Producer<String> producer = producerFuture.get();
+ Consumer<String> consumer = consumerFuture.get();
+
+ for (int i = 0; i < N; i++) {
+ producer.send("Hello-" + i);
+ }
+
+ consumer.close();
+ producer.close();
+
+ // Force topic reloading to re-open the schema multiple times in parallel
+ admin.namespaces().unload("prop/my-test");
+
+ producerFuture = client.newProducer(Schema.STRING).topic(topicName).createAsync();
+ consumerFuture = client.newConsumer(Schema.STRING).topic(topicName).subscriptionName("sub").subscribeAsync();
+
+ // Re-opening the topic should succeed
+ CompletableFuture.allOf(producerFuture, consumerFuture).get();
+
+ consumer = consumerFuture.get();
+
+ Set<String> messages = new TreeSet<>();
+
+ for (int i = 0; i < N; i++) {
+ Message<String> msg = consumer.receive();
+ messages.add(msg.getValue());
+ consumer.acknowledge(msg);
+ }
+
+ assertEquals(messages.size(), N);
+ for (int i = 0; i < N; i++) {
+ assertTrue(messages.contains("Hello-" + i));
+ }
+
+ client.close();
+ }
+
+ @Test(enabled = false)
+ public void testCrashBrokerWithoutCursorLedgerLeak() throws Exception {
+ // Ignore test
+ }
+
+ @Test(enabled = false)
+ public void testSkipCorruptDataLedger() throws Exception {
+ // Ignore test
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/SchemaServiceTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/SchemaServiceTest.java
index 3c1a2d3cdd..98afe88bde 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/SchemaServiceTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/schema/SchemaServiceTest.java
@@ -25,6 +25,7 @@
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
+import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
@@ -48,6 +49,7 @@
.timestamp(MockClock.millis())
.isDeleted(false)
.data("message { required int64 a = 1};".getBytes())
+ .props(new TreeMap<>())
.build();
private SchemaData schema2 = SchemaData.builder()
@@ -56,6 +58,7 @@
.timestamp(MockClock.millis())
.isDeleted(false)
.data("message { required int64 b = 1};".getBytes())
+ .props(new TreeMap<>())
.build();
private SchemaData schema3 = SchemaData.builder()
@@ -64,6 +67,7 @@
.timestamp(MockClock.millis())
.isDeleted(false)
.data("message { required int64 c = 1};".getBytes())
+ .props(new TreeMap<>())
.build();
private SchemaRegistryServiceImpl schemaRegistryService;
@@ -247,6 +251,7 @@ private SchemaData randomSchema() {
.timestamp(MockClock.millis())
.isDeleted(false)
.data(randomString.toString().getBytes())
+ .props(new TreeMap<>())
.build();
}
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on 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
With regards,
Apache Git Services