use of org.apache.pulsar.common.naming.TopicName in project incubator-pulsar by apache.
the class PulsarAuthorizationProvider method canConsumeAsync.
/**
* Check if the specified role has permission to receive messages from the specified fully qualified topic
* name.
*
* @param topicName
* the fully qualified topic name associated with the topic.
* @param role
* the app id used to receive messages from the topic.
* @param subscription
* the subscription name defined by the client
*/
@Override
public CompletableFuture<Boolean> canConsumeAsync(TopicName topicName, String role, AuthenticationDataSource authenticationData, String subscription) {
CompletableFuture<Boolean> permissionFuture = new CompletableFuture<>();
try {
configCache.policiesCache().getAsync(POLICY_ROOT + topicName.getNamespace()).thenAccept(policies -> {
if (!policies.isPresent()) {
if (log.isDebugEnabled()) {
log.debug("Policies node couldn't be found for topic : {}", topicName);
}
} else {
if (isNotBlank(subscription) && !isSuperUser(role)) {
switch(policies.get().subscription_auth_mode) {
case Prefix:
if (!subscription.startsWith(role)) {
PulsarServerException ex = new PulsarServerException(String.format("Failed to create consumer - The subscription name needs to be prefixed by the authentication role, like %s-xxxx for topic: %s", role, topicName));
permissionFuture.completeExceptionally(ex);
return;
}
break;
default:
break;
}
}
}
checkAuthorization(topicName, role, AuthAction.consume).thenAccept(isAuthorized -> {
permissionFuture.complete(isAuthorized);
});
}).exceptionally(ex -> {
log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName, ex.getMessage());
permissionFuture.completeExceptionally(ex);
return null;
});
} catch (Exception e) {
log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName, e.getMessage());
permissionFuture.completeExceptionally(e);
}
return permissionFuture;
}
use of org.apache.pulsar.common.naming.TopicName in project incubator-pulsar by apache.
the class PerformanceConsumer method main.
public static void main(String[] args) throws Exception {
final Arguments arguments = new Arguments();
JCommander jc = new JCommander(arguments);
jc.setProgramName("pulsar-perf-consumer");
try {
jc.parse(args);
} catch (ParameterException e) {
System.out.println(e.getMessage());
jc.usage();
System.exit(-1);
}
if (arguments.help) {
jc.usage();
System.exit(-1);
}
if (arguments.topic.size() != 1) {
System.out.println("Only one topic name is allowed");
jc.usage();
System.exit(-1);
}
if (arguments.confFile != null) {
Properties prop = new Properties(System.getProperties());
prop.load(new FileInputStream(arguments.confFile));
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("brokerServiceUrl");
}
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("webServiceUrl");
}
// fallback to previous-version serviceUrl property to maintain backward-compatibility
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
}
if (arguments.authPluginClassName == null) {
arguments.authPluginClassName = prop.getProperty("authPlugin", null);
}
if (arguments.authParams == null) {
arguments.authParams = prop.getProperty("authParams", null);
}
if (arguments.useTls == false) {
arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
}
if (isBlank(arguments.tlsTrustCertsFilePath)) {
arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
}
}
// Dump config variables
ObjectMapper m = new ObjectMapper();
ObjectWriter w = m.writerWithDefaultPrettyPrinter();
log.info("Starting Pulsar performance consumer with config: {}", w.writeValueAsString(arguments));
final TopicName prefixTopicName = TopicName.get(arguments.topic.get(0));
final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;
MessageListener<byte[]> listener = (consumer, msg) -> {
messagesReceived.increment();
bytesReceived.add(msg.getData().length);
if (limiter != null) {
limiter.acquire();
}
long latencyMillis = System.currentTimeMillis() - msg.getPublishTime();
if (latencyMillis >= 0) {
recorder.recordValue(latencyMillis);
cumulativeRecorder.recordValue(latencyMillis);
}
consumer.acknowledgeAsync(msg);
};
ClientBuilder clientBuilder = //
PulsarClient.builder().serviceUrl(//
arguments.serviceURL).connectionsPerBroker(//
arguments.maxConnections).statsInterval(arguments.statsIntervalSeconds, //
TimeUnit.SECONDS).ioThreads(//
Runtime.getRuntime().availableProcessors()).enableTls(//
arguments.useTls).tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
if (isNotBlank(arguments.authPluginClassName)) {
clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
}
PulsarClient pulsarClient = clientBuilder.build();
class EncKeyReader implements CryptoKeyReader {
EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
EncKeyReader(byte[] value) {
keyInfo.setKey(value);
}
@Override
public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
return null;
}
@Override
public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
if (keyName.equals(arguments.encKeyName)) {
return keyInfo;
}
return null;
}
}
List<Future<Consumer<byte[]>>> futures = Lists.newArrayList();
ConsumerBuilder<byte[]> consumerBuilder = //
pulsarClient.newConsumer().messageListener(//
listener).receiverQueueSize(//
arguments.receiverQueueSize).subscriptionType(arguments.subscriptionType);
if (arguments.encKeyName != null) {
byte[] pKey = Files.readAllBytes(Paths.get(arguments.encKeyFile));
EncKeyReader keyReader = new EncKeyReader(pKey);
consumerBuilder.cryptoKeyReader(keyReader);
}
for (int i = 0; i < arguments.numTopics; i++) {
final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
log.info("Adding {} consumers on topic {}", arguments.numConsumers, topicName);
for (int j = 0; j < arguments.numConsumers; j++) {
String subscriberName;
if (arguments.numConsumers > 1) {
subscriberName = String.format("%s-%d", arguments.subscriberName, j);
} else {
subscriberName = arguments.subscriberName;
}
futures.add(consumerBuilder.clone().topic(topicName.toString()).subscriptionName(subscriberName).subscribeAsync());
}
}
for (Future<Consumer<byte[]>> future : futures) {
future.get();
}
log.info("Start receiving from {} consumers on {} topics", arguments.numConsumers, arguments.numTopics);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
printAggregatedStats();
}
});
long oldTime = System.nanoTime();
Histogram reportHistogram = null;
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
break;
}
long now = System.nanoTime();
double elapsed = (now - oldTime) / 1e9;
double rate = messagesReceived.sumThenReset() / elapsed;
double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;
reportHistogram = recorder.getIntervalHistogram(reportHistogram);
log.info("Throughput received: {} msg/s -- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}", dec.format(rate), dec.format(throughput), dec.format(reportHistogram.getMean()), (long) reportHistogram.getValueAtPercentile(50), (long) reportHistogram.getValueAtPercentile(95), (long) reportHistogram.getValueAtPercentile(99), (long) reportHistogram.getValueAtPercentile(99.9), (long) reportHistogram.getValueAtPercentile(99.99), (long) reportHistogram.getMaxValue());
reportHistogram.reset();
oldTime = now;
}
pulsarClient.close();
}
use of org.apache.pulsar.common.naming.TopicName in project incubator-pulsar by apache.
the class CliCommand method validatePersistentTopic.
String validatePersistentTopic(List<String> params) {
String topic = checkArgument(params);
TopicName topicName = TopicName.get(topic);
if (topicName.getDomain() != TopicDomain.persistent) {
throw new ParameterException("Need to provide a persistent topic name");
}
return topicName.toString();
}
use of org.apache.pulsar.common.naming.TopicName in project incubator-pulsar by apache.
the class PulsarKafkaConsumer method poll.
@SuppressWarnings("unchecked")
@Override
public ConsumerRecords<K, V> poll(long timeoutMillis) {
try {
QueueItem item = receivedMessages.poll(timeoutMillis, TimeUnit.MILLISECONDS);
if (item == null) {
return (ConsumerRecords<K, V>) ConsumerRecords.EMPTY;
}
Map<TopicPartition, List<ConsumerRecord<K, V>>> records = new HashMap<>();
int numberOfRecords = 0;
while (item != null && ++numberOfRecords < MAX_RECORDS_IN_SINGLE_POLL) {
TopicName topicName = TopicName.get(item.consumer.getTopic());
String topic = topicName.getPartitionedTopicName();
int partition = topicName.isPartitioned() ? topicName.getPartitionIndex() : 0;
Message<byte[]> msg = item.message;
MessageIdImpl msgId = (MessageIdImpl) msg.getMessageId();
long offset = MessageIdUtils.getOffset(msgId);
TopicPartition tp = new TopicPartition(topic, partition);
K key = getKey(topic, msg);
V value = valueDeserializer.deserialize(topic, msg.getData());
TimestampType timestampType = TimestampType.LOG_APPEND_TIME;
long timestamp = msg.getPublishTime();
if (msg.getEventTime() > 0) {
// If we have Event time, use that in preference
timestamp = msg.getEventTime();
timestampType = TimestampType.CREATE_TIME;
}
ConsumerRecord<K, V> consumerRecord = new ConsumerRecord<>(topic, partition, offset, timestamp, timestampType, -1, msg.hasKey() ? msg.getKey().length() : 0, msg.getData().length, key, value);
records.computeIfAbsent(tp, k -> new ArrayList<>()).add(consumerRecord);
// Update last offset seen by application
lastReceivedOffset.put(tp, offset);
// Check if we have an item already available
item = receivedMessages.poll(0, TimeUnit.MILLISECONDS);
}
if (isAutoCommit) {
// Commit the offset of previously dequeued messages
commitAsync();
}
return new ConsumerRecords<>(records);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
use of org.apache.pulsar.common.naming.TopicName in project incubator-pulsar by apache.
the class NonPersistentTopicsImpl method getInternalStatsAsync.
@Override
public CompletableFuture<PersistentTopicInternalStats> getInternalStatsAsync(String topic) {
TopicName topicName = validateTopic(topic);
final CompletableFuture<PersistentTopicInternalStats> future = new CompletableFuture<>();
WebTarget path = topicPath(topicName, "internalStats");
asyncGetRequest(path, new InvocationCallback<PersistentTopicInternalStats>() {
@Override
public void completed(PersistentTopicInternalStats response) {
future.complete(response);
}
@Override
public void failed(Throwable throwable) {
future.completeExceptionally(getApiException(throwable.getCause()));
}
});
return future;
}
Aggregations