-
Notifications
You must be signed in to change notification settings - Fork 12
/
feed_files.go
473 lines (402 loc) · 11.5 KB
/
feed_files.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Copyright 2014-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbgt
import (
"fmt"
"hash"
"hash/crc32"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
log "github.com/couchbase/clog"
)
const FILES_FEED_SLEEP_START_MS = 5000
const FILES_FEED_BACKOFF_FACTOR = 1.5
const FILES_FEED_MAX_SLEEP_MS = 1000 * 60 * 5 // 5 minutes.
func init() {
RegisterFeedType("files", &FeedType{
Start: StartFilesFeed,
Partitions: FilesFeedPartitions,
Public: true,
Description: "general/files" +
" - files under a dataDir subdirectory tree will be the data source",
StartSample: &FilesFeedParams{
RegExps: []string{".txt$", ".md$"},
SleepStartMS: FILES_FEED_SLEEP_START_MS,
BackoffFactor: FILES_FEED_BACKOFF_FACTOR,
MaxSleepMS: FILES_FEED_MAX_SLEEP_MS,
},
})
}
// FilesFeed is a Feed interface implementation that that emits file
// contents from a local subdirectory tree.
//
// The subdirectory tree lives under the dataDir...
//
// <dataDir>/<sourceName/**
//
// FilesFeed supports optional regexp patterns to allow you to filter
// for only the file paths that you want.
//
// Limitations:
//
// - Only a small number of files will work well (hundreds to low
// thousands, not millions).
//
// - FilesFeed polls for file modification timestamp changes as a
// poor-man's approach instead of properly tracking sequence numbers.
// That has implications such as whenever a FilesFeed (re-)starts
// (e.g., the process restarts), the FilesFeed will re-emits all files
// and then track the max modification timestamp going forwards as it
// regularly polls for file changes.
type FilesFeed struct {
mgr *Manager
name string
indexName string
sourceName string
params *FilesFeedParams
dests map[string]Dest
disable bool
m sync.Mutex
closeCh chan struct{}
}
// FilesFeedParams represents the JSON expected as the sourceParams
// for a FilesFeed.
type FilesFeedParams struct {
RegExps []string `json:"regExps"`
MaxFileSize int64 `json:"maxFileSize"`
NumPartitions int `json:"numPartitions"`
SleepStartMS int `json:"sleepStartMS"`
BackoffFactor float32 `json:"backoffFactor"`
MaxSleepMS int `json:"maxSleepMS"`
}
// FileDoc represents the JSON for each file/document that will be
// emitted by a FilesFeed as a data source.
type FileDoc struct {
Name string `json:"name"`
Path string `json:"path"` // Path relative to the source name.
Contents string `json:"contents"`
}
// StartFilesFeed starts a FilesFeed and is the the callback function
// registered at init/startup time.
func StartFilesFeed(mgr *Manager, feedName, indexName, indexUUID,
sourceType, sourceName, sourceUUID, params string,
dests map[string]Dest) error {
feed, err := NewFilesFeed(mgr, feedName, indexName, sourceName,
params, dests, mgr.tagsMap != nil && !mgr.tagsMap["feed"])
if err != nil {
return fmt.Errorf("feed_files: NewFilesFeed,"+
" feedName: %s, err: %v", feedName, err)
}
err = feed.Start()
if err != nil {
return fmt.Errorf("feed_files: could not start,"+
" feedName: %s, err: %v", feedName, err)
}
err = mgr.registerFeed(feed)
if err != nil {
feed.Close()
return err
}
return nil
}
// NewFilesFeed creates a ready-to-be-started FilesFeed.
func NewFilesFeed(mgr *Manager, name, indexName, sourceName,
paramsStr string, dests map[string]Dest, disable bool) (
*FilesFeed, error) {
if sourceName == "" {
return nil, fmt.Errorf("feed_files: missing source name")
}
if strings.Index(sourceName, "..") >= 0 {
return nil, fmt.Errorf("feed_files: disallowed source name,"+
" name: %s, sourceName: %q", name, sourceName)
}
params := &FilesFeedParams{}
if paramsStr != "" {
err := UnmarshalJSON([]byte(paramsStr), params)
if err != nil {
return nil, err
}
}
return &FilesFeed{
mgr: mgr,
name: name,
indexName: indexName,
sourceName: sourceName,
params: params,
dests: dests,
disable: disable,
closeCh: make(chan struct{}),
}, nil
}
func (t *FilesFeed) Name() string {
return t.name
}
func (t *FilesFeed) IndexName() string {
return t.indexName
}
func (t *FilesFeed) Start() error {
if t.disable {
log.Printf("feed_files: disable, name: %s", t.Name())
return nil
}
startSleepMS := t.params.SleepStartMS
if startSleepMS <= 0 {
startSleepMS = FILES_FEED_SLEEP_START_MS
}
backoffFactor := t.params.BackoffFactor
if backoffFactor <= 0 {
backoffFactor = FILES_FEED_BACKOFF_FACTOR
}
maxSleepMS := t.params.MaxSleepMS
if maxSleepMS <= 0 {
maxSleepMS = FILES_FEED_MAX_SLEEP_MS
}
numPartitions := t.params.NumPartitions
if numPartitions < 0 {
numPartitions = 0
}
partitions := make([]string, numPartitions)
for i := 0; i < len(partitions); i++ {
partitions[i] = strconv.Itoa(i)
}
go func() {
initTime := time.Now()
initTimeMicroSecs := initTime.UnixNano() / int64(1000)
// TODO: NOTE: We're assuming (lazily, incorrectly) that this
// way of initializing a sequence number never goes downwards,
// even during fast restarts or clock changes or node
// rebalances/reassignments.
seqs := map[string]uint64{}
for partition := range t.dests {
seqs[partition] = uint64(initTimeMicroSecs)
}
var prevStartTime time.Time
ExponentialBackoffLoop(t.Name(),
func() int {
t.m.Lock()
closeCh := t.closeCh
t.m.Unlock()
select {
case <-closeCh:
return -1
default:
}
h := crc32.NewIEEE()
startTime := time.Now()
progress := false
paths, err := FilesFindMatches(t.mgr.DataDir(),
t.sourceName, t.params.RegExps, prevStartTime,
t.params.MaxFileSize)
if err != nil {
log.Warnf("feed_files, FilesFindMatches, err: %v", err)
return -1
}
seqDeltaMax := uint64(0)
seqEnds := map[string]uint64{}
for _, path := range paths {
partition := FilesPathToPartition(h, partitions, path)
if t.dests[partition] == nil {
continue
}
seq := seqs[partition]
seqEnd, exists := seqEnds[partition]
if exists {
seqEnd = seqEnd + 1
} else {
seqEnd = seq
}
seqEnds[partition] = seqEnd
if seqDeltaMax < seqEnd-seq {
seqDeltaMax = seqEnd - seq
}
}
snapshotSent := map[string]bool{}
for _, path := range paths {
select {
case <-closeCh:
return -1
default:
}
partition := FilesPathToPartition(h, partitions, path)
dest := t.dests[partition]
if dest == nil {
continue
}
seqCur := seqs[partition]
seqs[partition] = seqCur + 1
buf, err := os.ReadFile(path)
if err != nil {
log.Warnf("feed_files: read file,"+
" name: %s, path: %s, err: %v",
t.Name(), path, err)
continue
}
jbuf, err := MarshalJSON(FileDoc{
Name: filepath.Base(path),
Path: path,
Contents: string(buf),
})
if err != nil {
log.Warnf("feed_files: json marshal file,"+
" name: %s, path: %s, err: %v",
t.Name(), path, err)
continue
}
if !snapshotSent[partition] {
err = dest.SnapshotStart(partition, seqCur,
seqEnds[partition])
if err != nil {
log.Warnf("feed_files: SnapshotStart,"+
" name: %s, partition: %s, seqCur: %d,"+
" seqEnd: %d, err: %v", t.Name(), partition,
seqCur, seqEnds[partition], err)
return -1
}
snapshotSent[partition] = true
}
pathBuf := []byte(path)
err = dest.DataUpdate(partition, pathBuf, seqCur,
jbuf, 0, DEST_EXTRAS_TYPE_NIL, nil)
if err != nil {
log.Warnf("feed_files: DataUpdate,"+
" name: %s, path: %s, partition: %s,"+
" seqCur: %d, err: %v", t.Name(), path,
partition, seqCur, err)
return -1
}
progress = true
}
prevStartTime = startTime
// NOTE: We may need to sleep a certain amount in case
// there were tons of file updates/mutations, and we
// want to reduce the window of potentially repeating
// sequence numbers. The window still exists if we
// crash and quickly restart during the sleep, where
// the restarted process might have a
// lower-than-wanted initTime.
wantTime := initTime // Copy, because Add() mutates.
wantTime.Add(time.Duration(int64(seqDeltaMax)))
currTime := time.Now()
if wantTime.After(currTime) {
time.Sleep(wantTime.Sub(currTime))
}
if progress {
return 1
}
return 0
},
startSleepMS,
backoffFactor,
maxSleepMS)
}()
return nil
}
func (t *FilesFeed) Close() error {
t.m.Lock()
if t.closeCh != nil {
close(t.closeCh)
t.closeCh = nil
}
t.m.Unlock()
return nil
}
func (t *FilesFeed) Dests() map[string]Dest {
return t.dests
}
func (t *FilesFeed) Stats(w io.Writer) error {
_, err := w.Write([]byte("{}"))
return err
}
// -----------------------------------------------------
// FilesFeedPartitions returns the partitions, controlled by
// FilesFeedParams.NumPartitions, for a FilesFeed instance.
func FilesFeedPartitions(sourceType, sourceName, sourceUUID, sourceParams,
server string, options map[string]string) ([]string, error) {
ffp := &FilesFeedParams{}
if sourceParams != "" {
err := UnmarshalJSON([]byte(sourceParams), ffp)
if err != nil {
return nil, fmt.Errorf("feed_files:"+
" could not parse sourceParams: %s, err: %v",
sourceParams, err)
}
}
rv := make([]string, ffp.NumPartitions)
for i := 0; i < ffp.NumPartitions; i++ {
rv[i] = strconv.Itoa(i)
}
return rv, nil
}
// -----------------------------------------------------
// FilesFindMatches finds all leaf file paths in a subdirectory tree
// that match any in an optional array of regExps (regular expression
// strings). If regExps is nil, though, then all leaf file paths are
// considered as a potential candidate match. The regExps are with
// respect to a path from filepath.Walk().
//
// Additionally, a candidate file must have been modified since a
// modTimeGTE and (if maxSize is > 0) should have size that's <=
// maxSize.
func FilesFindMatches(dataDir, sourceName string,
regExps []string, modTimeGTE time.Time, maxSize int64) (
[]string, error) {
walkPath, err := filepath.EvalSymlinks(dataDir +
string(os.PathSeparator) + "files" +
string(os.PathSeparator) + sourceName)
if err != nil {
return nil, err
}
pathsOk := []string(nil)
err = filepath.Walk(walkPath,
func(path string, fi os.FileInfo, err error) error {
if err != nil ||
fi.IsDir() ||
fi.ModTime().Before(modTimeGTE) ||
(maxSize > 0 && fi.Size() > maxSize) {
return nil
}
if len(regExps) <= 0 {
pathsOk = append(pathsOk, path)
return nil
}
for _, reStr := range regExps {
matched, err := regexp.MatchString(reStr, path)
if err != nil {
return fmt.Errorf("feed_files, MatchString,"+
" reStr: %s, path: %s, err: %v",
reStr, path, err)
}
if matched {
pathsOk = append(pathsOk, path)
return nil
}
}
return nil
})
if err != nil {
return nil, err
}
return pathsOk, nil
}
// FilesPathToPartition hashes a file path to a partition.
func FilesPathToPartition(h hash.Hash32,
partitions []string, path string) string {
if len(partitions) <= 0 {
return ""
}
h.Reset()
io.WriteString(h, path)
i := h.Sum32() % uint32(len(partitions))
return partitions[i]
}