Skip to content

Commit

Permalink
[feat][broker] PIP-264: Add transaction metrics (apache#22970)
Browse files Browse the repository at this point in the history
  • Loading branch information
dragosvictor authored Jun 27, 2024
1 parent 4ac9bc4 commit 4e535cb
Show file tree
Hide file tree
Showing 25 changed files with 678 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@
import org.apache.pulsar.broker.stats.OpenTelemetryProducerStats;
import org.apache.pulsar.broker.stats.OpenTelemetryReplicatorStats;
import org.apache.pulsar.broker.stats.OpenTelemetryTopicStats;
import org.apache.pulsar.broker.stats.OpenTelemetryTransactionCoordinatorStats;
import org.apache.pulsar.broker.stats.OpenTelemetryTransactionPendingAckStoreStats;
import org.apache.pulsar.broker.stats.PulsarBrokerOpenTelemetry;
import org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsServlet;
import org.apache.pulsar.broker.stats.prometheus.PrometheusRawMetricsProvider;
Expand Down Expand Up @@ -263,6 +265,8 @@ public class PulsarService implements AutoCloseable, ShutdownService {
private OpenTelemetryConsumerStats openTelemetryConsumerStats;
private OpenTelemetryProducerStats openTelemetryProducerStats;
private OpenTelemetryReplicatorStats openTelemetryReplicatorStats;
private OpenTelemetryTransactionCoordinatorStats openTelemetryTransactionCoordinatorStats;
private OpenTelemetryTransactionPendingAckStoreStats openTelemetryTransactionPendingAckStoreStats;

private TransactionMetadataStoreService transactionMetadataStoreService;
private TransactionBufferProvider transactionBufferProvider;
Expand Down Expand Up @@ -684,6 +688,14 @@ public CompletableFuture<Void> closeAsync() {
brokerClientSharedTimer.stop();
monotonicSnapshotClock.close();

if (openTelemetryTransactionPendingAckStoreStats != null) {
openTelemetryTransactionPendingAckStoreStats.close();
openTelemetryTransactionPendingAckStoreStats = null;
}
if (openTelemetryTransactionCoordinatorStats != null) {
openTelemetryTransactionCoordinatorStats.close();
openTelemetryTransactionCoordinatorStats = null;
}
if (openTelemetryReplicatorStats != null) {
openTelemetryReplicatorStats.close();
openTelemetryReplicatorStats = null;
Expand Down Expand Up @@ -996,6 +1008,9 @@ public void start() throws PulsarServerException {
.newProvider(config.getTransactionBufferProviderClassName());
transactionPendingAckStoreProvider = TransactionPendingAckStoreProvider
.newProvider(config.getTransactionPendingAckStoreProviderClassName());

openTelemetryTransactionCoordinatorStats = new OpenTelemetryTransactionCoordinatorStats(this);
openTelemetryTransactionPendingAckStoreStats = new OpenTelemetryTransactionPendingAckStoreStats(this);
}

this.metricsGenerator = new MetricsGenerator(this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ public class PersistentTopicAttributes extends TopicAttributes {
private final Attributes transactionCommittedAttributes;
private final Attributes transactionAbortedAttributes;

private final Attributes transactionBufferClientCommitSucceededAttributes;
private final Attributes transactionBufferClientCommitFailedAttributes;
private final Attributes transactionBufferClientAbortSucceededAttributes;
private final Attributes transactionBufferClientAbortFailedAttributes;

public PersistentTopicAttributes(TopicName topicName) {
super(topicName);

Expand All @@ -61,6 +66,31 @@ public PersistentTopicAttributes(TopicName topicName) {
.putAll(OpenTelemetryAttributes.TransactionStatus.ABORTED.attributes)
.build();

transactionBufferClientCommitSucceededAttributes = Attributes.builder()
.putAll(commonAttributes)
.remove(OpenTelemetryAttributes.PULSAR_DOMAIN)
.putAll(OpenTelemetryAttributes.TransactionStatus.COMMITTED.attributes)
.putAll(OpenTelemetryAttributes.TransactionBufferClientOperationStatus.SUCCESS.attributes)
.build();
transactionBufferClientCommitFailedAttributes = Attributes.builder()
.putAll(commonAttributes)
.remove(OpenTelemetryAttributes.PULSAR_DOMAIN)
.putAll(OpenTelemetryAttributes.TransactionStatus.COMMITTED.attributes)
.putAll(OpenTelemetryAttributes.TransactionBufferClientOperationStatus.FAILURE.attributes)
.build();
transactionBufferClientAbortSucceededAttributes = Attributes.builder()
.putAll(commonAttributes)
.remove(OpenTelemetryAttributes.PULSAR_DOMAIN)
.putAll(OpenTelemetryAttributes.TransactionStatus.ABORTED.attributes)
.putAll(OpenTelemetryAttributes.TransactionBufferClientOperationStatus.SUCCESS.attributes)
.build();
transactionBufferClientAbortFailedAttributes = Attributes.builder()
.putAll(commonAttributes)
.remove(OpenTelemetryAttributes.PULSAR_DOMAIN)
.putAll(OpenTelemetryAttributes.TransactionStatus.ABORTED.attributes)
.putAll(OpenTelemetryAttributes.TransactionBufferClientOperationStatus.FAILURE.attributes)
.build();

compactionSuccessAttributes = Attributes.builder()
.putAll(commonAttributes)
.putAll(OpenTelemetryAttributes.CompactionStatus.SUCCESS.attributes)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import lombok.Getter;
import org.apache.bookkeeper.mledger.AsyncCallbacks;
import org.apache.bookkeeper.mledger.AsyncCallbacks.ClearBacklogCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCallback;
Expand Down Expand Up @@ -128,6 +129,7 @@ public class PersistentSubscription extends AbstractSubscription {
private static final Map<String, Long> NON_REPLICATED_SUBSCRIPTION_CURSOR_PROPERTIES = Map.of();

private volatile ReplicatedSubscriptionSnapshotCache replicatedSubscriptionSnapshotCache;
@Getter
private final PendingAckHandle pendingAckHandle;
private volatile Map<String, String> subscriptionProperties;
private volatile CompletableFuture<Void> fenceFuture;
Expand Down Expand Up @@ -1439,11 +1441,6 @@ public ManagedCursor getCursor() {
return cursor;
}

@VisibleForTesting
public PendingAckHandle getPendingAckHandle() {
return pendingAckHandle;
}

public void syncBatchPositionBitSetForPendingAck(Position position) {
this.pendingAckHandle.syncBatchPositionAckSetForTransaction(position);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@
import java.util.concurrent.atomic.LongAdder;
import lombok.Getter;

@SuppressWarnings("LombokGetterMayBeUsed")
@Getter
public class PersistentTopicMetrics {

@Getter
private final BacklogQuotaMetrics backlogQuotaMetrics = new BacklogQuotaMetrics();

private final TransactionBufferClientMetrics transactionBufferClientMetrics = new TransactionBufferClientMetrics();

public static class BacklogQuotaMetrics {
private final LongAdder timeBasedBacklogQuotaExceededEvictionCount = new LongAdder();
private final LongAdder sizeBasedBacklogQuotaExceededEvictionCount = new LongAdder();
Expand All @@ -47,4 +48,13 @@ public long getTimeBasedBacklogQuotaExceededEvictionCount() {
return timeBasedBacklogQuotaExceededEvictionCount.longValue();
}
}

@Getter
public static class TransactionBufferClientMetrics {
private final LongAdder commitSucceededCount = new LongAdder();
private final LongAdder commitFailedCount = new LongAdder();

private final LongAdder abortSucceededCount = new LongAdder();
private final LongAdder abortFailedCount = new LongAdder();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ public class OpenTelemetryTopicStats implements AutoCloseable {
public static final String TRANSACTION_COUNTER = "pulsar.broker.topic.transaction.count";
private final ObservableLongMeasurement transactionCounter;

// Replaces ['pulsar_txn_tb_client_abort_failed_total', 'pulsar_txn_tb_client_commit_failed_total',
// 'pulsar_txn_tb_client_abort_latency', 'pulsar_txn_tb_client_commit_latency']
public static final String TRANSACTION_BUFFER_CLIENT_OPERATION_COUNTER =
"pulsar.broker.topic.transaction.buffer.client.operation.count";
private final ObservableLongMeasurement transactionBufferClientOperationCounter;

// Replaces pulsar_subscription_delayed
public static final String DELAYED_SUBSCRIPTION_COUNTER = "pulsar.broker.topic.subscription.delayed.entry.count";
private final ObservableLongMeasurement delayedSubscriptionCounter;
Expand Down Expand Up @@ -333,6 +339,12 @@ public OpenTelemetryTopicStats(PulsarService pulsar) {
.setDescription("The number of transactions on this topic.")
.buildObserver();

transactionBufferClientOperationCounter = meter
.counterBuilder(TRANSACTION_BUFFER_CLIENT_OPERATION_COUNTER)
.setUnit("{operation}")
.setDescription("The number of operations on the transaction buffer client.")
.buildObserver();

delayedSubscriptionCounter = meter
.upDownCounterBuilder(DELAYED_SUBSCRIPTION_COUNTER)
.setUnit("{entry}")
Expand Down Expand Up @@ -371,6 +383,7 @@ public OpenTelemetryTopicStats(PulsarService pulsar) {
compactionEntriesCounter,
compactionBytesCounter,
transactionCounter,
transactionBufferClientOperationCounter,
delayedSubscriptionCounter);
}

Expand Down Expand Up @@ -399,6 +412,8 @@ private void recordMetricsForTopic(Topic topic) {
}

if (topic instanceof PersistentTopic persistentTopic) {
var persistentTopicMetrics = persistentTopic.getPersistentTopicMetrics();

var persistentTopicAttributes = persistentTopic.getTopicAttributes();
var managedLedger = persistentTopic.getManagedLedger();
var managedLedgerStats = persistentTopic.getManagedLedger().getStats();
Expand All @@ -416,7 +431,7 @@ private void recordMetricsForTopic(Topic topic) {
topic.getBacklogQuota(BacklogQuota.BacklogQuotaType.message_age).getLimitTime(),
attributes);
backlogQuotaAge.record(topic.getBestEffortOldestUnacknowledgedMessageAgeSeconds(), attributes);
var backlogQuotaMetrics = persistentTopic.getPersistentTopicMetrics().getBacklogQuotaMetrics();
var backlogQuotaMetrics = persistentTopicMetrics.getBacklogQuotaMetrics();
backlogEvictionCounter.record(backlogQuotaMetrics.getSizeBasedBacklogQuotaExceededEvictionCount(),
persistentTopicAttributes.getSizeBasedQuotaAttributes());
backlogEvictionCounter.record(backlogQuotaMetrics.getTimeBasedBacklogQuotaExceededEvictionCount(),
Expand All @@ -430,6 +445,16 @@ private void recordMetricsForTopic(Topic topic) {
transactionCounter.record(txnBuffer.getAbortedTxnCount(),
persistentTopicAttributes.getTransactionAbortedAttributes());

var txnBufferClientMetrics = persistentTopicMetrics.getTransactionBufferClientMetrics();
transactionBufferClientOperationCounter.record(txnBufferClientMetrics.getCommitSucceededCount().sum(),
persistentTopicAttributes.getTransactionBufferClientCommitSucceededAttributes());
transactionBufferClientOperationCounter.record(txnBufferClientMetrics.getCommitFailedCount().sum(),
persistentTopicAttributes.getTransactionBufferClientCommitFailedAttributes());
transactionBufferClientOperationCounter.record(txnBufferClientMetrics.getAbortSucceededCount().sum(),
persistentTopicAttributes.getTransactionBufferClientAbortSucceededAttributes());
transactionBufferClientOperationCounter.record(txnBufferClientMetrics.getAbortFailedCount().sum(),
persistentTopicAttributes.getTransactionBufferClientAbortFailedAttributes());

Optional.ofNullable(pulsar.getNullableCompactor())
.map(Compactor::getStats)
.flatMap(compactorMXBean -> compactorMXBean.getCompactionRecordForTopic(topic.getName()))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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.stats;

import io.opentelemetry.api.metrics.BatchCallback;
import io.opentelemetry.api.metrics.ObservableLongMeasurement;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.transaction.coordinator.TransactionMetadataStore;

public class OpenTelemetryTransactionCoordinatorStats implements AutoCloseable {

// Replaces ['pulsar_txn_aborted_total',
// 'pulsar_txn_committed_total',
// 'pulsar_txn_created_total',
// 'pulsar_txn_timeout_total',
// 'pulsar_txn_active_count']
public static final String TRANSACTION_COUNTER = "pulsar.broker.transaction.coordinator.transaction.count";
private final ObservableLongMeasurement transactionCounter;

// Replaces pulsar_txn_append_log_total
public static final String APPEND_LOG_COUNTER = "pulsar.broker.transaction.coordinator.append.log.count";
private final ObservableLongMeasurement appendLogCounter;

private final BatchCallback batchCallback;

public OpenTelemetryTransactionCoordinatorStats(PulsarService pulsar) {
var meter = pulsar.getOpenTelemetry().getMeter();

transactionCounter = meter
.upDownCounterBuilder(TRANSACTION_COUNTER)
.setUnit("{transaction}")
.setDescription("The number of transactions handled by the coordinator.")
.buildObserver();

appendLogCounter = meter
.counterBuilder(APPEND_LOG_COUNTER)
.setUnit("{entry}")
.setDescription("The number of transaction metadata entries appended by the coordinator.")
.buildObserver();

batchCallback = meter.batchCallback(() -> {
var transactionMetadataStoreService = pulsar.getTransactionMetadataStoreService();
// Avoid NPE during Pulsar shutdown.
if (transactionMetadataStoreService != null) {
transactionMetadataStoreService.getStores()
.values()
.forEach(this::recordMetricsForTransactionMetadataStore);
}
},
transactionCounter,
appendLogCounter);
}

@Override
public void close() {
batchCallback.close();
}

private void recordMetricsForTransactionMetadataStore(TransactionMetadataStore transactionMetadataStore) {
var attributes = transactionMetadataStore.getAttributes();
var stats = transactionMetadataStore.getMetadataStoreStats();

transactionCounter.record(stats.getAbortedCount(), attributes.getTxnAbortedAttributes());
transactionCounter.record(stats.getActives(), attributes.getTxnActiveAttributes());
transactionCounter.record(stats.getCommittedCount(), attributes.getTxnCommittedAttributes());
transactionCounter.record(stats.getCreatedCount(), attributes.getTxnCreatedAttributes());
transactionCounter.record(stats.getTimeoutCount(), attributes.getTxnTimeoutAttributes());

appendLogCounter.record(stats.getAppendLogCount(), attributes.getCommonAttributes());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* 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.stats;

import io.opentelemetry.api.metrics.ObservableLongCounter;
import io.opentelemetry.api.metrics.ObservableLongMeasurement;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.service.Subscription;
import org.apache.pulsar.broker.service.Topic;
import org.apache.pulsar.broker.service.persistent.PersistentSubscription;

public class OpenTelemetryTransactionPendingAckStoreStats implements AutoCloseable {

// Replaces ['pulsar_txn_tp_committed_count_total', 'pulsar_txn_tp_aborted_count_total']
public static final String ACK_COUNTER = "pulsar.broker.transaction.pending.ack.store.transaction.count";
private final ObservableLongCounter ackCounter;

public OpenTelemetryTransactionPendingAckStoreStats(PulsarService pulsar) {
var meter = pulsar.getOpenTelemetry().getMeter();

ackCounter = meter
.counterBuilder(ACK_COUNTER)
.setUnit("{transaction}")
.setDescription("The number of transactions handled by the persistent ack store.")
.buildWithCallback(measurement -> pulsar.getBrokerService()
.getTopics()
.values()
.stream()
.filter(topicFuture -> topicFuture.isDone() && !topicFuture.isCompletedExceptionally())
.map(CompletableFuture::join)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(Topic::isPersistent)
.map(Topic::getSubscriptions)
.forEach(subs -> subs.forEach((__, sub) -> recordMetricsForSubscription(measurement, sub))));
}

@Override
public void close() {
ackCounter.close();
}

private void recordMetricsForSubscription(ObservableLongMeasurement measurement, Subscription subscription) {
assert subscription instanceof PersistentSubscription; // The topics have already been filtered for persistence.
var stats = ((PersistentSubscription) subscription).getPendingAckHandle().getPendingAckHandleStats();
if (stats != null) {
var attributes = stats.getAttributes();
measurement.record(stats.getCommitSuccessCount(), attributes.getCommitSuccessAttributes());
measurement.record(stats.getCommitFailedCount(), attributes.getCommitFailureAttributes());
measurement.record(stats.getAbortSuccessCount(), attributes.getAbortSuccessAttributes());
measurement.record(stats.getAbortFailedCount(), attributes.getAbortFailureAttributes());
}
}
}
Loading

0 comments on commit 4e535cb

Please sign in to comment.