forked from benthosdev/benthos
/
output.go
218 lines (186 loc) · 5.85 KB
/
output.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
package pulsar
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/dafanshu/benthos/v3/internal/bloblang/field"
"github.com/dafanshu/benthos/v3/internal/bundle"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/internal/impl/pulsar/auth"
"github.com/dafanshu/benthos/v3/internal/interop"
"github.com/dafanshu/benthos/v3/internal/shutdown"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/output"
"github.com/dafanshu/benthos/v3/lib/output/writer"
"github.com/dafanshu/benthos/v3/lib/types"
)
func init() {
bundle.AllOutputs.Add(bundle.OutputConstructorFromSimple(func(c output.Config, nm bundle.NewManagement) (output.Type, error) {
w, err := newPulsarWriter(c.Pulsar, nm, nm.Logger(), nm.Metrics())
if err != nil {
return nil, err
}
o, err := output.NewAsyncWriter(output.TypePulsar, c.Pulsar.MaxInFlight, w, nm.Logger(), nm.Metrics())
if err != nil {
return nil, err
}
return output.OnlySinglePayloads(o), nil
}), docs.ComponentSpec{
Name: output.TypePulsar,
Type: docs.TypeOutput,
Status: docs.StatusExperimental,
Version: "3.43.0",
Summary: `Write messages to an Apache Pulsar server.`,
Categories: []string{
string(output.CategoryServices),
},
Config: docs.FieldComponent().WithChildren(
docs.FieldCommon("url",
"A URL to connect to.",
"pulsar://localhost:6650",
"pulsar://pulsar.us-west.example.com:6650",
"pulsar+ssl://pulsar.us-west.example.com:6651",
),
docs.FieldCommon("topic", "A topic to publish to."),
docs.FieldCommon("key", "The key to publish messages with.").IsInterpolated(),
docs.FieldCommon("ordering_key", "The ordering key to publish messages with.").IsInterpolated(),
docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
auth.FieldSpec(),
).ChildDefaultAndTypesFromStruct(output.NewPulsarConfig()),
})
}
//------------------------------------------------------------------------------
type pulsarWriter struct {
client pulsar.Client
producer pulsar.Producer
conf output.PulsarConfig
stats metrics.Type
log log.Modular
key *field.Expression
orderingKey *field.Expression
m sync.RWMutex
shutSig *shutdown.Signaller
}
func newPulsarWriter(conf output.PulsarConfig, mgr types.Manager, log log.Modular, stats metrics.Type) (*pulsarWriter, error) {
var err error
var key, orderingKey *field.Expression
if conf.URL == "" {
return nil, errors.New("field url must not be empty")
}
if conf.Topic == "" {
return nil, errors.New("field topic must not be empty")
}
if key, err = interop.NewBloblangField(mgr, conf.Key); err != nil {
return nil, fmt.Errorf("failed to parse key expression: %v", err)
}
if orderingKey, err = interop.NewBloblangField(mgr, conf.OrderingKey); err != nil {
return nil, fmt.Errorf("failed to parse ordering_key expression: %v", err)
}
p := pulsarWriter{
conf: conf,
stats: stats,
log: log,
key: key,
orderingKey: orderingKey,
shutSig: shutdown.NewSignaller(),
}
return &p, nil
}
//------------------------------------------------------------------------------
// ConnectWithContext establishes a connection to an Pulsar server.
func (p *pulsarWriter) ConnectWithContext(ctx context.Context) error {
p.m.Lock()
defer p.m.Unlock()
if p.client != nil {
return nil
}
var (
client pulsar.Client
producer pulsar.Producer
err error
)
opts := pulsar.ClientOptions{
Logger: DefaultLogger(p.log),
ConnectionTimeout: time.Second * 3,
URL: p.conf.URL,
}
if p.conf.Auth.OAuth2.Enabled {
opts.Authentication = pulsar.NewAuthenticationOAuth2(p.conf.Auth.OAuth2.ToMap())
} else if p.conf.Auth.Token.Enabled {
opts.Authentication = pulsar.NewAuthenticationToken(p.conf.Auth.Token.Token)
}
if client, err = pulsar.NewClient(opts); err != nil {
return err
}
if producer, err = client.CreateProducer(pulsar.ProducerOptions{
Topic: p.conf.Topic,
}); err != nil {
client.Close()
return err
}
p.client = client
p.producer = producer
p.log.Infof("Writing Pulsar messages to URL: %v\n", p.conf.URL)
return nil
}
// disconnect safely closes a connection to an Pulsar server.
func (p *pulsarWriter) disconnect(ctx context.Context) error {
p.m.Lock()
defer p.m.Unlock()
if p.client == nil {
return nil
}
p.producer.Close()
p.client.Close()
p.producer = nil
p.client = nil
if p.shutSig.ShouldCloseAtLeisure() {
p.shutSig.ShutdownComplete()
}
return nil
}
//------------------------------------------------------------------------------
// WriteWithContext will attempt to write a message over Pulsar, wait for
// acknowledgement, and returns an error if applicable.
func (p *pulsarWriter) WriteWithContext(ctx context.Context, msg types.Message) error {
var r pulsar.Producer
p.m.RLock()
if p.producer != nil {
r = p.producer
}
p.m.RUnlock()
if r == nil {
return types.ErrNotConnected
}
return writer.IterateBatchedSend(msg, func(i int, part types.Part) error {
m := &pulsar.ProducerMessage{
Payload: part.Get(),
}
if key := p.key.Bytes(i, msg); len(key) > 0 {
m.Key = string(key)
}
if orderingKey := p.orderingKey.Bytes(i, msg); len(orderingKey) > 0 {
m.OrderingKey = string(orderingKey)
}
_, err := r.Send(context.Background(), m)
return err
})
}
// CloseAsync shuts down the Pulsar input and stops processing requests.
func (p *pulsarWriter) CloseAsync() {
p.shutSig.CloseAtLeisure()
go p.disconnect(context.Background())
}
// WaitForClose blocks until the Pulsar input has closed down.
func (p *pulsarWriter) WaitForClose(timeout time.Duration) error {
select {
case <-p.shutSig.HasClosedChan():
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}