telegraf/plugins/inputs/mongodb/mongodb_server.go

64 lines
1.4 KiB
Go
Raw Normal View History

2015-07-07 01:20:11 +00:00
package mongodb
import (
2016-04-19 23:16:22 +00:00
"log"
2015-07-07 01:20:11 +00:00
"net/url"
"time"
"github.com/influxdata/telegraf"
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
2016-04-19 23:16:22 +00:00
lastResult *MongoStatus
2015-07-07 01:20:11 +00:00
}
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
}
func (s *Server) gatherData(acc telegraf.Accumulator) error {
2015-07-07 01:20:11 +00:00
s.Session.SetMode(mgo.Eventual, true)
s.Session.SetSocketTimeout(0)
2016-04-19 23:16:22 +00:00
result_server := &ServerStatus{}
err := s.Session.DB("admin").Run(bson.D{{"serverStatus", 1}, {"recordStats", 0}}, result_server)
2015-07-07 01:20:11 +00:00
if err != nil {
return err
}
2016-04-19 23:16:22 +00:00
result_repl := &ReplSetStatus{}
err = s.Session.DB("admin").Run(bson.D{{"replSetGetStatus", 1}}, result_repl)
if err != nil {
log.Println("Not gathering replica set status, member not in replica set")
}
result := &MongoStatus{
ServerStatus: result_server,
ReplSetStatus: result_repl,
}
2015-07-07 01:20:11 +00:00
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
}