From 36e3b2a923e551830b583ecd43c8f9a9726576cf Mon Sep 17 00:00:00 2001 From: Christian Hoffmann Date: Thu, 18 Apr 2019 17:47:04 +0200 Subject: [PATCH] textfile: use opened file's mtime as timestamp (#1326) Previously, the node_textfile_mtime_seconds metric was based on the Fileinfo.ModTime() of the ioutil.ReadDir() return value. This is based on lstat() and therefore has unintended consequences for symlinks (modification time of the symlink instead of the symlink target is returned). It is also racy as the lstat() is performed before reading the file. This commit changes the node_textfile_mtime_seconds metric to be based on a fresh Stat() call on the open file. This eliminates the race and works as expected for symlinks. Fixes #1324. Signed-off-by: Christian Hoffmann --- CHANGELOG.md | 1 + collector/textfile.go | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d86dbcfc..08a9bf4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ ### Changes * [BUGFIX] +* [BUGFIX] Fix node_textfile_mtime_seconds to work properly on symlinks #1326 * [CHANGE] Renamed `interface` label to `device` in netclass collector #1224 * [BUGFIX] Add fallback for missing /proc/1/mounts #1172 * [CHANGE] Add TCPSynRetrans to netstat default filter #1143 diff --git a/collector/textfile.go b/collector/textfile.go index c80de98d..52e88bb7 100644 --- a/collector/textfile.go +++ b/collector/textfile.go @@ -204,9 +204,9 @@ func (c *textFileCollector) Update(ch chan<- prometheus.Metric) error { error = 1.0 continue } + defer file.Close() var parser expfmt.TextParser parsedFamilies, err := parser.TextToMetricFamilies(file) - file.Close() if err != nil { log.Errorf("Error parsing %q: %v", path, err) error = 1.0 @@ -227,7 +227,13 @@ func (c *textFileCollector) Update(ch chan<- prometheus.Metric) error { // Only set this once it has been parsed and validated, so that // a failure does not appear fresh. - mtimes[f.Name()] = f.ModTime() + stat, err := file.Stat() + if err != nil { + log.Errorf("Error stat'ing %q: %v", path, err) + error = 1.0 + continue + } + mtimes[f.Name()] = stat.ModTime() for _, mf := range parsedFamilies { convertMetricFamily(mf, ch)