forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
251 lines (216 loc) · 6.47 KB
/
file.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
package input
import (
"context"
"errors"
"io"
"os"
"strings"
"sync"
"time"
"github.com/dafanshu/benthos/v3/internal/codec"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/internal/filepath"
"github.com/dafanshu/benthos/v3/lib/input/reader"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/message"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeFile] = TypeSpec{
constructor: fromSimpleConstructor(NewFile),
Summary: `
Consumes data from files on disk, emitting messages according to a chosen codec.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldString("paths", "A list of paths to consume sequentially. Glob patterns are supported, including super globs (double star).").Array(),
codec.ReaderDocs,
docs.FieldAdvanced("max_buffer", "The largest token size expected when consuming delimited files."),
docs.FieldDeprecated("path"),
docs.FieldDeprecated("delimiter"),
docs.FieldDeprecated("multipart"),
docs.FieldAdvanced("delete_on_finish", "Whether to delete consumed files from the disk once they are fully consumed."),
},
Description: `
### Metadata
This input adds the following metadata fields to each message:
` + "```text" + `
- path
` + "```" + `
You can access these metadata fields using
[function interpolation](/docs/configuration/interpolation#metadata).`,
Categories: []Category{
CategoryLocal,
},
Examples: []docs.AnnotatedExample{
{
Title: "Read a Bunch of CSVs",
Summary: "If we wished to consume a directory of CSV files as structured documents we can use a glob pattern and the `csv` codec:",
Config: `
input:
file:
paths: [ ./data/*.csv ]
codec: csv
`,
},
},
}
}
//------------------------------------------------------------------------------
// FileConfig contains configuration values for the File input type.
type FileConfig struct {
Path string `json:"path" yaml:"path"`
Paths []string `json:"paths" yaml:"paths"`
Codec string `json:"codec" yaml:"codec"`
Multipart bool `json:"multipart" yaml:"multipart"`
MaxBuffer int `json:"max_buffer" yaml:"max_buffer"`
Delim string `json:"delimiter" yaml:"delimiter"`
DeleteOnFinish bool `json:"delete_on_finish" yaml:"delete_on_finish"`
}
// NewFileConfig creates a new FileConfig with default values.
func NewFileConfig() FileConfig {
return FileConfig{
Path: "",
Paths: []string{},
// TODO: V4 change this default
Codec: "lines",
Multipart: false,
MaxBuffer: 1000000,
Delim: "",
DeleteOnFinish: false,
}
}
//------------------------------------------------------------------------------
// NewFile creates a new File input type.
func NewFile(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
if len(conf.File.Path) > 0 {
conf.File.Paths = append(conf.File.Paths, conf.File.Path)
}
if len(conf.File.Delim) > 0 {
conf.File.Codec = "delim:" + conf.File.Delim
}
if conf.File.Multipart && !strings.HasSuffix(conf.File.Codec, "/multipart") {
conf.File.Codec += "/multipart"
}
rdr, err := newFileConsumer(conf.File, log)
if err != nil {
return nil, err
}
return NewAsyncReader(TypeFile, true, reader.NewAsyncPreserver(rdr), log, stats)
}
//------------------------------------------------------------------------------
type fileConsumer struct {
log log.Modular
paths []string
scannerCtor codec.ReaderConstructor
scannerMut sync.Mutex
scanner codec.Reader
currentPath string
delete bool
}
func newFileConsumer(conf FileConfig, log log.Modular) (*fileConsumer, error) {
expandedPaths, err := filepath.Globs(conf.Paths)
if err != nil {
return nil, err
}
codecConf := codec.NewReaderConfig()
codecConf.MaxScanTokenSize = conf.MaxBuffer
ctor, err := codec.GetReader(conf.Codec, codecConf)
if err != nil {
return nil, err
}
return &fileConsumer{
log: log,
scannerCtor: ctor,
paths: expandedPaths,
delete: conf.DeleteOnFinish,
}, nil
}
// ConnectWithContext does nothing as we don't have a concept of a connection
// with this input.
func (f *fileConsumer) ConnectWithContext(ctx context.Context) error {
return nil
}
func (f *fileConsumer) getReader(ctx context.Context) (codec.Reader, string, error) {
f.scannerMut.Lock()
defer f.scannerMut.Unlock()
if f.scanner != nil {
return f.scanner, f.currentPath, nil
}
if len(f.paths) == 0 {
return nil, "", types.ErrTypeClosed
}
nextPath := f.paths[0]
file, err := os.Open(nextPath)
if err != nil {
return nil, "", err
}
if f.scanner, err = f.scannerCtor(nextPath, file, func(ctx context.Context, err error) error {
if err == nil && f.delete {
return os.Remove(nextPath)
}
return nil
}); err != nil {
file.Close()
return nil, "", err
}
f.currentPath = nextPath
f.paths = f.paths[1:]
f.log.Infof("Consuming from file '%v'\n", nextPath)
return f.scanner, f.currentPath, nil
}
// ReadWithContext attempts to read a new message from the target S3 bucket.
func (f *fileConsumer) ReadWithContext(ctx context.Context) (types.Message, reader.AsyncAckFn, error) {
for {
scanner, currentPath, err := f.getReader(ctx)
if err != nil {
return nil, nil, err
}
parts, codecAckFn, err := scanner.Next(ctx)
if err != nil {
if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
err = types.ErrTimeout
}
if err != types.ErrTimeout {
f.scanner.Close(ctx)
f.scanner = nil
}
if errors.Is(err, io.EOF) {
continue
}
return nil, nil, err
}
msg := message.New(nil)
for _, part := range parts {
if len(part.Get()) > 0 {
part.Metadata().Set("path", currentPath)
msg.Append(part)
}
}
if msg.Len() == 0 {
_ = codecAckFn(ctx, nil)
return nil, nil, types.ErrTimeout
}
return msg, func(rctx context.Context, res types.Response) error {
return codecAckFn(rctx, res.Error())
}, nil
}
}
// CloseAsync begins cleaning up resources used by this reader asynchronously.
func (f *fileConsumer) CloseAsync() {
go func() {
f.scannerMut.Lock()
if f.scanner != nil {
f.scanner.Close(context.Background())
f.scanner = nil
f.paths = nil
}
f.scannerMut.Unlock()
}()
}
// WaitForClose will block until either the reader is closed or a specified
// timeout occurs.
func (f *fileConsumer) WaitForClose(time.Duration) error {
return nil
}