forked from mkabilov/pg2ch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
199 lines (165 loc) · 4.93 KB
/
sync.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
package replicator
import (
"fmt"
"sort"
"github.com/jackc/pgx"
"gopkg.in/djherbis/buffer.v1"
"github.com/mkabilov/pg2ch/pkg/config"
"github.com/mkabilov/pg2ch/pkg/utils/chutils"
"github.com/mkabilov/pg2ch/pkg/utils/chutils/bulkupload"
"github.com/mkabilov/pg2ch/pkg/utils/dbtypes"
"github.com/mkabilov/pg2ch/pkg/utils/pgutils"
)
func (r *Replicator) SyncTables(syncTables []config.PgTableName, async bool) error {
if len(syncTables) == 0 {
r.logger.Info("no tables to sync")
return nil
}
doneCh := make(chan struct{}, r.cfg.SyncWorkers)
for i := 0; i < r.cfg.SyncWorkers; i++ {
go r.syncJob(i, doneCh)
}
for _, tblName := range syncTables {
r.syncJobs <- tblName
}
close(r.syncJobs)
if async {
go func() {
for i := 0; i < r.cfg.SyncWorkers; i++ {
<-doneCh
}
r.logger.Infof("sync is finished")
}()
} else {
for i := 0; i < r.cfg.SyncWorkers; i++ {
<-doneCh
}
r.logger.Infof("sync is finished")
}
return nil
}
func (r *Replicator) syncTable(chUploader bulkupload.BulkUploader, conn *pgx.Conn, pgTableName config.PgTableName) error {
if err := chUploader.Init(buffer.New(r.cfg.PipeBufferSize)); err != nil {
return fmt.Errorf("could not init bulkuploader: %v", err)
}
tx, snapshotLSN, err := r.getTxAndLSN(conn, pgTableName)
if err != nil {
return err
}
defer func() {
r.logger.Debugf("committing pg transaction, pid: %v", conn.PID())
if err := tx.Commit(); err != nil {
r.errCh <- fmt.Errorf("could not commit: %v", err)
}
}()
if err := r.chTables[pgTableName].Sync(chUploader, tx, snapshotLSN); err != nil {
return fmt.Errorf("could not sync: %v", err)
}
return nil
}
func (r *Replicator) GetTablesToSync() ([]config.PgTableName, error) {
var err error
syncTables := make([]config.PgTableName, 0)
if err := r.pgDeltaConnect(); err != nil {
return nil, fmt.Errorf("could not connect: %v", err)
}
defer r.pgDeltaDisconnect()
tx, err := r.pgBegin(r.pgDeltaConn)
if err != nil {
return nil, fmt.Errorf("could not start transaction: %v", err)
}
defer r.pgCommit(tx)
rowsCnt := make(map[config.PgTableName]uint64)
for tblName := range r.cfg.Tables {
if r.cfg.Tables[tblName].InitSyncSkip {
continue
}
if r.persStorage.Has(tblName.KeyName()) {
lsn, _ := r.persStorage.ReadLSN(tblName.KeyName())
if lsn != dbtypes.InvalidLSN {
continue
}
}
syncTables = append(syncTables, tblName)
rowsCnt[tblName], err = pgutils.PgStatLiveTuples(tx, tblName)
if err != nil {
return nil, fmt.Errorf("could not get stat live tuples: %v", err)
}
}
if len(syncTables) > 0 {
sort.SliceStable(syncTables, func(i, j int) bool {
return rowsCnt[syncTables[i]] > rowsCnt[syncTables[j]]
})
}
return syncTables, nil
}
func (r *Replicator) getTxAndLSN(conn *pgx.Conn, pgTableName config.PgTableName) (*pgx.Tx, dbtypes.LSN, error) { //TODO: better name: getSnapshot?
for attempt := 0; attempt < r.cfg.CreateSlotMaxAttempts; attempt++ {
select {
case <-r.ctx.Done():
return nil, dbtypes.InvalidLSN, fmt.Errorf("context done")
default:
}
tx, err := r.pgBegin(conn)
if err != nil {
r.logger.Warnf("could not begin transaction: %v", err)
r.pgCommit(tx)
continue
}
tmpSlotName := tempSlotName(pgTableName)
r.logger.Debugf("creating %q temporary logical replication slot for %q pg table (attempt: %d)",
tmpSlotName, pgTableName, attempt)
lsn, err := r.pgCreateTempRepSlot(tx, tmpSlotName)
if err == nil {
return tx, lsn, nil
}
r.pgRollback(tx)
r.logger.Warnf("could not create logical replication slot: %v", err)
}
return nil, dbtypes.InvalidLSN, fmt.Errorf("attempts exceeded")
}
// go routine
func (r *Replicator) syncJob(jobID int, doneCh chan<- struct{}) {
defer func() {
r.logger.Infof("sync job %d finished", jobID)
doneCh <- struct{}{}
}()
conn, err := pgx.Connect(r.pgxConnConfig)
if err != nil {
select {
case r.errCh <- fmt.Errorf("could not connect: %v", err):
default:
}
}
r.logger.Infof("sync job %d: connected to postgres, pid: %v", jobID, conn.PID())
defer func() {
r.logger.Infof("sync job %d: closing pg connection, pid: %v", jobID, conn.PID())
if err := conn.Close(); err != nil {
select {
case r.errCh <- fmt.Errorf("could not close connection: %v", err):
default:
}
}
}()
connInfo, err := initPostgresql(conn)
if err != nil {
select {
case r.errCh <- fmt.Errorf("could not fetch conn info: %v", err):
default:
}
}
conn.ConnInfo = connInfo
chConn := chutils.MakeChConnection(&r.cfg.ClickHouse, r.cfg.GzipCompression.UseCompression())
chUploader := bulkupload.New(chConn, r.cfg.GzipBufSize, r.cfg.GzipCompression)
for pgTableName := range r.syncJobs {
r.logger.Infof("sync job %d: starting syncing %q pg table", jobID, pgTableName)
if err := r.syncTable(chUploader, conn, pgTableName); err != nil {
select {
case r.errCh <- fmt.Errorf("could not sync table %s: %v", pgTableName, err):
default:
}
return
}
r.logger.Infof("sync job %d: %q table synced", jobID, pgTableName)
}
}