use of org.apache.pulsar.client.api.Reader in project incubator-pulsar by apache.
the class FunctionMetaDataManager method initialize.
/**
* Public methods. Please use these methods if references FunctionMetaManager from an external class
*/
/**
* Initializes the FunctionMetaDataManager. Does the following:
* 1. Restores from snapshot if one exists
* 2. Sends out initialize marker to FMT and consume messages until the initialize marker is consumed
*/
public void initialize() {
log.info("/** Initializing Function Metadata Manager **/");
try {
Reader reader = pulsarClient.newReader().topic(this.workerConfig.getFunctionMetadataTopic()).startMessageId(MessageId.earliest).create();
this.functionMetaDataTopicTailer = new FunctionMetaDataTopicTailer(this, reader);
// read all existing messages
this.setInitializePhase(true);
while (reader.hasMessageAvailable()) {
this.functionMetaDataTopicTailer.processRequest(reader.readNext());
}
this.setInitializePhase(false);
// schedule functions if necessary
this.schedulerManager.schedule();
// start function metadata tailer
this.functionMetaDataTopicTailer.start();
} catch (Exception e) {
log.error("Failed to initialize meta data store: ", e.getMessage(), e);
throw new RuntimeException(e);
}
}
use of org.apache.pulsar.client.api.Reader in project incubator-pulsar by apache.
the class FunctionsImpl method triggerFunction.
@POST
@Path("/{tenant}/{namespace}/{functionName}/trigger")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response triggerFunction(@PathParam("tenant") final String tenant, @PathParam("namespace") final String namespace, @PathParam("name") final String functionName, @FormDataParam("data") final String input, @FormDataParam("dataStream") final InputStream uploadedInputStream) {
FunctionConfig functionConfig;
// validate parameters
try {
validateTriggerRequestParams(tenant, namespace, functionName, input, uploadedInputStream);
} catch (IllegalArgumentException e) {
log.error("Invalid trigger function request @ /{}/{}/{}", tenant, namespace, functionName, e);
return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON).entity(new ErrorData(e.getMessage())).build();
}
FunctionMetaDataManager functionMetaDataManager = worker().getFunctionMetaDataManager();
if (!functionMetaDataManager.containsFunction(tenant, namespace, functionName)) {
log.error("Function in getFunction does not exist @ /{}/{}/{}", tenant, namespace, functionName);
return Response.status(Status.NOT_FOUND).type(MediaType.APPLICATION_JSON).entity(new ErrorData(String.format("Function %s doesn't exist", functionName))).build();
}
FunctionMetaData functionMetaData = functionMetaDataManager.getFunctionMetaData(tenant, namespace, functionName);
String inputTopicToWrite;
if (functionMetaData.getFunctionConfig().getInputsList().size() > 0) {
inputTopicToWrite = functionMetaData.getFunctionConfig().getInputsList().get(0);
} else {
inputTopicToWrite = functionMetaData.getFunctionConfig().getCustomSerdeInputs().entrySet().iterator().next().getKey();
}
String outputTopic = functionMetaData.getFunctionConfig().getOutput();
Reader reader = null;
Producer producer = null;
try {
if (outputTopic != null && !outputTopic.isEmpty()) {
reader = worker().getClient().newReader().topic(outputTopic).startMessageId(MessageId.latest).create();
}
producer = worker().getClient().newProducer().topic(inputTopicToWrite).create();
byte[] targetArray;
if (uploadedInputStream != null) {
targetArray = new byte[uploadedInputStream.available()];
uploadedInputStream.read(targetArray);
} else {
targetArray = input.getBytes();
}
MessageId msgId = producer.send(targetArray);
if (reader == null) {
return Response.status(Status.OK).build();
}
long curTime = System.currentTimeMillis();
long maxTime = curTime + 1000;
while (curTime < maxTime) {
Message msg = reader.readNext(10000, TimeUnit.MILLISECONDS);
if (msg == null)
break;
if (msg.getProperties().containsKey("__pfn_input_msg_id__") && msg.getProperties().containsKey("__pfn_input_topic__")) {
MessageId newMsgId = MessageId.fromByteArray(Base64.getDecoder().decode((String) msg.getProperties().get("__pfn_input_msg_id__")));
if (msgId.equals(newMsgId) && msg.getProperties().get("__pfn_input_topic__").equals(inputTopicToWrite)) {
return Response.status(Status.OK).entity(msg.getData()).build();
}
}
curTime = System.currentTimeMillis();
}
return Response.status(Status.REQUEST_TIMEOUT).build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
} finally {
if (reader != null) {
reader.closeAsync();
}
if (producer != null) {
producer.closeAsync();
}
}
}
use of org.apache.pulsar.client.api.Reader in project incubator-pulsar by apache.
the class PerformanceReader method main.
public static void main(String[] args) throws Exception {
final Arguments arguments = new Arguments();
JCommander jc = new JCommander(arguments);
jc.setProgramName("pulsar-perf-reader");
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 reader 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;
ReaderListener<byte[]> listener = (reader, msg) -> {
messagesReceived.increment();
bytesReceived.add(msg.getData().length);
if (limiter != null) {
limiter.acquire();
}
};
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();
List<CompletableFuture<Reader<byte[]>>> futures = Lists.newArrayList();
MessageId startMessageId;
if ("earliest".equals(arguments.startMessageId)) {
startMessageId = MessageId.earliest;
} else if ("latest".equals(arguments.startMessageId)) {
startMessageId = MessageId.latest;
} else {
String[] parts = arguments.startMessageId.split(":");
startMessageId = new MessageIdImpl(Long.parseLong(parts[0]), Long.parseLong(parts[1]), -1);
}
ReaderBuilder<byte[]> readerBuilder = //
pulsarClient.newReader().readerListener(//
listener).receiverQueueSize(//
arguments.receiverQueueSize).startMessageId(startMessageId);
for (int i = 0; i < arguments.numTopics; i++) {
final TopicName topicName = (arguments.numTopics == 1) ? prefixTopicName : TopicName.get(String.format("%s-%d", prefixTopicName, i));
futures.add(readerBuilder.clone().topic(topicName.toString()).createAsync());
}
FutureUtil.waitForAll(futures).get();
log.info("Start reading from {} topics", arguments.numTopics);
long oldTime = System.nanoTime();
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;
log.info("Read throughput: {} msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
oldTime = now;
}
pulsarClient.close();
}
use of org.apache.pulsar.client.api.Reader in project incubator-pulsar by apache.
the class TopicTerminationTest method testSimpleTerminationReaderListener.
@Test(timeOut = 20000)
public void testSimpleTerminationReaderListener() throws Exception {
Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
CountDownLatch latch = new CountDownLatch(1);
Reader<byte[]> reader = pulsarClient.newReader().topic(topicName).startMessageId(MessageId.latest).readerListener(new ReaderListener<byte[]>() {
@Override
public void received(Reader<byte[]> reader, Message<byte[]> msg) {
// do nothing
}
@Override
public void reachedEndOfTopic(Reader<byte[]> reader) {
latch.countDown();
assertTrue(reader.hasReachedEndOfTopic());
}
}).create();
/* MessageId msgId1 = */
producer.send("test-msg-1".getBytes());
/* MessageId msgId2 = */
producer.send("test-msg-2".getBytes());
MessageId msgId3 = producer.send("test-msg-3".getBytes());
Thread.sleep(100);
assertFalse(reader.hasReachedEndOfTopic());
MessageId lastMessageId = admin.persistentTopics().terminateTopicAsync(topicName).get();
assertEquals(lastMessageId, msgId3);
assertTrue(latch.await(3, TimeUnit.SECONDS));
assertTrue(reader.hasReachedEndOfTopic());
}
Aggregations