-
Notifications
You must be signed in to change notification settings - Fork 29
/
compact.go
107 lines (87 loc) · 1.87 KB
/
compact.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
package catena
import (
"os"
"strings"
"sync/atomic"
"github.com/Cistern/catena/partition"
"github.com/Cistern/catena/partition/disk"
"github.com/Cistern/catena/partition/memory"
)
// compact drops old partitions and compacts older memory to
// read-only disk partitions.
func (db *DB) compact() {
// Look for partitions to drop
i := db.partitionList.NewIterator()
seen := 0
lastMin := int64(0)
for i.Next() {
p, err := i.Value()
if err != nil {
break
}
seen++
if seen <= db.maxPartitions {
lastMin = p.MinTimestamp()
continue
}
atomic.SwapInt64(&db.minTimestamp, lastMin)
// Remove it from the list
db.partitionList.Remove(p)
// Make sure we're the only ones accessing the partition
p.ExclusiveHold()
p.Destroy()
p.ExclusiveRelease()
}
// Find partitions to compact
toCompact := []partition.Partition{}
seen = 0
i = db.partitionList.NewIterator()
for i.Next() {
seen++
if seen <= 2 {
// Skip the latest two in-memory partitions
continue
}
p, _ := i.Value()
p.Hold()
if !p.ReadOnly() {
p.Release()
p.ExclusiveHold()
p.SetReadOnly()
p.ExclusiveRelease()
toCompact = append(toCompact, p)
} else {
p.Release()
}
}
for _, p := range toCompact {
// p is read-only, so no need to lock.
memPart := p.(*memory.MemoryPartition)
// Create the disk partition file
filename := strings.TrimSuffix(memPart.Filename(), ".wal") + ".part"
f, err := os.Create(filename)
if err != nil {
// ???
return
}
// Compact
err = memPart.Compact(f)
if err != nil {
// ???
return
}
// Close and reopen.
f.Sync()
f.Close()
diskPart, err := disk.OpenDiskPartition(filename)
if err != nil {
// ???
return
}
// Swap the memory partition with the disk partition.
db.partitionList.Swap(memPart, diskPart)
memPart.ExclusiveHold()
memPart.Destroy()
memPart.ExclusiveRelease()
}
}