-
Notifications
You must be signed in to change notification settings - Fork 5
/
dbtransactionlogio.go
374 lines (307 loc) · 8.39 KB
/
dbtransactionlogio.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
371
372
373
374
package datastore
import (
"encoding/json"
"fmt"
"sort"
"sync"
"time"
"context"
"cloud.google.com/go/datastore"
"go.uber.org/zap"
"google.golang.org/api/iterator"
"github.com/nyaxt/otaru/btncrypt"
oflags "github.com/nyaxt/otaru/flags"
gcutil "github.com/nyaxt/otaru/gcloud/util"
"github.com/nyaxt/otaru/inodedb"
"github.com/nyaxt/otaru/logger"
"github.com/nyaxt/otaru/util"
)
var txlog = logger.Registry().Category("dbtxlogio")
type DBTransactionLogIO struct {
flags int
cfg *Config
rootKey *datastore.Key
mu sync.Mutex
nextbatch []inodedb.DBTransaction
muSync sync.Mutex
committing []inodedb.DBTransaction
}
const kindTransaction = "OtaruINodeDBTxBulk"
var _ = inodedb.DBTransactionLogIO(&DBTransactionLogIO{})
func NewDBTransactionLogIO(cfg *Config, flags int) *DBTransactionLogIO {
return &DBTransactionLogIO{
flags: flags,
cfg: cfg,
rootKey: datastore.NameKey(kindTransaction, cfg.rootKeyStr, nil),
nextbatch: make([]inodedb.DBTransaction, 0),
}
}
func (*DBTransactionLogIO) ImplName() string { return "gcloud/datastore.DBTransactionLogIO" }
type storedbtx struct {
TxsJSON []byte `datastore:",noindex"`
}
func (txio *DBTransactionLogIO) encodeKey(id inodedb.TxID) *datastore.Key {
return datastore.IDKey(kindTransaction, int64(id), txio.rootKey)
}
func (txio *DBTransactionLogIO) encodeBatch(txs []inodedb.DBTransaction) (*datastore.Key, *storedbtx, error) {
if len(txs) == 0 {
return nil, nil, fmt.Errorf("txs empty")
}
id := txs[len(txs)-1].TxID
for _, tx := range txs {
inodedb.SetOpMetas(tx.Ops)
}
jsonops, err := json.Marshal(txs)
if err != nil {
return nil, nil, fmt.Errorf("Failed to encode txs: %v", err)
}
gzjsonops, err := util.Gzip(jsonops)
if err != nil {
return nil, nil, fmt.Errorf("Failed to compress txs: %v", err)
}
c := txio.cfg.c
env, err := btncrypt.Encrypt(c, gzjsonops)
if err != nil {
return nil, nil, fmt.Errorf("Failed to encrypt TxsJSON: %v", err)
}
zap.S().Debugf("len(TxsJSON): %d", len(env))
key := txio.encodeKey(id)
return key, &storedbtx{TxsJSON: env}, nil
}
func decodeBatch(c *btncrypt.Cipher, key *datastore.Key, stx *storedbtx) ([]inodedb.DBTransaction, error) {
gzjsontxs, err := btncrypt.Decrypt(c, stx.TxsJSON, len(stx.TxsJSON)-c.FrameOverhead())
if err != nil {
return nil, fmt.Errorf("Failed to decrypt TxsJSON: %v", err)
}
jsontxs, err := util.Gunzip(gzjsontxs)
if err != nil {
return nil, fmt.Errorf("Failed to uncompress TxsJSON: %v", err)
}
var utxs []*inodedb.UnresolvedDBTransaction
if err := json.Unmarshal(jsontxs, &utxs); err != nil {
return nil, err
}
txs := make([]inodedb.DBTransaction, 0, len(utxs))
for _, utx := range utxs {
tx, err := inodedb.ResolveDBTransaction(*utx)
if err != nil {
return nil, err
}
txs = append(txs, tx)
}
return txs, nil
}
func (txio *DBTransactionLogIO) AppendTransaction(tx inodedb.DBTransaction) error {
if !oflags.IsWriteAllowed(txio.flags) {
return util.EACCES
}
txio.mu.Lock()
defer txio.mu.Unlock()
txio.nextbatch = append(txio.nextbatch, tx)
return nil
}
func (txio *DBTransactionLogIO) Sync() error {
if !oflags.IsWriteAllowed(txio.flags) {
return util.EACCES
}
start := time.Now()
txio.muSync.Lock()
defer txio.muSync.Unlock()
txio.mu.Lock()
if len(txio.committing) != 0 {
panic("I should be the only one committing.")
}
txio.committing = txio.nextbatch
batch := txio.committing
txio.nextbatch = make([]inodedb.DBTransaction, 0)
txio.mu.Unlock()
rollback := func() {
txio.mu.Lock()
txio.nextbatch = append(txio.committing, txio.nextbatch...)
txio.committing = []inodedb.DBTransaction{}
txio.mu.Unlock()
}
if len(batch) == 0 {
return nil
}
cli, err := txio.cfg.getClient(context.Background())
if err != nil {
rollback()
return err
}
defer cli.Close()
key, txbatch, err := txio.encodeBatch(batch)
if err != nil {
rollback()
return err
}
dstx, err := cli.NewTransaction(context.Background())
if err != nil {
rollback()
return err
}
if _, err := dstx.Put(key, txbatch); err != nil {
rollback()
dstx.Rollback()
return err
}
if _, err := dstx.Commit(); err != nil {
rollback()
return err
}
txio.mu.Lock()
txio.committing = []inodedb.DBTransaction{}
txio.mu.Unlock()
zap.S().Infof("Sync() took %s. Committed %d txs. Last committed txid: %v", time.Since(start), len(batch), batch[len(batch)-1].TxID)
return nil
}
type txsorter []inodedb.DBTransaction
func (s txsorter) Len() int { return len(s) }
func (s txsorter) Less(i, j int) bool { return s[i].TxID < s[j].TxID }
func (s txsorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (txio *DBTransactionLogIO) QueryTransactions(minID inodedb.TxID) (txs []inodedb.DBTransaction, err error) {
err = gcutil.RetryIfNeeded(func() error {
txs, err = txio.queryTransactionsOnce(minID)
return err
}, txlog)
return
}
func (txio *DBTransactionLogIO) queryTransactionsOnce(minID inodedb.TxID) ([]inodedb.DBTransaction, error) {
start := time.Now()
txs := []inodedb.DBTransaction{}
txio.mu.Lock()
for _, tx := range txio.committing {
if tx.TxID >= minID {
txs = append(txs, tx)
}
}
for _, tx := range txio.nextbatch {
if tx.TxID >= minID {
txs = append(txs, tx)
}
}
txio.mu.Unlock()
cli, err := txio.cfg.getClient(context.Background())
if err != nil {
return nil, err
}
defer cli.Close()
dstx, err := cli.NewTransaction(context.Background())
if err != nil {
return nil, err
}
q := datastore.NewQuery(kindTransaction).Ancestor(txio.rootKey).Transaction(dstx)
if minID != inodedb.AnyVersion {
minKey := txio.encodeKey(minID)
q = q.Filter("__key__ >=", minKey)
}
it := cli.Run(context.Background(), q)
for {
var stx storedbtx
key, err := it.Next(&stx)
if err != nil {
if err == iterator.Done {
break
}
dstx.Commit()
return []inodedb.DBTransaction{}, err
}
batchtxs, err := decodeBatch(txio.cfg.c, key, &stx)
if err != nil {
dstx.Commit()
return []inodedb.DBTransaction{}, err
}
for _, tx := range batchtxs {
if tx.TxID >= minID {
txs = append(txs, tx)
}
}
}
// FIXME: not sure if Rollback() is better
if _, err := dstx.Commit(); err != nil {
return nil, err
}
sort.Sort(txsorter(txs))
uniqed := make([]inodedb.DBTransaction, 0, len(txs))
var prevId inodedb.TxID
for _, tx := range txs {
if tx.TxID == prevId {
continue
}
uniqed = append(uniqed, tx)
prevId = tx.TxID
}
zap.S().Infof("QueryTransactions(%v) took %s", minID, time.Since(start))
return uniqed, nil
}
const maxWriteEntriesPerTx = 500 // Google Cloud Datastore limit on number of write entries per tx
func (txio *DBTransactionLogIO) DeleteTransactions(smallerThanID inodedb.TxID) error {
if !oflags.IsWriteAllowed(txio.flags) {
return util.EACCES
}
start := time.Now()
txio.mu.Lock()
batch := make([]inodedb.DBTransaction, 0, len(txio.nextbatch))
for _, tx := range txio.nextbatch {
if tx.TxID < smallerThanID {
continue
}
batch = append(batch, tx)
}
txio.nextbatch = batch
txio.mu.Unlock()
cli, err := txio.cfg.getClient(context.Background())
if err != nil {
return err
}
defer cli.Close()
ndel := 0
for {
needAnotherTx := false
txStart := time.Now()
dstx, err := cli.NewTransaction(context.Background())
if err != nil {
return err
}
keys := []*datastore.Key{}
ltkey := txio.encodeKey(smallerThanID)
q := datastore.NewQuery(kindTransaction).Ancestor(txio.rootKey).Filter("__key__ <", ltkey).KeysOnly().Transaction(dstx)
it := cli.Run(context.Background(), q)
for {
k, err := it.Next(nil)
if err != nil {
if err == iterator.Done {
break
}
dstx.Rollback()
return err
}
keys = append(keys, k)
if len(keys) == maxWriteEntriesPerTx {
needAnotherTx = true
break
}
}
if err := dstx.DeleteMulti(keys); err != nil {
dstx.Rollback()
return err
}
if _, err := dstx.Commit(); err != nil {
return err
}
ndel += len(keys)
if needAnotherTx {
zap.S().Infof("DeleteTransactions(%v): A tx deleting %d entries took %s. Starting next tx to delete more.", smallerThanID, len(keys), time.Since(txStart))
} else {
zap.S().Infof("DeleteTransactions(%v): A tx deleting %d entries took %s.", smallerThanID, len(keys), time.Since(txStart))
break
}
}
zap.S().Infof("DeleteTransactions(%v) deleted %d entries. tx took %s", smallerThanID, ndel, time.Since(start))
return nil
}
func (txio *DBTransactionLogIO) DeleteAllTransactions() error {
return txio.DeleteTransactions(inodedb.LatestVersion)
}