Develop Pulsar Functions

    在 Java 和 Python 中,编写 Pulsar Functions 的方式有两种。 在 Go 中,可以使用 Pulsar Functions SDK。

    语言原生 function 没有外部依赖关系,该 function 为所有传入的字符串添加感叹号,并将结果发布到 topic。 语言原生 function示例如下。

    Java

    Python

    查看完整代码,请点击这里

    查看完整代码,请点击。

    sudo update-alternatives —install /usr/bin/python python /usr/bin/python3 10

    使用 Pulsar Functions SDK 的示例如下。

    Java

    Python

    Go

    1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;public class ExclamationFunction implements Function<String, String> { @Override public String process(String input, Context context) { return String.format("%s!", input); }}

    查看完整代码,请点击这里

    1. from pulsar import Functionclass ExclamationFunction(Function): def __init__(self): pass def process(self, input, context): return input + '!'

    查看完整代码,请点击。

    1. package mainimport ( "context" "fmt" "github.com/apache/pulsar/pulsar-function-go/pf")func HandleRequest(ctx context.Context, in []byte) error{ fmt.Println(string(in) + "!") return nil}func main() { pf.Start(HandleRequest)}

    查看完整代码,请点击这里

    Schema registry

    Pulsar 有一个内置的 schema registry,还有各种常用的 schema 类型(avro、json、protobuf)。 Pulsar Functions 可以利用输入 topic 中现有 schema 的信息,并派生出输入类型。 Schema registry 也适用于输出 topic。

    SerDe stands for Serialization and Deserialization. Pulsar Functions 使用 SerDe 向 Pulsar topic 发布数据或使用其中的数据。 默认情况下,SerDe 的工作方式取决于特定 function 所使用的语言。

    Java

    Python

    Go

    当使用 Java 编写 Pulsar Functions 时,默认内置以下基本 Java 类型:

    • String
    • Double
    • Integer
    • Float
    • Long
    • Short
    • Byte

    要自定义 Java 类型,需要实现以下接口。

      在 Python 中,默认的 SerDe 是 identity,即该类型将被序列化为 producer function 返回的类型。

      创建或 function 时,可以指定 SerDe。

      1. $ bin/pulsar-admin functions create \ --tenant public \ --namespace default \ --name my_function \ --py my_function.py \ --classname my_function.MyFunction \ --custom-serde-inputs '{"input-topic-1":"Serde1","input-topic-2":"Serde2"}' \ --output-serde-classname Serde3 \ --output output-topic-1

      此案例包含两个输入 topic:input-topic-1input-topic-2,它们分别映射到不同的 SerDe 类(映射必须指定为 JSON 字符串)。 The output topic, output-topic-1, uses the Serde3 class for SerDe. 目前,所有 Pulsar Functions 逻辑(包括处理函数和 SerDe 类)都必须包含在同一个 Python 文件中。

      在将 Pulsar Functions 用于 Python 时,有三个 SerDe 可供选择:

      1. You can use the IdentitySerde, which leaves the data unchanged. The IdentitySerDe is the default. 在未显式指定 SerDe 的情况下创建或运行 function 即使用此选项。
      2. 可以使用 ,将 Python pickle 用于 SerDe。
      3. You can create a custom SerDe class by implementing the baseline class, which has just two methods: serialize for converting the object into bytes, and for converting bytes into an object of the required application-specific type.

      下表显示了每个 SerDe 的使用情形。

      SerDe optionWhen to use
      IdentitySerde在使用简单类型(如:字符串、布尔值、整型)时。
      PickleSerDe在使用复杂的、特定于某应用程序的类型,并且适合于 pickle 的 “best effort”方法时。
      Custom SerDe在需要显示控制 SerDe 时,可能是出于性能或数据兼容性的考虑。

      当前,该功能在 Go 中不可用。

      Imagine that you’re writing Pulsar Functions that are processing tweet objects, you can refer to the following example of Tweet class.

      Java

      Python

      1. public class Tweet { private String username; private String tweetContent; public Tweet(String username, String tweetContent) { this.username = username; this.tweetContent = tweetContent; } // Standard setters and getters}

      To pass Tweet objects directly between Pulsar Functions, you need to provide a custom SerDe class. In the example below, Tweet objects are basically strings in which the username and tweet content are separated by a |.

      1. package com.example.serde;import org.apache.pulsar.functions.api.SerDe;import java.util.regex.Pattern;public class TweetSerde implements SerDe<Tweet> { public Tweet deserialize(byte[] input) { String s = new String(input); String[] fields = s.split(Pattern.quote("|")); return new Tweet(fields[0], fields[1]); } public byte[] serialize(Tweet input) { return "%s|%s".format(input.getUsername(), input.getTweetContent()).getBytes(); }}

      To apply this customized SerDe to a particular Pulsar Function, you need to:

      • TweetTweetSerde 类打包到一个 JAR 中。
      • 部署 function 时,指定 JAR 和 SerDe 类名称的路径。

      The following is an example of create operation.

      1. $ bin/pulsar-admin functions create \ --jar /path/to/your.jar \ --output-serde-classname com.example.serde.TweetSerde \ # Other function attributes

      Custom SerDe classes must be packaged with your function JARs

      Pulsar does not store your custom SerDe classes separately from your Pulsar Functions. 需要在 function JAR 中包含 SerDe 类。 否则,Pulsar 将返回错误。

      1. class Tweet(object): def __init__(self, username, tweet_content): self.username = username self.tweet_content = tweet_content

      In order to use this class in Pulsar Functions, you have two options:

      1. 可以指定 PickleSerDe,它将应用 pickle 库 SerDe.
      2. 可以自己创建 SerDe 类。 The following is an example.
      1. from pulsar import SerDeclass TweetSerDe(SerDe): def serialize(self, input): return bytes("{0}|{1}".format(input.username, input.tweet_content)) def deserialize(self, input_bytes): tweet_components = str(input_bytes).split('|') return Tweet(tweet_components[0], tweet_componentsp[1])

      For complete code, see .

      Context

      Java, Python and Go SDKs provide access to a context object that can be used by a function. 并提供了各种各样的信息和功能。

      • The name and ID of a Pulsar Function.
      • The message ID of each message. 每条 Pulsar 消息都会自动分配一个 ID。
      • The key, event time, properties and partition key of each message.
      • The name of the topic to which the message is sent.
      • The names of all input topics as well as the output topic associated with the function.
      • The name of the class used for .
      • The tenant and namespace associated with the function.
      • The ID of the Pulsar Functions instance running the function.
      • The version of the function.
      • The used by the function, which can be used to create function log messages.
      • Access to arbitrary user configuration values supplied via the CLI.
      • An interface for recording .
      • An interface for storing and retrieving state in state storage.
      • A function to publish new messages onto arbitrary topics.
      • A function to ack the message being processed (if auto-ack is disabled).

      Java

      Python

      Go

      The interface provides a number of methods that you can use to access the function context. The various method signatures for the Context interface are listed as follows.

      1. public interface Context { Record<?> getCurrentRecord(); Collection<String> getInputTopics(); String getOutputTopic(); String getOutputSchemaType(); String getTenant(); String getNamespace(); String getFunctionName(); String getFunctionId(); String getInstanceId(); String getFunctionVersion(); Logger getLogger(); void incrCounter(String key, long amount); long getCounter(String key); void putState(String key, ByteBuffer value); void deleteState(String key); ByteBuffer getState(String key); Map<String, Object> getUserConfigMap(); Optional<Object> getUserConfigValue(String key); Object getUserConfigValueOrDefault(String key, Object defaultValue); void recordMetric(String metricName, double value); <O> CompletableFuture<Void> publish(String topicName, O object, String schemaOrSerdeClassName); <O> CompletableFuture<Void> publish(String topicName, O object); <O> TypedMessageBuilder<O> newOutputMessage(String topicName, Schema<O> schema) throws PulsarClientException; <O> ConsumerBuilder<O> newConsumerBuilder(Schema<O> schema) throws PulsarClientException;}

      The following example uses several methods available via the Context object.

      1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;import org.slf4j.Logger;import java.util.stream.Collectors;public class ContextFunction implements Function<String, Void> { public Void process(String input, Context context) { Logger LOG = context.getLogger(); String inputTopics = context.getInputTopics().stream().collect(Collectors.joining(", ")); String functionName = context.getFunctionName(); String logMessage = String.format("A message with a value of \"%s\" has arrived on one of the following topics: %s\n", input, inputTopics); LOG.info(logMessage); String metricName = String.format("function-%s-messages-received", functionName); context.recordMetric(metricName, 1); return null; }}
      1. class ContextImpl(pulsar.Context): def get_message_id(self): ... def get_message_key(self): ... def get_message_eventtime(self): ... def get_message_properties(self): ... def get_current_message_topic_name(self): ... def get_partition_key(self): ... def get_function_name(self): ... def get_function_tenant(self): ... def get_function_namespace(self): ... def get_function_id(self): ... def get_instance_id(self): ... def get_function_version(self): ... def get_logger(self): ... def get_user_config_value(self, key): ... def get_user_config_map(self): ... def record_metric(self, metric_name, metric_value): ... def get_input_topics(self): ... def get_output_topic(self): ... def get_output_serde_class_name(self): ... def publish(self, topic_name, message, serde_class_name="serde.IdentitySerDe", properties=None, compression_type=None, callback=None, message_conf=None): ... def ack(self, msgid, topic): ... def get_and_reset_metrics(self): ... def reset_metrics(self): ... def get_metrics(self): ... def incr_counter(self, key, amount): ... def get_counter(self, key): ... def del_counter(self, key): ... def put_state(self, key, value): ... def get_state(self, key): ...

      The following example uses several methods available via the Context object.

      1. import ( "context" "fmt" "github.com/apache/pulsar/pulsar-function-go/pf")func contextFunc(ctx context.Context) { if fc, ok := pf.FromContext(ctx); ok { fmt.Printf("function ID is:%s, ", fc.GetFuncID()) fmt.Printf("function version is:%s\n", fc.GetFuncVersion()) }}

      For complete code, see .

      User config

      当你使用SDK 运行或者更新函数时,你能够通过--user-config参数传递任意的key/value格式的参数。 Key/values must be specified as JSON. The following function creation command passes a user configured key/value to a function.

      1. $ bin/pulsar-admin functions create \
      2. # Other function configs
      3. --user-config '{"forbidden-word":"rosebud"}'

      Java

      Python

      Go

      The Java SDK object enables you to access key/value pairs provided to Pulsar Functions via the command line (as JSON). The following example passes a key/value pair.

        To access that value in a Java function:

        1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;import org.slf4j.Logger;import java.util.Optional;public class UserConfigFunction implements Function<String, Void> { @Override public void apply(String input, Context context) { Logger LOG = context.getLogger(); Optional<String> wotd = context.getUserConfigValue("word-of-the-day"); if (wotd.isPresent()) { LOG.info("The word of the day is {}", wotd); } else { LOG.warn("No word of the day provided"); } return null; }}

        The UserConfigFunction function will log the string "The word of the day is verdure" every time the function is invoked (which means every time a message arrives). The word-of-the-day user config will be changed only when the function is updated with a new config value via the command line.

        You can also access the entire user config map or set a default value in case no value is present:

        1. // Get the whole config mapMap<String, String> allConfigs = context.getUserConfigMap();// Get value or resort to defaultString wotd = context.getUserConfigValueOrDefault("word-of-the-day", "perspicacious");

        In Python function, you can access the configuration value like this.

        1. from pulsar import Functionclass WordFilter(Function): def process(self, context, input): forbidden_word = context.user_config()["forbidden-word"] # Don't publish the message if it contains the user-supplied # forbidden word if forbidden_word in input: pass # Otherwise publish the message else: return input

        The Python SDK Context object enables you to access key/value pairs provided to Pulsar Functions via the command line (as JSON). The following example passes a key/value pair.

        1. $ bin/pulsar-admin functions create \ # Other function configs \ --user-config '{"word-of-the-day":"verdure"}'

        To access that value in a Python function:

        1. from pulsar import Functionclass UserConfigFunction(Function): def process(self, input, context): logger = context.get_logger() wotd = context.get_user_config_value('word-of-the-day') if wotd is None: logger.warn('No word of the day provided') else: logger.info("The word of the day is {0}".format(wotd))

        当前,该功能在 Go 中不可用。

        Java

        Python

        Go

        Pulsar Functions that use the Java SDK have access to an Logger object that can be used to produce logs at the chosen log level. The following example logs either a WARNING- or INFO-level log based on whether the incoming string contains the word danger.

        1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;import org.slf4j.Logger;public class LoggingFunction implements Function<String, Void> { @Override public void apply(String input, Context context) { Logger LOG = context.getLogger(); String messageId = new String(context.getMessageId()); if (input.contains("danger")) { LOG.warn("A warning was received in message {}", messageId); } else { LOG.info("Message {} received\nContent: {}", messageId, input); } return null; }}

        If you want your function to produce logs, you need to specify a log topic when creating or running the function. The following is an example.

        1. $ bin/pulsar-admin functions create \ --jar my-functions.jar \ --classname my.package.LoggingFunction \ --log-topic persistent://public/default/logging-function-logs \ # Other function configs

        All logs produced by LoggingFunction above can be accessed via the persistent://public/default/logging-function-logs topic.

        Pulsar Functions that use the Python SDK have access to a logging object that can be used to produce logs at the chosen log level. The following example function that logs either a WARNING- or INFO-level log based on whether the incoming string contains the word danger.

        1. from pulsar import Functionclass LoggingFunction(Function): def process(self, input, context): logger = context.get_logger() msg_id = context.get_message_id() if 'danger' in input: logger.warn("A warning was received in message {0}".format(context.get_message_id())) else: logger.info("Message {0} received\nContent: {1}".format(msg_id, input))

        If you want your function to produce logs on a Pulsar topic, you need to specify a log topic when creating or running the function. The following is an example.

        1. $ bin/pulsar-admin functions create \ --py logging_function.py \ --classname logging_function.LoggingFunction \ --log-topic logging-function-logs \ # Other function configs

        All logs produced by LoggingFunction above can be accessed via the logging-function-logs topic.

        The following Go Function example shows different log levels based on the function input.

        1. import ( "context" "github.com/apache/pulsar/pulsar-function-go/pf" log "github.com/apache/pulsar/pulsar-function-go/logutil")func loggerFunc(ctx context.Context, input []byte) { if len(input) <= 100 { log.Infof("This input has a length of: %d", len(input)) } else { log.Warnf("This input is getting too long! It has {%d} characters", len(input)) }}func main() { pf.Start(loggerFunc)}

        当你在 GO 函数里面使用logTopic相关函数时,需要导入github.com/apache/pulsar/pulsar-function-go/logutil包,这时你不必使用getLogger() 上下文对象。

        Pulsar Functions can publish arbitrary metrics to the metrics interface which can be queried.

        如果 Pulsar Function 使用 Java 或 Python 的语言本机接口,则该 function 无法将度量和统计信息发布到 Pulsar。

        Java

        Python

        Go

        You can record metrics using the object on a per-key basis. For example, you can set a metric for the process-count key and a different metric for the elevens-count key every time the function processes a message.

        1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;public class MetricRecorderFunction implements Function<Integer, Void> { @Override public void apply(Integer input, Context context) { // Records the metric 1 every time a message arrives context.recordMetric("hit-count", 1); // Records the metric only if the arriving number equals 11 if (input == 11) { context.recordMetric("elevens-count", 1); } return null; }}

        You can record metrics using the Context object on a per-key basis. For example, you can set a metric for the process-count key and a different metric for the elevens-count key every time the function processes a message. The following is an example.

        当前,该功能在 Go 中不可用。

        访问度量

        To access metrics created by Pulsar Functions, refer to Monitoring in Pulsar.

        安全

        如果你想在函数里面启用安全机制,首先你需要在Functions Workers上启用安全机制。 了解更多详情,参考

        Pulsar Function 可以支持如下的 provider:

        • ClearTextSecretsProvider
        • EnvironmentBasedSecretsProvider

        Pulsar Function 默认支持 ClearTextSecretsProvider。

        At the same time, Pulsar Functions provides two interfaces, SecretsProvider and SecretsProviderConfigurator, allowing users to customize secret provider.

        Java

        Python

        Go

        你能够使用Context 对象获取到安全 provider。 如下所示:

        1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;import org.slf4j.Logger;public class GetSecretProviderFunction implements Function<String, Void> { @Override public Void process(String input, Context context) throws Exception { Logger LOG = context.getLogger(); String secretProvider = context.getSecret(input); if (!secretProvider.isEmpty()) { LOG.info("The secret provider is {}", secretProvider); } else { LOG.warn("No secret provider"); } return null; }}

        你能够使用 对象获取到安全 provider。 如下所示:

        1. from pulsar import Functionclass GetSecretProviderFunction(Function): def process(self, input, context): logger = context.get_logger() secret_provider = context.get_secret(input) if secret_provider is None: logger.warn('No secret provider') else: logger.info("The secret provider is {0}".format(secret_provider))

        当前,该功能在 Go 中不可用。

        Pulsar Functions使用 Apache Bookerper 存储状态。 Pulsar installation, including the local standalone installation, includes deployment of BookKeeper bookies.

        Since Pulsar 2.1.0 release, Pulsar integrates with Apache BookKeeper to store the State for functions. For example, a WordCount function can store its counters state into BookKeeper table service via Pulsar Functions State API.

        States are key-value pairs, where the key is a string and the value is arbitrary binary data - counters are stored as 64-bit big-endian binary values. Keys are scoped to an individual Pulsar Function, and shared between instances of that function.

        You can access states within Pulsar Functions using the putState, getState, , getCounter and deleteState calls on the context object. You can also manage states using the querystate and options to pulsar-admin functions.

        Java

        Python

        Currently Pulsar Functions expose the following APIs for mutating and accessing State. These APIs are available in the Context object when you are using Java SDK functions.

        incrCounter

        1. /** * Increment the builtin distributed counter refered by key * @param key The name of the key * @param amount The amount to be incremented */ void incrCounter(String key, long amount);

        Application can use incrCounter to change the counter of a given key by the given amount.

        getCounter

        1. /** * Retrieve the counter value for the key. * * @param key name of the key * @return the amount of the counter value for this key */ long getCounter(String key);

        Application can use getCounter to retrieve the counter of a given key mutated by incrCounter.

        Except the counter API, Pulsar also exposes a general key/value API for functions to store general key/value state.

        putState

        1. /** * Update the state value for the key. * * @param key name of the key * @param value state value of the key */ void putState(String key, ByteBuffer value);

        getState

        1. /** * Retrieve the state value for the key. * * @param key name of the key * @return the state value for the key. */ ByteBuffer getState(String key);

        deleteState

        1. /** * Delete the state value for the key. * * @param key name of the key */

        Counters and binary values share the same keyspace, so this deletes either type.

        Currently Pulsar Functions expose the following APIs for mutating and accessing State. These APIs are available in the Context object when you are using Python SDK functions.

        incr_counter

        1. def incr_counter(self, key, amount): """incr the counter of a given key in the managed state"""

        Application can use incr_counter to change the counter of a given key by the given amount. If the key does not exist, a new key is created.

        get_counter

        1. def get_counter(self, key): """get the counter of a given key in the managed state"""

        Application can use get_counter to retrieve the counter of a given key mutated by incrCounter.

        Except the counter API, Pulsar also exposes a general key/value API for functions to store general key/value state.

        put_state

        1. def put_state(self, key, value): """update the value of a given key in the managed state"""

        The key is a string, and the value is arbitrary binary data.

        get_state

        1. def get_state(self, key): """get the value of a given key in the managed state"""

        del_counter

        1. def del_counter(self, key): """delete the counter of a given key in the managed state"""

        Counters and binary values share the same keyspace, so this deletes either type.

        Query State

        A Pulsar Function can use the for storing state into Pulsar’s state storage and retrieving state back from Pulsar’s state storage. Additionally Pulsar also provides CLI commands for querying its state.

        1. $ bin/pulsar-admin functions querystate \
        2. --tenant <tenant> \
        3. --namespace <namespace> \
        4. --name <function-name> \
        5. --state-storage-url <bookkeeper-service-url> \
        6. --key <state-key> \
        7. [---watch]

        If --watch is specified, the CLI will watch the value of the provided state-key.

        Java

        Python

        WordCountFunction is a very good example demonstrating on how Application can easily store state in Pulsar Functions.

        1. import org.apache.pulsar.functions.api.Context;import org.apache.pulsar.functions.api.Function;import java.util.Arrays;public class WordCountFunction implements Function<String, Void> { @Override public Void process(String input, Context context) throws Exception { Arrays.asList(input.split("\\.")).forEach(word -> context.incrCounter(word, 1)); return null; }}

        The logic of this WordCount function is pretty simple and straightforward:

        1. The function first splits the received String into multiple words using regex \\..
        2. For each word, the function increments the corresponding counter by 1 (via incrCounter(key, amount)).

        The logic of this WordCount function is pretty simple and straightforward:

        1. 该 function 首先将接收到的字符串拆分为多个单词。