forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
312 lines (272 loc) · 8.49 KB
/
input.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package pulsar
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/public/service"
)
const (
defaultSubscriptionType = "shared"
)
func init() {
err := service.RegisterInput(
"pulsar",
inputConfigSpec(),
func(conf *service.ParsedConfig, mgr *service.Resources) (service.Input, error) {
return newPulsarReaderFromParsed(conf, mgr.Logger())
})
if err != nil {
panic(err)
}
}
func inputConfigSpec() *service.ConfigSpec {
return service.NewConfigSpec().
Version("3.43.0").
Categories("Services").
Summary("Reads messages from an Apache Pulsar server.").
Description(`
### Metadata
This input adds the following metadata fields to each message:
` + "```text" + `
- pulsar_message_id
- pulsar_key
- pulsar_ordering_key
- pulsar_event_time_unix
- pulsar_publish_time_unix
- pulsar_topic
- pulsar_producer_name
- pulsar_redelivery_count
- All properties of the message
` + "```" + `
You can access these metadata fields using
[function interpolation](/docs/configuration/interpolation#bloblang-queries).
`).
Field(service.NewURLField("url").
Description("A URL to connect to.").
Example("pulsar://localhost:6650").
Example("pulsar://pulsar.us-west.example.com:6650").
Example("pulsar+ssl://pulsar.us-west.example.com:6651")).
Field(service.NewStringListField("topics").
Description("A list of topics to subscribe to. This or topics_pattern must be set.").
Optional()).
Field(service.NewStringField("topics_pattern").
Description("A regular expression matching the topics to subscribe to. This or topics must be set.").
Optional()).
Field(service.NewStringField("subscription_name").
Description("Specify the subscription name for this consumer.")).
Field(service.NewStringEnumField("subscription_type", "shared", "key_shared", "failover", "exclusive").
Description("Specify the subscription type for this consumer.\n\n> NOTE: Using a `key_shared` subscription type will __allow out-of-order delivery__ since nack-ing messages sets non-zero nack delivery delay - this can potentially cause consumers to stall. See [Pulsar documentation](https://pulsar.apache.org/docs/en/2.8.1/concepts-messaging/#negative-acknowledgement) and [this Github issue](https://github.com/apache/pulsar/issues/12208) for more details.").
Default(defaultSubscriptionType)).
Field(service.NewObjectField("tls",
service.NewStringField("root_cas_file").
Description("An optional path of a root certificate authority file to use. This is a file, often with a .pem extension, containing a certificate chain from the parent trusted root certificate, to possible intermediate signing certificates, to the host certificate.").
Default("").
Example("./root_cas.pem")).
Description("Specify the path to a custom CA certificate to trust broker TLS service.")).
Field(authField())
}
//------------------------------------------------------------------------------
type pulsarReader struct {
client pulsar.Client
consumer pulsar.Consumer
m sync.RWMutex
log *service.Logger
authConf authConfig
url string
topics []string
topicsPattern string
subName string
subType string
rootCasFile string
}
func newPulsarReaderFromParsed(conf *service.ParsedConfig, log *service.Logger) (p *pulsarReader, err error) {
p = &pulsarReader{
log: log,
}
if p.authConf, err = authFromParsed(conf); err != nil {
return
}
if p.url, err = conf.FieldString("url"); err != nil {
return
}
if p.topics, _ = conf.FieldStringList("topics"); err != nil {
return
}
if p.topicsPattern, _ = conf.FieldString("topics_pattern"); err != nil {
return
}
if p.subName, err = conf.FieldString("subscription_name"); err != nil {
return
}
if p.subType, err = conf.FieldString("subscription_type"); err != nil {
return
}
if p.rootCasFile, err = conf.FieldString("tls", "root_cas_file"); err != nil {
return
}
if p.url == "" {
err = errors.New("field url must not be empty")
return
}
if len(p.topics) == 0 && len(p.topicsPattern) == 0 ||
len(p.topics) != 0 && len(p.topicsPattern) != 0 {
err = errors.New("exactly one of fields topics and topics_pattern must be set")
return
}
if p.subName == "" {
err = errors.New("field subscription_name must not be empty")
return
}
if p.subType == "" {
p.subType = defaultSubscriptionType // set default subscription type if empty
}
if _, err = parseSubscriptionType(p.subType); err != nil {
err = fmt.Errorf("field subscription_type is invalid: %v", err)
return
}
if err = p.authConf.Validate(); err != nil {
err = fmt.Errorf("field auth is invalid: %v", err)
}
return
}
func parseSubscriptionType(subType string) (pulsar.SubscriptionType, error) {
// Pulsar docs: https://pulsar.apache.org/docs/en/2.8.0/concepts-messaging/#subscriptions
switch subType {
case "shared":
return pulsar.Shared, nil
case "key_shared":
return pulsar.KeyShared, nil
case "failover":
return pulsar.Failover, nil
case "exclusive":
return pulsar.Exclusive, nil
}
return pulsar.Shared, fmt.Errorf("could not parse subscription type: %s", subType)
}
//------------------------------------------------------------------------------
func (p *pulsarReader) Connect(ctx context.Context) error {
p.m.Lock()
defer p.m.Unlock()
if p.client != nil {
return nil
}
var (
client pulsar.Client
consumer pulsar.Consumer
subType pulsar.SubscriptionType
err error
)
opts := pulsar.ClientOptions{
Logger: createDefaultLogger(p.log),
ConnectionTimeout: time.Second * 3,
URL: p.url,
TLSTrustCertsFilePath: p.rootCasFile,
}
if p.authConf.OAuth2.Enabled {
opts.Authentication = pulsar.NewAuthenticationOAuth2(p.authConf.OAuth2.ToMap())
} else if p.authConf.Token.Enabled {
opts.Authentication = pulsar.NewAuthenticationToken(p.authConf.Token.Token)
}
if client, err = pulsar.NewClient(opts); err != nil {
return err
}
if subType, err = parseSubscriptionType(p.subType); err != nil {
return err
}
options := pulsar.ConsumerOptions{
Topics: p.topics,
TopicsPattern: p.topicsPattern,
SubscriptionName: p.subName,
Type: subType,
KeySharedPolicy: &pulsar.KeySharedPolicy{
AllowOutOfOrderDelivery: true,
},
}
if consumer, err = client.Subscribe(options); err != nil {
client.Close()
return err
}
p.client = client
p.consumer = consumer
p.log.Infof("Receiving Pulsar messages to URL: %v\n", p.url)
return nil
}
func (p *pulsarReader) disconnect(ctx context.Context) error {
p.m.Lock()
defer p.m.Unlock()
if p.client == nil {
return nil
}
p.consumer.Close()
p.client.Close()
p.consumer = nil
p.client = nil
return nil
}
func (p *pulsarReader) Read(ctx context.Context) (*service.Message, service.AckFunc, error) {
var r pulsar.Consumer
p.m.RLock()
if p.consumer != nil {
r = p.consumer
}
p.m.RUnlock()
if r == nil {
return nil, nil, component.ErrNotConnected
}
// Receive next message
pulMsg, err := r.Receive(ctx)
if err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
err = component.ErrTimeout
} else {
p.log.Errorf("Lost connection due to: %v\n", err)
_ = p.disconnect(ctx)
err = component.ErrNotConnected
}
return nil, nil, err
}
msg := service.NewMessage(pulMsg.Payload())
msg.MetaSet("pulsar_message_id", string(pulMsg.ID().Serialize()))
msg.MetaSet("pulsar_topic", pulMsg.Topic())
msg.MetaSet("pulsar_publish_time_unix", strconv.FormatInt(pulMsg.PublishTime().Unix(), 10))
msg.MetaSet("pulsar_redelivery_count", strconv.FormatInt(int64(pulMsg.RedeliveryCount()), 10))
if key := pulMsg.Key(); len(key) > 0 {
msg.MetaSet("pulsar_key", key)
}
if orderingKey := pulMsg.OrderingKey(); len(orderingKey) > 0 {
msg.MetaSet("pulsar_ordering_key", orderingKey)
}
if !pulMsg.EventTime().IsZero() {
msg.MetaSet("pulsar_event_time_unix", strconv.FormatInt(pulMsg.EventTime().Unix(), 10))
}
if producerName := pulMsg.ProducerName(); producerName != "" {
msg.MetaSet("pulsar_producer_name", producerName)
}
for k, v := range pulMsg.Properties() {
msg.MetaSet(k, v)
}
return msg, func(ctx context.Context, res error) error {
var r pulsar.Consumer
p.m.RLock()
if p.consumer != nil {
r = p.consumer
}
p.m.RUnlock()
if r != nil {
if res != nil {
r.Nack(pulMsg)
} else {
return r.Ack(pulMsg)
}
}
return nil
}, nil
}
func (p *pulsarReader) Close(ctx context.Context) error {
return p.disconnect(ctx)
}