-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
input.go
293 lines (250 loc) · 8.4 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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package gcppubsub
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
"cloud.google.com/go/pubsub"
"golang.org/x/time/rate"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/elastic/beats/v7/filebeat/channel"
"github.com/elastic/beats/v7/filebeat/input"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common/acker"
"github.com/elastic/beats/v7/libbeat/common/atomic"
"github.com/elastic/beats/v7/libbeat/version"
conf "github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/elastic-agent-libs/useragent"
)
const (
inputName = "gcp-pubsub"
oldInputName = "google-pubsub"
// retryInterval is the minimum duration between pub/sub client retries.
retryInterval = 30 * time.Second
)
func init() {
err := input.Register(inputName, NewInput)
if err != nil {
panic(fmt.Errorf("failed to register %v input: %w", inputName, err))
}
err = input.Register(oldInputName, NewInput)
if err != nil {
panic(fmt.Errorf("failed to register %v input: %w", oldInputName, err))
}
}
type pubsubInput struct {
config
log *logp.Logger
outlet channel.Outleter // Output of received pubsub messages.
inputCtx context.Context // Wraps the Done channel from parent input.Context.
workerCtx context.Context // Worker goroutine context. It's cancelled when the input stops or the worker exits.
workerCancel context.CancelFunc // Used to signal that the worker should stop.
workerOnce sync.Once // Guarantees that the worker goroutine is only started once.
workerWg sync.WaitGroup // Waits on pubsub worker goroutine.
ackedCount *atomic.Uint32 // Total number of successfully ACKed pubsub messages.
}
// NewInput creates a new Google Cloud Pub/Sub input that consumes events from
// a topic subscription.
func NewInput(
cfg *conf.C,
connector channel.Connector,
inputContext input.Context,
) (inp input.Input, err error) {
// Extract and validate the input's configuration.
conf := defaultConfig()
if err = cfg.Unpack(&conf); err != nil {
return nil, err
}
logger := logp.NewLogger("gcp.pubsub").With(
"pubsub_project", conf.ProjectID,
"pubsub_topic", conf.Topic,
"pubsub_subscription", conf.Subscription)
if conf.Type == oldInputName {
logger.Warnf("%s input name is deprecated, please use %s instead", oldInputName, inputName)
}
// Wrap input.Context's Done channel with a context.Context. This goroutine
// stops with the parent closes the Done channel.
inputCtx, cancelInputCtx := context.WithCancel(context.Background())
go func() {
defer cancelInputCtx()
select {
case <-inputContext.Done:
case <-inputCtx.Done():
}
}()
// If the input ever needs to be made restartable, then context would need
// to be recreated with each restart.
workerCtx, workerCancel := context.WithCancel(inputCtx)
in := &pubsubInput{
config: conf,
log: logger,
inputCtx: inputCtx,
workerCtx: workerCtx,
workerCancel: workerCancel,
ackedCount: atomic.NewUint32(0),
}
// Build outlet for events.
in.outlet, err = connector.ConnectWith(cfg, beat.ClientConfig{
EventListener: acker.ConnectionOnly(
acker.EventPrivateReporter(func(_ int, privates []interface{}) {
for _, priv := range privates {
if msg, ok := priv.(*pubsub.Message); ok {
msg.Ack()
in.ackedCount.Inc()
} else {
in.log.Error("Failed ACKing pub/sub event")
}
}
}),
),
})
if err != nil {
return nil, err
}
in.log.Info("Initialized GCP Pub/Sub input.")
return in, nil
}
// Run starts the pubsub input worker then returns. Only the first invocation
// will ever start the pubsub worker.
func (in *pubsubInput) Run() {
in.workerOnce.Do(func() {
in.workerWg.Add(1)
go func() {
in.log.Info("Pub/Sub input worker has started.")
defer in.log.Info("Pub/Sub input worker has stopped.")
defer in.workerWg.Done()
defer in.workerCancel()
// Throttle pubsub client restarts.
rt := rate.NewLimiter(rate.Every(retryInterval), 1)
// Watchdog to keep the worker operating after an error.
for in.workerCtx.Err() == nil {
// Rate limit.
if err := rt.Wait(in.workerCtx); err != nil {
continue
}
if err := in.run(); err != nil {
if in.workerCtx.Err() == nil {
in.log.Warnw("Restarting failed Pub/Sub input worker.", "error", err)
continue
}
// Log any non-cancellation error before stopping.
if !errors.Is(err, context.Canceled) {
in.log.Errorw("Pub/Sub input worker failed.", "error", err)
}
}
}
}()
})
}
func (in *pubsubInput) run() error {
ctx, cancel := context.WithCancel(in.workerCtx)
defer cancel()
client, err := in.newPubsubClient(ctx)
if err != nil {
return err
}
defer client.Close()
// Setup our subscription to the topic.
sub, err := in.getOrCreateSubscription(ctx, client)
if err != nil {
return fmt.Errorf("failed to subscribe to pub/sub topic: %w", err)
}
sub.ReceiveSettings.NumGoroutines = in.Subscription.NumGoroutines
sub.ReceiveSettings.MaxOutstandingMessages = in.Subscription.MaxOutstandingMessages
// Start receiving messages.
topicID := makeTopicID(in.ProjectID, in.Topic)
return sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
if ok := in.outlet.OnEvent(makeEvent(topicID, msg)); !ok {
msg.Nack()
in.log.Debug("OnEvent returned false. Stopping input worker.")
cancel()
}
})
}
// Stop stops the pubsub input and waits for it to fully stop.
func (in *pubsubInput) Stop() {
in.workerCancel()
in.workerWg.Wait()
}
// Wait is an alias for Stop.
func (in *pubsubInput) Wait() {
in.Stop()
}
// makeTopicID returns a short sha256 hash of the project ID plus topic name.
// This string can be joined with pub/sub message IDs that are unique within a
// topic to create a unique _id for documents.
func makeTopicID(project, topic string) string {
h := sha256.New()
h.Write([]byte(project))
h.Write([]byte(topic))
prefix := hex.EncodeToString(h.Sum(nil))
return prefix[:10]
}
func makeEvent(topicID string, msg *pubsub.Message) beat.Event {
id := topicID + "-" + msg.ID
event := beat.Event{
Timestamp: msg.PublishTime.UTC(),
Fields: mapstr.M{
"event": mapstr.M{
"id": id,
"created": time.Now().UTC(),
},
"message": string(msg.Data),
},
Private: msg,
}
event.SetID(id)
if len(msg.Attributes) > 0 {
event.Fields["labels"] = msg.Attributes
}
return event
}
func (in *pubsubInput) getOrCreateSubscription(ctx context.Context, client *pubsub.Client) (*pubsub.Subscription, error) {
sub := client.Subscription(in.Subscription.Name)
exists, err := sub.Exists(ctx)
if err != nil {
return nil, fmt.Errorf("failed to check if subscription exists: %w", err)
}
if exists {
return sub, nil
}
// Create subscription.
if in.Subscription.Create {
sub, err = client.CreateSubscription(ctx, in.Subscription.Name, pubsub.SubscriptionConfig{
Topic: client.Topic(in.Topic),
})
if err != nil {
return nil, fmt.Errorf("failed to create subscription: %w", err)
}
in.log.Debug("Created new subscription.")
return sub, nil
}
return nil, errors.New("no subscription exists and 'subscription.create' is not enabled")
}
func (in *pubsubInput) newPubsubClient(ctx context.Context) (*pubsub.Client, error) {
opts := []option.ClientOption{option.WithUserAgent(useragent.UserAgent("Filebeat", version.GetDefaultVersion(), version.Commit(), version.BuildTime().String()))}
if in.AlternativeHost != "" {
// This will be typically set because we want to point the input to a testing pubsub emulator.
conn, err := grpc.Dial(in.AlternativeHost, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("cannot connect to alternative host %q: %w", in.AlternativeHost, err)
}
opts = append(opts, option.WithGRPCConn(conn), option.WithTelemetryDisabled())
}
if in.CredentialsFile != "" {
opts = append(opts, option.WithCredentialsFile(in.CredentialsFile))
} else if len(in.CredentialsJSON) > 0 {
opts = append(opts, option.WithCredentialsJSON(in.CredentialsJSON))
}
return pubsub.NewClient(ctx, in.ProjectID, opts...)
}