forked from chenjiandongx/mandodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory_segment.go
308 lines (244 loc) · 6.62 KB
/
memory_segment.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
package mandodb
import (
"encoding/json"
"fmt"
"math"
"os"
"path"
"sort"
"sync"
"sync/atomic"
"github.com/chenjiandongx/mandodb/pkg/sortedlist"
)
type memorySegment struct {
once sync.Once
segment sync.Map
indexMap *memoryIndexMap
labelVs *labelValueSet
outdated map[string]sortedlist.List
outdatedMut sync.Mutex
minTs int64
maxTs int64
seriesCount int64
dataPointsCount int64
}
func newMemorySegment() Segment {
return &memorySegment{
indexMap: newMemoryIndexMap(),
labelVs: newLabelValueSet(),
outdated: make(map[string]sortedlist.List),
minTs: math.MaxInt64,
maxTs: math.MinInt64,
}
}
func (ms *memorySegment) getOrCreateSeries(row *Row) *memorySeries {
v, ok := ms.segment.Load(row.ID())
if ok {
return v.(*memorySeries)
}
atomic.AddInt64(&ms.seriesCount, 1)
newSeries := newSeries(row)
ms.segment.Store(row.ID(), newSeries)
return newSeries
}
func (ms *memorySegment) MinTs() int64 {
return atomic.LoadInt64(&ms.minTs)
}
func (ms *memorySegment) MaxTs() int64 {
return atomic.LoadInt64(&ms.maxTs)
}
func (ms *memorySegment) Frozen() bool {
if globalOpts.onlyMemoryMode {
return false
}
return ms.MaxTs()-ms.MinTs() > int64(globalOpts.segmentDuration.Seconds())
}
func (ms *memorySegment) Type() SegmentType {
return MemorySegmentType
}
func (ms *memorySegment) Close() error {
if ms.dataPointsCount == 0 || globalOpts.onlyMemoryMode {
return nil
}
return writeToDisk(ms)
}
func (ms *memorySegment) Cleanup() error {
return nil
}
func (ms *memorySegment) Load() Segment {
return ms
}
func (ms *memorySegment) InsertRows(rows []*Row) {
for _, row := range rows {
ms.labelVs.Set(metricName, row.Metric)
for _, label := range row.Labels {
ms.labelVs.Set(label.Name, label.Value)
}
row.Labels = row.Labels.AddMetricName(row.Metric)
row.Labels.Sorted()
series := ms.getOrCreateSeries(row)
dp := series.Append(&row.Point)
if dp != nil {
ms.outdatedMut.Lock()
if _, ok := ms.outdated[row.ID()]; !ok {
ms.outdated[row.ID()] = sortedlist.NewTree()
}
ms.outdated[row.ID()].Add(row.Point.Ts, row.Point)
ms.outdatedMut.Unlock()
}
if atomic.LoadInt64(&ms.minTs) >= row.Point.Ts {
atomic.StoreInt64(&ms.minTs, row.Point.Ts)
}
if atomic.LoadInt64(&ms.maxTs) <= row.Point.Ts {
atomic.StoreInt64(&ms.maxTs, row.Point.Ts)
}
atomic.AddInt64(&ms.dataPointsCount, 1)
ms.indexMap.UpdateIndex(row.ID(), row.Labels)
}
}
func (ms *memorySegment) QueryLabelValues(label string) []string {
return ms.labelVs.Get(label)
}
func (ms *memorySegment) QuerySeries(lms LabelMatcherSet) ([]LabelSet, error) {
matchSids := ms.indexMap.MatchSids(ms.labelVs, lms)
ret := make([]LabelSet, 0)
for _, sid := range matchSids {
b, _ := ms.segment.Load(sid)
series := b.(*memorySeries)
ret = append(ret, series.labels)
}
return ret, nil
}
func (ms *memorySegment) QueryRange(lms LabelMatcherSet, start, end int64) ([]MetricRet, error) {
matchSids := ms.indexMap.MatchSids(ms.labelVs, lms)
ret := make([]MetricRet, 0, len(matchSids))
for _, sid := range matchSids {
b, _ := ms.segment.Load(sid)
series := b.(*memorySeries)
points := series.Get(start, end)
ms.outdatedMut.Lock()
v, ok := ms.outdated[sid]
if ok {
iter := v.Range(start, end)
for iter.Next() {
points = append(points, iter.Value().(Point))
}
}
ms.outdatedMut.Unlock()
ret = append(ret, MetricRet{
Labels: series.labels,
Points: points,
})
}
return ret, nil
}
func (ms *memorySegment) Marshal() ([]byte, []byte, error) {
sids := make(map[string]uint32)
startOffset := 0
size := 0
dataBuf := make([]byte, 0)
// TOC 占位符 用于后面标记 dataBytes / metaBytes 长度
dataBuf = append(dataBuf, make([]byte, uint64Size*2)...)
meta := Metadata{MinTs: ms.minTs, MaxTs: ms.maxTs}
// key: sid
// value: series entity
ms.segment.Range(func(key, value interface{}) bool {
sid := key.(string)
sids[sid] = uint32(size)
size++
series := value.(*memorySeries)
meta.sidRelatedLabels = append(meta.sidRelatedLabels, series.labels)
ms.outdatedMut.Lock()
v, ok := ms.outdated[sid]
ms.outdatedMut.Unlock()
var dataBytes []byte
if ok {
dataBytes = ByteCompress(series.MergeOutdatedList(v).Bytes())
} else {
dataBytes = ByteCompress(series.Bytes())
}
dataBuf = append(dataBuf, dataBytes...)
endOffset := startOffset + len(dataBytes)
meta.Series = append(meta.Series, metaSeries{
Sid: key.(string),
StartOffset: uint64(startOffset),
EndOffset: uint64(endOffset),
})
startOffset = endOffset
return true
})
labelIdx := make([]seriesWithLabel, 0)
// key: Label.MarshalName()
// value: sids...
ms.indexMap.Range(func(key string, value *memorySidSet) {
l := make([]uint32, 0)
for _, s := range value.List() {
l = append(l, sids[s])
}
sort.Slice(l, func(i, j int) bool {
return l[i] < l[j]
})
labelIdx = append(labelIdx, seriesWithLabel{Name: key, Sids: l})
})
meta.Labels = labelIdx
metaBytes, err := MarshalMeta(meta)
if err != nil {
return nil, nil, err
}
metalen := len(metaBytes)
desc := &Desc{
SeriesCount: ms.seriesCount,
DataPointsCount: ms.dataPointsCount,
MaxTs: ms.maxTs,
MinTs: ms.minTs,
}
descBytes, _ := json.MarshalIndent(desc, "", " ")
dataLen := len(dataBuf) - (uint64Size * 2)
dataBuf = append(dataBuf, metaBytes...)
// TOC 写入
encf := newEncbuf()
encf.MarshalUint64(uint64(dataLen))
dataLenBs := encf.Bytes()
copy(dataBuf[:uint64Size], dataLenBs[:uint64Size])
encf.Reset()
encf.MarshalUint64(uint64(metalen))
metaLenBs := encf.Bytes()
copy(dataBuf[uint64Size:uint64Size*2], metaLenBs[:uint64Size])
return dataBuf, descBytes, nil
}
func mkdir(d string) {
if _, err := os.Stat(d); !os.IsNotExist(err) {
return
}
if err := os.MkdirAll(d, os.ModePerm); err != nil {
panic(fmt.Sprintf("BUG: failed to create dir: %s", d))
}
}
func writeToDisk(segment *memorySegment) error {
dataBytes, descBytes, err := segment.Marshal()
if err != nil {
return fmt.Errorf("failed to marshal segment: %s", err.Error())
}
writeFile := func(f string, data []byte) error {
if isFileExist(f) {
return fmt.Errorf("%s file is already exists", f)
}
fd, err := os.OpenFile(f, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
defer fd.Close()
_, err = fd.Write(data)
return err
}
dn := dirname(segment.MinTs(), segment.MaxTs())
mkdir(dn)
if err := writeFile(path.Join(dn, "data"), dataBytes); err != nil {
return err
}
// 这里的 meta.json 只是描述了一些简单的信息 并非全局定义的 MetaData
if err := writeFile(path.Join(dn, "meta.json"), descBytes); err != nil {
return err
}
return nil
}