Skip to content

Commit

Permalink
Fix open error handling in file output (#5540)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielnelson authored Mar 22, 2019
1 parent fa65a82 commit 99a390b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 23 deletions.
11 changes: 3 additions & 8 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,10 +129,7 @@ func (a *Agent) Run(ctx context.Context) error {
wg.Wait()

log.Printf("D! [agent] Closing outputs")
err = a.closeOutputs()
if err != nil {
return err
}
a.closeOutputs()

log.Printf("D! [agent] Stopped Successfully")
return nil
Expand Down Expand Up @@ -589,12 +586,10 @@ func (a *Agent) connectOutputs(ctx context.Context) error {
}

// closeOutputs closes all outputs.
func (a *Agent) closeOutputs() error {
var err error
func (a *Agent) closeOutputs() {
for _, output := range a.Config.Outputs {
err = output.Output.Close()
output.Close()
}
return err
}

// startServiceInputs starts all service inputs.
Expand Down
7 changes: 7 additions & 0 deletions internal/models/running_output.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ func (ro *RunningOutput) WriteBatch() error {
return nil
}

func (ro *RunningOutput) Close() {
err := ro.Output.Close()
if err != nil {
log.Printf("E! [outputs.%s] Error closing output: %v", ro.Name, err)
}
}

func (ro *RunningOutput) write(metrics []telegraf.Metric) error {
start := time.Now()
err := ro.Output.Write(metrics)
Expand Down
22 changes: 7 additions & 15 deletions plugins/outputs/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,11 @@ func (f *File) Connect() error {
if file == "stdout" {
f.writers = append(f.writers, os.Stdout)
} else {
var of *os.File
var err error
if _, err := os.Stat(file); os.IsNotExist(err) {
of, err = os.Create(file)
} else {
of, err = os.OpenFile(file, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
}

of, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend|0644)
if err != nil {
return err
}

f.writers = append(f.writers, of)
f.closers = append(f.closers, of)
}
Expand All @@ -62,16 +56,14 @@ func (f *File) Connect() error {
}

func (f *File) Close() error {
var errS string
var err error
for _, c := range f.closers {
if err := c.Close(); err != nil {
errS += err.Error() + "\n"
errClose := c.Close()
if errClose != nil {
err = errClose
}
}
if errS != "" {
return fmt.Errorf(errS)
}
return nil
return err
}

func (f *File) SampleConfig() string {
Expand Down

0 comments on commit 99a390b

Please sign in to comment.