forked from LuttyYang/harmony-leveldb-sharder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
135 lines (114 loc) · 2.51 KB
/
main.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
package main
import (
"bytes"
"encoding/binary"
"flag"
"fmt"
"github.com/syndtr/goleveldb/leveldb"
"io/ioutil"
"kv-compare/compare"
"net/http"
_ "net/http/pprof"
"path/filepath"
"sync"
"time"
)
const (
safePointKey = "kv-compare-safe-point"
)
var shardIdxKey = []byte("__DB_SHARED_INDEX__")
func buildMultiDB(savePath string, diskCount int, diskShards int) *compare.MultiDBInstance {
var err error
var dbs = make([]compare.DBInstance, diskCount*diskShards)
// clean when error
defer func() {
if err != nil {
for _, db := range dbs {
if db != nil {
_ = db.Close()
}
}
}
}()
// async open
wg := sync.WaitGroup{}
for i := 0; i < diskCount; i++ {
for j := 0; j < diskShards; j++ {
shardPath := filepath.Join(savePath, fmt.Sprintf("disk%02d", i), fmt.Sprintf("block%02d", j))
dbIndex := i*diskShards + j
wg.Add(1)
go func() {
defer wg.Done()
ldb, err := compare.NewLevelDBInstance(shardPath)
if err != nil {
panic(err)
}
indexByte := make([]byte, 8)
binary.BigEndian.PutUint64(indexByte, uint64(dbIndex))
inDBIndex, getErr := ldb.Get(shardIdxKey)
if getErr != nil {
if getErr == leveldb.ErrNotFound {
putErr := ldb.Add(shardIdxKey, indexByte)
if putErr != nil {
err = putErr
return
}
} else {
err = getErr
return
}
} else if bytes.Compare(indexByte, inDBIndex) != 0 {
err = fmt.Errorf("db shard index error, need %v, got %v", indexByte, inDBIndex)
return
}
dbs[dbIndex] = ldb
}()
}
}
wg.Wait()
return compare.NewMultiDBInstance(dbs)
}
func main() {
from := flag.String("from", "", "from dir")
to := flag.String("to", "", "to dir")
flag.Parse()
go func() {
http.ListenAndServe(":8649", nil)
}()
instance, err := compare.NewLevelDBInstance(*from)
if err != nil {
panic(err)
}
defer instance.Close()
kvInstance := buildMultiDB(*to, 8, 4)
kvCompare := compare.NewCompare(instance, kvInstance, 32)
// load point
file, err := ioutil.ReadFile(safePointKey)
if err == nil {
err = kvCompare.LoadSafePoint(file)
if err != nil {
panic(err)
}
}
savePoint := func() {
point, err := kvCompare.SaveSafePointAndGet()
if err != nil {
panic(err)
}
kvCompare.PrintProcess()
err = ioutil.WriteFile(safePointKey, point, 0644)
if err != nil {
panic(err)
}
}
// save point
go func() {
for tick := range time.Tick(time.Second * 10) {
if time.Now().Sub(tick) < 5*time.Second {
savePoint()
}
}
}()
kvCompare.Start()
savePoint()
}