-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsubOutput.go
268 lines (227 loc) · 6.75 KB
/
pubsubOutput.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
// Copyright 2015 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pubsub
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"go.chromium.org/luci/common/clock"
"go.chromium.org/luci/common/data/recordio"
"go.chromium.org/luci/common/errors"
gcps "go.chromium.org/luci/common/gcloud/pubsub"
log "go.chromium.org/luci/common/logging"
"go.chromium.org/luci/common/retry"
"go.chromium.org/luci/common/retry/transient"
"go.chromium.org/luci/grpc/grpcutil"
"go.chromium.org/luci/logdog/api/logpb"
"go.chromium.org/luci/logdog/client/butler/output"
"go.chromium.org/luci/logdog/client/butlerproto"
"go.chromium.org/luci/logdog/common/types"
"cloud.google.com/go/pubsub"
)
// Topic is an interface for a Pub/Sub topic.
//
// pubsub.Topic implements Topic.
type Topic interface {
// String returns the name of the topic.
String() string
// Publish mirrors the pubsub.Connection Publish method.
Publish(context.Context, *pubsub.Message) (string, error)
}
// Config is a configuration structure for Pub/Sub output.
type Config struct {
// Topic is the Pub/Sub topic to publish to.
Topic Topic
// Secret, if not nil, is the prefix secret to attach to each outgoing bundle.
Secret types.PrefixSecret
// Compress, if true, enables zlib compression.
Compress bool
// Track, if true, tracks all log entries that have been successfully
// submitted.
Track bool
// RPCTimeout is the timeout to apply to an individual RPC.
RPCTimeout time.Duration
}
// buffer
type buffer struct {
bytes.Buffer // Output buffer for published message data.
frameWriter recordio.Writer
protoWriter *butlerproto.Writer
}
// Butler Output that sends messages into Google Cloud PubSub as compressed
// protocol buffer blobs.
type pubSubOutput struct {
*Config
context.Context
bufferPool sync.Pool // Pool of reusable buffer instances.
statsMu sync.Mutex
stats output.StatsBase
et *output.EntryTracker
}
// New instantiates a new GCPS output.
func New(ctx context.Context, c Config) output.Output {
o := pubSubOutput{
Config: &c,
}
o.bufferPool.New = func() interface{} { return &buffer{} }
if c.Track {
o.et = &output.EntryTracker{}
}
o.Context = log.SetField(ctx, "pubsub", &o)
return &o
}
func (o *pubSubOutput) String() string {
return fmt.Sprintf("pubsub(%s)", o.Topic.String())
}
func (o *pubSubOutput) SendBundle(bundle *logpb.ButlerLogBundle) error {
st := output.StatsBase{}
defer o.mergeStats(&st)
b := o.bufferPool.Get().(*buffer)
defer o.bufferPool.Put(b)
bundle.Secret = []byte(o.Secret)
message, err := o.buildMessage(b, bundle)
if err != nil {
log.Fields{
log.ErrorKey: err,
}.Errorf(o, "Failed to build PubSub Message from bundle.")
st.F.DiscardedMessages++
st.F.Errors++
return err
}
if len(message.Data) > gcps.MaxPublishRequestBytes {
log.Fields{
"messageSize": len(message.Data),
"maxPubSubSize": gcps.MaxPublishRequestBytes,
}.Errorf(o, "Constructed message exceeds Pub/Sub maximum size.")
return errors.New("pubsub: bundle contents violate Pub/Sub size limit")
}
if err := o.publishMessage(message); err != nil {
st.F.DiscardedMessages++
st.F.Errors++
return err
}
if o.et != nil {
o.et.Track(bundle)
}
st.F.SentBytes += int64(len(message.Data))
st.F.SentMessages++
return nil
}
func (*pubSubOutput) MaxSize() int {
return gcps.MaxPublishRequestBytes / 2
}
func (o *pubSubOutput) Stats() output.Stats {
o.statsMu.Lock()
defer o.statsMu.Unlock()
statsCopy := o.stats
return &statsCopy
}
func (o *pubSubOutput) Record() *output.EntryRecord {
if o.et == nil {
return nil
}
return o.et.Record()
}
func (o *pubSubOutput) Close() {
// Nothing to do.
}
// buildMessage constructs a Pub/Sub Message out of LogDog frames.
//
// The first frame will be a ButlerMetadata message describing the second
// frame. The second frame will be a ButlerLogBundle containing the bundle
// data.
func (o *pubSubOutput) buildMessage(buf *buffer, bundle *logpb.ButlerLogBundle) (*pubsub.Message, error) {
if buf.protoWriter == nil {
buf.protoWriter = &butlerproto.Writer{
Compress: o.Compress,
CompressThreshold: butlerproto.DefaultCompressThreshold,
}
}
// Clear our buffer and (re)initialize our frame writer.
buf.Reset()
if buf.frameWriter == nil {
buf.frameWriter = recordio.NewWriter(buf)
} else {
buf.frameWriter.Reset(buf)
}
if err := buf.protoWriter.WriteWith(buf.frameWriter, bundle); err != nil {
return nil, err
}
return &pubsub.Message{
Data: buf.Bytes(),
}, nil
}
// publishMessage handles an individual publish request. It will indefinitely
// retry transient errors until the publish succeeds.
func (o *pubSubOutput) publishMessage(message *pubsub.Message) error {
var messageID string
transientErrors := 0
err := retry.Retry(o, transient.Only(indefiniteRetry), func() (err error) {
ctx := o.Context
if o.RPCTimeout > 0 {
var cancelFunc context.CancelFunc
ctx, cancelFunc = clock.WithTimeout(o, o.RPCTimeout)
defer cancelFunc()
}
messageID, err = o.Topic.Publish(ctx, message)
if err == context.DeadlineExceeded {
// If we hit our publish deadline, retry.
err = transient.Tag.Apply(err)
} else {
err = grpcutil.WrapIfTransient(err)
}
return
}, func(err error, d time.Duration) {
log.Fields{
log.ErrorKey: err,
"delay": d,
}.Warningf(o, "TRANSIENT error publishing messages; retrying...")
transientErrors++
})
if err != nil {
log.WithError(err).Errorf(o, "Failed to send PubSub message.")
return err
}
if transientErrors > 0 {
// We successfully published, but we hit a transient error, so explicitly
// acknowledge this at warning-level for log message closure.
log.Fields{
"messageId": messageID,
"transientErrors": transientErrors,
}.Warningf(o, "Successfully published messages after transient errors.")
} else {
log.Fields{
"messageId": messageID,
}.Debugf(o, "Published messages.")
}
return nil
}
func (o *pubSubOutput) mergeStats(s output.Stats) {
o.statsMu.Lock()
defer o.statsMu.Unlock()
o.stats.Merge(s)
}
// indefiniteRetry is a retry.Iterator that will indefinitely retry errors with
// a maximum backoff.
func indefiniteRetry() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Retries: -1,
Delay: 500 * time.Millisecond,
},
MaxDelay: 30 * time.Second,
}
}