forked from mackerelio/mackerel-agent-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
263 lines (232 loc) · 7.44 KB
/
postgres.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"database/sql"
"flag"
"fmt"
"os"
_ "github.com/lib/pq"
mp "github.com/mackerelio/go-mackerel-plugin"
"github.com/mackerelio/mackerel-agent/logging"
)
var logger = logging.GetLogger("metrics.plugin.postgres")
var graphdef map[string](mp.Graphs) = map[string](mp.Graphs){
"postgres.connections": mp.Graphs{
Label: "Postgres Connections",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "active", Label: "Active", Diff: false, Stacked: true},
mp.Metrics{Name: "waiting", Label: "Waiting", Diff: false, Stacked: true},
},
},
"postgres.commits": mp.Graphs{
Label: "Postgres Commits",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "xact_commit", Label: "Xact Commit", Diff: true, Stacked: false},
mp.Metrics{Name: "xact_rollback", Label: "Xact Rollback", Diff: true, Stacked: false},
},
},
"postgres.blocks": mp.Graphs{
Label: "Postgres Blocks",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "blks_read", Label: "Blocks Read", Diff: true, Stacked: false},
mp.Metrics{Name: "blks_hit", Label: "Blocks Hit", Diff: true, Stacked: false},
},
},
"postgres.rows": mp.Graphs{
Label: "Postgres Rows",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "tup_returned", Label: "Returned Rows", Diff: true, Stacked: false},
mp.Metrics{Name: "tup_fetched", Label: "Fetched Rows", Diff: true, Stacked: true},
mp.Metrics{Name: "tup_inserted", Label: "Inserted Rows", Diff: true, Stacked: true},
mp.Metrics{Name: "tup_updated", Label: "Updated Rows", Diff: true, Stacked: true},
mp.Metrics{Name: "tup_deleted", Label: "Deleted Rows", Diff: true, Stacked: true},
},
},
"postgres.size": mp.Graphs{
Label: "Postgres Data Size",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "total_size", Label: "Total Size", Diff: false, Stacked: false},
},
},
"postgres.deadlocks": mp.Graphs{
Label: "Postgres Dead Locks",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "deadlocks", Label: "Deadlocks", Diff: true, Stacked: false},
},
},
"postgres.iotime": mp.Graphs{
Label: "Postgres Block I/O time",
Unit: "float",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "blk_read_time", Label: "Block Read Time (ms)", Diff: true, Stacked: false},
mp.Metrics{Name: "blk_write_time", Label: "Block Write Time (ms)", Diff: true, Stacked: false},
},
},
"postgres.tempfile": mp.Graphs{
Label: "Postgres Temporary file",
Unit: "integer",
Metrics: [](mp.Metrics){
mp.Metrics{Name: "temp_bytes", Label: "Temporary file size (byte)", Diff: true, Stacked: false},
},
},
}
type PostgresPlugin struct {
Host string
Port string
Username string
Password string
SSLmode string
Timeout int
Tempfile string
}
func FetchStatDatabase(db *sql.DB) (map[string]float64, error) {
rows, err := db.Query(`
select xact_commit, xact_rollback, blks_read, blks_hit, blk_read_time, blk_write_time,
tup_returned, tup_fetched, tup_inserted, tup_updated, tup_deleted, deadlocks, temp_bytes
from pg_stat_database
`)
if err != nil {
logger.Errorf("Failed to select pg_stat_database. %s", err)
return nil, err
}
stat := make(map[string]float64)
for rows.Next() {
var xact_commit, xact_rollback, blks_read, blks_hit, blk_read_time, blk_write_time int
var tup_returned, tup_fetched, tup_inserted, tup_updated, tup_deleted, deadlocks, temp_bytes int
if err := rows.Scan(&xact_commit, &xact_rollback, &blks_read, &blks_hit, &blk_read_time, &blk_write_time, &tup_returned, &tup_fetched, &tup_inserted, &tup_updated, &tup_deleted, &deadlocks, &temp_bytes); err != nil {
logger.Warningf("Failed to scan. %s", err)
continue
}
stat["xact_commit"] += float64(xact_commit)
stat["xact_rollback"] += float64(xact_rollback)
stat["blks_read"] += float64(blks_read)
stat["blks_hit"] += float64(blks_hit)
stat["blk_read_time"] += float64(blks_hit)
stat["blk_write_time"] += float64(blks_hit)
stat["tup_returned"] += float64(tup_returned)
stat["tup_fetched"] += float64(tup_fetched)
stat["tup_inserted"] += float64(tup_inserted)
stat["tup_updated"] += float64(tup_updated)
stat["tup_deleted"] += float64(tup_deleted)
stat["deadlocks"] += float64(deadlocks)
stat["temp_bytes"] += float64(temp_bytes)
}
return stat, nil
}
func FetchConnections(db *sql.DB) (map[string]float64, error) {
rows, err := db.Query(`
select count(*), waiting from pg_stat_activity group by waiting
`)
if err != nil {
logger.Errorf("Failed to select pg_stat_activity. %s", err)
return nil, err
}
stat := make(map[string]float64)
for rows.Next() {
var count int
var waiting string
if err := rows.Scan(&count, &waiting); err != nil {
logger.Warningf("Failed to scan %s", err)
continue
}
if waiting != "" {
stat["active"] += float64(count)
} else {
stat["waiting"] += float64(count)
}
}
return stat, nil
}
func FetchDatabaseSize(db *sql.DB) (map[string]float64, error) {
rows, err := db.Query("select sum(pg_database_size(datname)) as dbsize from pg_database")
if err != nil {
logger.Errorf("Failed to select pg_database_size. %s", err)
return nil, err
}
stat := make(map[string]float64)
for rows.Next() {
var dbsize int
if err := rows.Scan(&dbsize); err != nil {
logger.Warningf("Failed to scan %s", err)
continue
}
stat["total_size"] += float64(dbsize)
}
return stat, nil
}
func mergeStat(dst, src map[string]float64) {
for k, v := range src {
dst[k] = v
}
}
func (p PostgresPlugin) FetchMetrics() (map[string]float64, error) {
db, err := sql.Open("postgres", fmt.Sprintf("user=%s password=%s host=%s port=%s sslmode=%s connect_timeout=%d", p.Username, p.Password, p.Host, p.Port, p.SSLmode, p.Timeout))
if err != nil {
logger.Errorf("FetchMetrics: ", err)
return nil, err
}
defer db.Close()
statStatDatabase, err := FetchStatDatabase(db)
if err != nil {
return nil, err
}
statConnections, err := FetchConnections(db)
if err != nil {
return nil, err
}
statDatabaseSize, err := FetchDatabaseSize(db)
if err != nil {
return nil, err
}
stat := make(map[string]float64)
mergeStat(stat, statStatDatabase)
mergeStat(stat, statConnections)
mergeStat(stat, statDatabaseSize)
return stat, err
}
func (p PostgresPlugin) GraphDefinition() map[string](mp.Graphs) {
return graphdef
}
func main() {
optHost := flag.String("hostname", "localhost", "Hostname to login to")
optPort := flag.String("port", "5432", "Database port")
optUser := flag.String("user", "", "Postgres User")
optPass := flag.String("password", "", "Postgres Password")
optSSLmode := flag.String("sslmode", "disable", "Whether or not to use SSL")
optConnectTimeout := flag.Int("connect_timeout", 5, "Maximum wait for connection, in seconds.")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
if *optUser == "" {
logger.Warningf("user is required")
flag.PrintDefaults()
os.Exit(1)
}
if *optPass == "" {
logger.Warningf("password is required")
flag.PrintDefaults()
os.Exit(1)
}
var postgres PostgresPlugin
postgres.Host = *optHost
postgres.Port = *optPort
postgres.Username = *optUser
postgres.Password = *optPass
postgres.SSLmode = *optSSLmode
postgres.Timeout = *optConnectTimeout
helper := mp.NewMackerelPlugin(postgres)
if *optTempfile != "" {
helper.Tempfile = *optTempfile
} else {
helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-postgres-%s-%s", *optHost, *optPort)
}
if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
helper.OutputDefinitions()
} else {
helper.OutputValues()
}
}