telegraf/plugins/inputs/mongodb/mongodb_server.go

52 lines
1.1 KiB
Go
Raw Normal View History

2015-07-07 01:20:11 +00:00
package mongodb
import (
"net/url"
"time"
2016-01-07 20:39:43 +00:00
"github.com/influxdb/telegraf/plugins/inputs"
2015-07-07 01:20:11 +00:00
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Server struct {
Url *url.URL
Session *mgo.Session
lastResult *ServerStatus
}
func (s *Server) getDefaultTags() map[string]string {
tags := make(map[string]string)
tags["hostname"] = s.Url.Host
2015-07-07 01:20:11 +00:00
return tags
}
2016-01-07 20:39:43 +00:00
func (s *Server) gatherData(acc inputs.Accumulator) error {
2015-07-07 01:20:11 +00:00
s.Session.SetMode(mgo.Eventual, true)
s.Session.SetSocketTimeout(0)
result := &ServerStatus{}
err := s.Session.DB("admin").Run(bson.D{{"serverStatus", 1}, {"recordStats", 0}}, result)
if err != nil {
return err
}
defer func() {
s.lastResult = result
}()
result.SampleTime = time.Now()
if s.lastResult != nil && result != nil {
duration := result.SampleTime.Sub(s.lastResult.SampleTime)
durationInSeconds := int64(duration.Seconds())
if durationInSeconds == 0 {
durationInSeconds = 1
}
data := NewMongodbData(
NewStatLine(*s.lastResult, *result, s.Url.Host, true, durationInSeconds),
s.getDefaultTags(),
)
2015-12-19 20:31:22 +00:00
data.AddDefaultStats()
data.flush(acc)
2015-07-07 01:20:11 +00:00
}
return nil
}