-
Notifications
You must be signed in to change notification settings - Fork 1
/
connector.go
224 lines (183 loc) · 4.94 KB
/
connector.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
package cdc
import (
"context"
goerrors "errors"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/Trendyol/go-pq-cdc/pq/timescaledb"
"github.com/Trendyol/go-pq-cdc/config"
"github.com/Trendyol/go-pq-cdc/internal/http"
"github.com/Trendyol/go-pq-cdc/internal/metric"
"github.com/Trendyol/go-pq-cdc/logger"
"github.com/Trendyol/go-pq-cdc/pq"
"github.com/Trendyol/go-pq-cdc/pq/publication"
"github.com/Trendyol/go-pq-cdc/pq/replication"
"github.com/Trendyol/go-pq-cdc/pq/slot"
"github.com/go-playground/errors"
"github.com/prometheus/client_golang/prometheus"
)
type Connector interface {
Start(ctx context.Context)
WaitUntilReady(ctx context.Context) error
Close()
GetConfig() *config.Config
SetMetricCollectors(collectors ...prometheus.Collector)
}
type connector struct {
stream replication.Streamer
prometheusRegistry metric.Registry
server http.Server
cfg *config.Config
slot *slot.Slot
cancelCh chan os.Signal
readyCh chan struct{}
timescaleDB *timescaledb.TimescaleDB
system pq.IdentifySystemResult
once sync.Once
}
func NewConnectorWithConfigFile(ctx context.Context, configFilePath string, listenerFunc replication.ListenerFunc) (Connector, error) {
var cfg config.Config
var err error
if strings.HasSuffix(configFilePath, ".json") {
cfg, err = config.ReadConfigJSON(configFilePath)
}
if strings.HasSuffix(configFilePath, ".yml") || strings.HasSuffix(configFilePath, ".yaml") {
cfg, err = config.ReadConfigYAML(configFilePath)
}
if err != nil {
return nil, err
}
return NewConnector(ctx, cfg, listenerFunc)
}
func NewConnector(ctx context.Context, cfg config.Config, listenerFunc replication.ListenerFunc) (Connector, error) {
cfg.SetDefault()
if err := cfg.Validate(); err != nil {
return nil, errors.Wrap(err, "config validation")
}
cfg.Print()
logger.InitLogger(cfg.Logger.Logger)
conn, err := pq.NewConnection(ctx, cfg.DSN())
if err != nil {
return nil, err
}
pub := publication.New(cfg.Publication, conn)
if err = pub.SetReplicaIdentities(ctx); err != nil {
return nil, err
}
publicationInfo, err := pub.Create(ctx)
if err != nil {
return nil, err
}
logger.Info("publication", "info", publicationInfo)
system, err := pq.IdentifySystem(ctx, conn)
if err != nil {
return nil, err
}
logger.Info("system identification", "systemID", system.SystemID, "timeline", system.Timeline, "xLogPos", system.LoadXLogPos(), "database:", system.Database)
m := metric.NewMetric(cfg.Slot.Name)
sl, err := slot.NewSlot(ctx, cfg.DSN(), cfg.Slot, m)
if err != nil {
return nil, err
}
slotInfo, err := sl.Create(ctx)
if err != nil {
return nil, err
}
logger.Info("slot info", "info", slotInfo)
stream := replication.NewStream(conn, cfg, m, &system, listenerFunc)
prometheusRegistry := metric.NewRegistry(m)
tdb, err := timescaledb.NewTimescaleDB(ctx, cfg.DSN())
if err != nil {
return nil, err
}
_, err = tdb.FindHyperTables(ctx)
if err != nil {
return nil, err
}
return &connector{
cfg: &cfg,
system: system,
stream: stream,
prometheusRegistry: prometheusRegistry,
server: http.NewServer(cfg, prometheusRegistry),
slot: sl,
timescaleDB: tdb,
cancelCh: make(chan os.Signal, 1),
readyCh: make(chan struct{}, 1),
}, nil
}
func (c *connector) Start(ctx context.Context) {
c.once.Do(func() {
go c.server.Listen()
})
c.CaptureSlot(ctx)
err := c.stream.Open(ctx)
if err != nil {
if goerrors.Is(err, replication.ErrorSlotInUse) {
logger.Info("capture failed")
c.Start(ctx)
return
}
logger.Error("postgres stream open", "error", err)
return
}
logger.Info("slot captured")
go c.slot.Metrics(ctx)
go c.timescaleDB.SyncHyperTables(ctx)
signal.Notify(c.cancelCh, syscall.SIGTERM, syscall.SIGINT, syscall.SIGABRT, syscall.SIGQUIT)
c.readyCh <- struct{}{}
<-c.cancelCh
logger.Debug("cancel channel triggered")
}
func (c *connector) WaitUntilReady(ctx context.Context) error {
select {
case <-c.readyCh:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (c *connector) Close() {
if !isClosed(c.cancelCh) {
close(c.cancelCh)
}
if !isClosed(c.readyCh) {
close(c.readyCh)
}
c.slot.Close()
c.stream.Close(context.TODO())
c.server.Shutdown()
}
func (c *connector) GetConfig() *config.Config {
return c.cfg
}
func (c *connector) SetMetricCollectors(metricCollectors ...prometheus.Collector) {
c.prometheusRegistry.AddMetricCollectors(metricCollectors...)
}
func (c *connector) CaptureSlot(ctx context.Context) {
logger.Info("slot capturing...")
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for range ticker.C {
info, err := c.slot.Info(ctx)
if err != nil {
continue
}
if !info.Active {
break
}
logger.Debug("capture slot", "slotInfo", info)
}
}
func isClosed[T any](ch <-chan T) bool {
select {
case <-ch:
return true
default:
}
return false
}