forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.go
54 lines (43 loc) · 1.36 KB
/
database.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package database
import (
"database/sql"
"github.com/pkg/errors"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/metricbeat/mb"
"github.com/elastic/beats/metricbeat/module/postgresql"
// Register postgresql database/sql driver
_ "github.com/lib/pq"
)
// init registers the MetricSet with the central registry.
// The New method will be called after the setup of the module and before starting to fetch data
func init() {
if err := mb.Registry.AddMetricSet("postgresql", "database", New, postgresql.ParseURL); err != nil {
panic(err)
}
}
// MetricSet type defines all fields of the MetricSet
type MetricSet struct {
mb.BaseMetricSet
}
// New create a new instance of the postgresql database MetricSet.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
return &MetricSet{BaseMetricSet: base}, nil
}
// Fetch methods implements the data gathering and data conversion to the right format
func (m *MetricSet) Fetch() ([]common.MapStr, error) {
db, err := sql.Open("postgres", m.HostData().URI)
if err != nil {
return nil, err
}
defer db.Close()
results, err := postgresql.QueryStats(db, "SELECT * FROM pg_stat_database")
if err != nil {
return nil, errors.Wrap(err, "QueryStats")
}
events := []common.MapStr{}
for _, result := range results {
data, _ := schema.Apply(result)
events = append(events, data)
}
return events, nil
}