Skip to content

Commit f4e4bb1

Browse files
committed
fixes in opening the file
1 parent feb7075 commit f4e4bb1

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

filebeat/input/filestream/input.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
input "github.com/elastic/beats/v7/filebeat/input/v2"
3030
"github.com/elastic/beats/v7/libbeat/beat"
3131
"github.com/elastic/beats/v7/libbeat/common"
32+
"github.com/elastic/beats/v7/libbeat/common/cleanup"
3233
"github.com/elastic/beats/v7/libbeat/common/match"
3334
"github.com/elastic/beats/v7/libbeat/feature"
3435
"github.com/elastic/beats/v7/libbeat/logp"
@@ -225,12 +226,25 @@ func (inp *filestream) open(log *logp.Logger, canceler input.Canceler, path stri
225226
// is returned and the harvester is closed. The file will be picked up again the next time
226227
// the file system is scanned
227228
func (inp *filestream) openFile(log *logp.Logger, path string, offset int64) (*os.File, error) {
229+
fi, err := os.Stat(path)
230+
if err != nil {
231+
return nil, fmt.Errorf("failed to stat source file %s: %s", path, err)
232+
}
233+
234+
// it must be checked if the file is not a named pipe before we try to open it
235+
// if it is a named pipe os.OpenFile fails, so there is no need to try opening it.
236+
if fi.Mode()&os.ModeNamedPipe != 0 {
237+
return nil, fmt.Errorf("failed to open file %s, named pipes are not supported", fi.Name())
238+
}
239+
240+
ok := false
228241
f, err := os.OpenFile(path, os.O_RDONLY, os.FileMode(0))
229242
if err != nil {
230243
return nil, fmt.Errorf("failed opening %s: %s", path, err)
231244
}
245+
defer cleanup.IfNot(&ok, cleanup.IgnoreError(f.Close))
232246

233-
fi, err := f.Stat()
247+
fi, err = f.Stat()
234248
if err != nil {
235249
return nil, fmt.Errorf("failed to stat source file %s: %s", path, err)
236250
}
@@ -246,7 +260,6 @@ func (inp *filestream) openFile(log *logp.Logger, path string, offset int64) (*o
246260
}
247261
err = inp.initFileOffset(f, offset)
248262
if err != nil {
249-
f.Close()
250263
return nil, err
251264
}
252265

@@ -258,6 +271,7 @@ func (inp *filestream) openFile(log *logp.Logger, path string, offset int64) (*o
258271
}
259272
return nil, fmt.Errorf("initialising encoding for '%v' failed: %v", f, err)
260273
}
274+
ok = true
261275

262276
return f, nil
263277
}
@@ -267,10 +281,6 @@ func checkFileBeforeOpening(fi os.FileInfo) error {
267281
return fmt.Errorf("tried to open non regular file: %q %s", fi.Mode(), fi.Name())
268282
}
269283

270-
if fi.Mode()&os.ModeNamedPipe != 0 {
271-
return fmt.Errorf("failed to open file %s, named pipes are not supported", fi.Name())
272-
}
273-
274284
return nil
275285
}
276286

0 commit comments

Comments
 (0)