From a00fc883c377f50816f48b089fcb2f789263f3fc Mon Sep 17 00:00:00 2001 From: KalivarapuReshma Date: Sat, 12 Aug 2017 22:01:31 +0530 Subject: [PATCH] Add metric for timestamp of the files file_sd is using. --- discovery/file/file.go | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/discovery/file/file.go b/discovery/file/file.go index 777201302..911d87039 100644 --- a/discovery/file/file.go +++ b/discovery/file/file.go @@ -19,6 +19,7 @@ import ( "errors" "fmt" "io/ioutil" + "os" "path/filepath" "strings" "time" @@ -35,6 +36,54 @@ import ( const fileSDFilepathLabel = model.MetaLabelPrefix + "filepath" +// TimestampCollector is a Custom Collector for Timestamps of the files. +type TimestampCollector struct { + filenames []string + Description *prometheus.Desc + + logger log.Logger +} + +// Describe method sends the description to the channel. +func (t *TimestampCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- t.Description +} + +// SetFiles changes the filenames of the struct to the paths returned by listfiles(). +func (t *TimestampCollector) SetFiles(files []string) { + t.filenames = files +} + +// Collect creates constant metrics for each file with last modified time of the file. +func (t *TimestampCollector) Collect(ch chan<- prometheus.Metric) { + files := t.filenames + for i := 0; i < len(files); i++ { + info, err := os.Stat(files[i]) + if err != nil { + t.logger.Errorf("Error getting the fileinfo of the file %q: %s", files[i], err) + continue + } + ch <- prometheus.MustNewConstMetric( + t.Description, + prometheus.GaugeValue, + float64(info.ModTime().Unix()), + files[i], + ) + } +} + +// NewTimestampCollector creates a TimestampCollector. +func NewTimestampCollector() *TimestampCollector { + return &TimestampCollector{ + Description: prometheus.NewDesc( + "prometheus_sd_file_timestamp", + "Timestamp of files read by FileSD", + []string{"filename"}, + nil, + ), + } +} + var ( fileSDScanDuration = prometheus.NewSummary( prometheus.SummaryOpts{ @@ -46,11 +95,13 @@ var ( Name: "prometheus_sd_file_read_errors_total", Help: "The number of File-SD read errors.", }) + fileSDTimeStamp = NewTimestampCollector() ) func init() { prometheus.MustRegister(fileSDScanDuration) prometheus.MustRegister(fileSDReadErrorsCount) + prometheus.MustRegister(fileSDTimeStamp) } // Discovery provides service discovery functionality based @@ -195,6 +246,7 @@ func (d *Discovery) refresh(ctx context.Context, ch chan<- []*config.TargetGroup fileSDScanDuration.Observe(time.Since(t0).Seconds()) }() + fileSDTimeStamp.SetFiles(d.listFiles()) ref := map[string]int{} for _, p := range d.listFiles() { tgroups, err := readFile(p)