Skip to content

Commit

Permalink
Write metrics to a cached file and rename it - avoids race conditions…
Browse files Browse the repository at this point in the history
… with node_exporter
  • Loading branch information
rcowham committed Apr 7, 2021
1 parent 465a998 commit 521a423
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions p4prom.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,29 @@ func readServerID(logger *logrus.Logger, instance string) string {
return ""
}

// Writes metrics to appropriate file
// Writes metrics to appropriate file - writes to temp file first and renames it after
func (p4p *P4Prometheus) writeMetricsFile(metrics []byte) {
var f *os.File
var err error
f, err = os.Create(p4p.config.MetricsOutput)
tmpFile := p4p.config.MetricsOutput + ".tmp"
f, err = os.Create(tmpFile)
if err != nil {
p4p.logger.Errorf("Error opening %s: %v", p4p.config.MetricsOutput, err)
p4p.logger.Errorf("Error opening %s: %v", tmpFile, err)
return
}
f.Write(bytes.ToValidUTF8(metrics, []byte{'?'}))
err = f.Close()
if err != nil {
p4p.logger.Errorf("Error closing file: %v", err)
}
err = os.Chmod(p4p.config.MetricsOutput, 0644)
err = os.Chmod(tmpFile, 0644)
if err != nil {
p4p.logger.Errorf("Error chmod-ing file: %v", err)
}
err = os.Rename(tmpFile, p4p.config.MetricsOutput)
if err != nil {
p4p.logger.Errorf("Error renaming: %s to %s - %v", tmpFile, p4p.config.MetricsOutput, err)
}
}

// Returns a tailer object for specified file
Expand Down

0 comments on commit 521a423

Please sign in to comment.