-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdcp.go
370 lines (298 loc) · 8.76 KB
/
dcp.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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package dcp
import (
"bytes"
"encoding/json"
"errors"
"os"
"os/signal"
"reflect"
"regexp"
"strings"
"syscall"
"github.com/Trendyol/go-dcp/metric"
"github.com/asaskevich/EventBus"
"github.com/Trendyol/go-dcp/membership"
"github.com/sirupsen/logrus"
jsoniter "github.com/json-iterator/go"
"gopkg.in/yaml.v3"
"github.com/prometheus/client_golang/prometheus"
"github.com/Trendyol/go-dcp/api"
"github.com/Trendyol/go-dcp/config"
"github.com/Trendyol/go-dcp/couchbase"
"github.com/Trendyol/go-dcp/helpers"
"github.com/Trendyol/go-dcp/logger"
"github.com/Trendyol/go-dcp/metadata"
"github.com/Trendyol/go-dcp/models"
"github.com/Trendyol/go-dcp/servicediscovery"
"github.com/Trendyol/go-dcp/stream"
)
type Dcp interface {
WaitUntilReady() chan struct{}
Start()
Close()
Commit()
GetClient() couchbase.Client
GetConfig() *config.Dcp
GetVersion() *couchbase.Version
SetMetadata(metadata metadata.Metadata)
SetMetricCollectors(collectors ...prometheus.Collector)
SetEventHandler(handler models.EventHandler)
}
type dcp struct {
bus EventBus.Bus
stream stream.Stream
api api.API
leaderElection stream.LeaderElection
vBucketDiscovery stream.VBucketDiscovery
serviceDiscovery servicediscovery.ServiceDiscovery
metadata metadata.Metadata
eventHandler models.EventHandler
client couchbase.Client
apiShutdown chan struct{}
config *config.Dcp
version *couchbase.Version
bucketInfo *couchbase.BucketInfo
healthCheck couchbase.HealthCheck
listener models.Listener
readyCh chan struct{}
cancelCh chan os.Signal
stopCh chan struct{}
metricCollectors []prometheus.Collector
closeWithCancel bool
}
func (s *dcp) SetMetadata(metadata metadata.Metadata) {
s.metadata = metadata
}
func (s *dcp) SetMetricCollectors(metricCollectors ...prometheus.Collector) {
s.metricCollectors = append(s.metricCollectors, metricCollectors...)
}
func (s *dcp) SetEventHandler(eventHandler models.EventHandler) {
s.eventHandler = eventHandler
}
func (s *dcp) membershipChangedListener(_ *membership.Model) {
s.stream.Rebalance()
}
//nolint:funlen
func (s *dcp) Start() {
if s.metadata == nil {
switch {
case s.config.IsCouchbaseMetadata():
s.metadata = couchbase.NewCBMetadata(s.client, s.config)
case s.config.IsFileMetadata():
s.metadata = metadata.NewFSMetadata(s.config)
default:
err := errors.New("invalid metadata type")
logger.Log.Error("error while dcp start, err: %v", err)
panic(err)
}
}
if s.config.Metadata.ReadOnly {
s.metadata = metadata.NewReadMetadata(s.metadata)
}
logger.Log.Info("using %v metadata", reflect.TypeOf(s.metadata))
vBuckets := s.client.GetNumVBuckets()
s.vBucketDiscovery = stream.NewVBucketDiscovery(s.client, s.config, vBuckets, s.bus)
s.stream = stream.NewStream(
s.client, s.metadata, s.config, s.version, s.bucketInfo, s.vBucketDiscovery,
s.listener, s.client.GetCollectionIDs(s.config.ScopeName, s.config.CollectionNames), s.stopCh, s.bus, s.eventHandler,
)
if s.config.LeaderElection.Enabled {
s.serviceDiscovery = servicediscovery.NewServiceDiscovery(s.config, s.bus)
s.serviceDiscovery.StartHeartbeat()
s.serviceDiscovery.StartMonitor()
s.leaderElection = stream.NewLeaderElection(s.config, s.serviceDiscovery, s.bus)
s.leaderElection.Start()
}
if !s.config.API.Disabled {
go func() {
go func() {
<-s.apiShutdown
s.api.Shutdown()
}()
s.metricCollectors = append(s.metricCollectors, metric.NewMetricCollector(s.client, s.stream, s.vBucketDiscovery))
s.api = api.NewAPI(s.config, s.client, s.stream, s.serviceDiscovery, s.metricCollectors, s.bus)
s.api.Listen()
}()
}
s.stream.Open()
err := s.bus.SubscribeAsync(helpers.MembershipChangedBusEventName, s.membershipChangedListener, true)
if err != nil {
logger.Log.Error("error while subscribe to membership changed event, err: %v", err)
panic(err)
}
signal.Notify(s.cancelCh, syscall.SIGTERM, syscall.SIGINT, syscall.SIGABRT, syscall.SIGQUIT)
if !s.config.HealthCheck.Disabled {
s.healthCheck = couchbase.NewHealthCheck(&s.config.HealthCheck, s.client)
s.healthCheck.Start()
}
logger.Log.Info("dcp stream started")
s.readyCh <- struct{}{}
select {
case <-s.stopCh:
logger.Log.Debug("stop channel triggered")
case <-s.cancelCh:
logger.Log.Debug("cancel channel triggered")
s.closeWithCancel = true
}
s.close()
}
func (s *dcp) GetClient() couchbase.Client {
return s.client
}
func (s *dcp) WaitUntilReady() chan struct{} {
return s.readyCh
}
func (s *dcp) Close() {
s.cancelCh <- syscall.SIGTERM
}
func (s *dcp) close() {
if !s.config.HealthCheck.Disabled {
s.healthCheck.Stop()
}
s.vBucketDiscovery.Close()
if s.config.Checkpoint.Type == stream.CheckpointTypeAuto {
s.stream.Save()
}
err := s.bus.Unsubscribe(helpers.MembershipChangedBusEventName, s.membershipChangedListener)
if err != nil {
logger.Log.Error("cannot while unsubscribe: %v", err)
}
s.stream.Close(s.closeWithCancel)
if s.config.LeaderElection.Enabled {
s.leaderElection.Stop()
s.serviceDiscovery.StopMonitor()
s.serviceDiscovery.StopHeartbeat()
}
if s.api != nil && !s.config.API.Disabled {
s.apiShutdown <- struct{}{}
}
s.client.DcpClose()
s.client.Close()
if s.api != nil && !s.config.API.Disabled {
s.api.UnregisterMetricCollectors()
}
s.metricCollectors = []prometheus.Collector{}
logger.Log.Info("dcp stream closed")
}
func (s *dcp) Commit() {
s.stream.Save()
}
func (s *dcp) GetConfig() *config.Dcp {
return s.config
}
func (s *dcp) GetVersion() *couchbase.Version {
return s.version
}
func newDcp(config *config.Dcp, listener models.Listener) (Dcp, error) {
config.ApplyDefaults()
copyOfConfig := config
printConfiguration(*copyOfConfig)
client := couchbase.NewClient(config)
err := client.Connect()
if err != nil {
return nil, err
}
httpClient := couchbase.NewHTTPClient(config, client)
err = httpClient.Connect()
if err != nil {
return nil, err
}
version, err := httpClient.GetVersion()
if err != nil {
return nil, err
}
bucketInfo, err := httpClient.GetBucketInfo()
if err != nil {
return nil, err
}
var useExpiryOpcode bool
var useChangeStreams bool
if version.Higher(couchbase.SrvVer650) || version.Equal(couchbase.SrvVer650) {
useExpiryOpcode = true
}
if bucketInfo.IsMagma() && (version.Higher(couchbase.SrvVer720) || version.Equal(couchbase.SrvVer720)) {
useChangeStreams = true
}
err = client.DcpConnect(useExpiryOpcode, useChangeStreams)
if err != nil {
return nil, err
}
return &dcp{
client: client,
listener: listener,
config: config,
version: version,
bucketInfo: bucketInfo,
apiShutdown: make(chan struct{}, 1),
cancelCh: make(chan os.Signal, 1),
stopCh: make(chan struct{}, 1),
readyCh: make(chan struct{}, 1),
metricCollectors: []prometheus.Collector{},
eventHandler: models.DefaultEventHandler,
bus: EventBus.New(),
}, nil
}
// NewDcp creates a new Dcp client
//
// config: path to a configuration file or a configuration struct
// listener is a callback function that will be called when a mutation, deletion or expiration event occurs
func NewDcp(cfg any, listener models.Listener) (Dcp, error) {
switch v := cfg.(type) {
case *config.Dcp:
return newDcp(v, listener)
case config.Dcp:
return newDcp(&v, listener)
case string:
return newDcpWithPath(v, listener)
default:
return nil, errors.New("invalid config")
}
}
func newDcpWithPath(path string, listener models.Listener) (Dcp, error) {
c, err := newDcpConfig(path)
if err != nil {
return nil, err
}
return newDcp(&c, listener)
}
func newDcpConfig(path string) (config.Dcp, error) {
file, err := os.ReadFile(path)
if err != nil {
return config.Dcp{}, err
}
var c config.Dcp
err = yaml.Unmarshal(file, &c)
if err != nil {
return config.Dcp{}, err
}
envPattern := regexp.MustCompile(`\${([^}]+)}`)
matches := envPattern.FindAllStringSubmatch(string(file), -1)
for _, match := range matches {
envVar := match[1]
if value, exists := os.LookupEnv(envVar); exists {
updatedFile := strings.ReplaceAll(string(file), "${"+envVar+"}", value)
file = []byte(updatedFile)
}
}
err = yaml.Unmarshal(file, &c)
if err != nil {
return config.Dcp{}, err
}
return c, nil
}
func NewDcpWithLogger(cfg any, listener models.Listener, logrus *logrus.Logger) (Dcp, error) {
logger.Log = &logger.Loggers{
Logrus: logrus,
}
return NewDcp(cfg, listener)
}
func printConfiguration(config config.Dcp) {
config.Password = "*****"
configJSON, _ := jsoniter.Marshal(config)
dst := &bytes.Buffer{}
if err := json.Compact(dst, configJSON); err != nil {
logger.Log.Error("error while print configuration, err: %v", err)
panic(err)
}
logger.Log.Info("using config: %v", dst.String())
}