-
Notifications
You must be signed in to change notification settings - Fork 21
/
postgresql.go
404 lines (336 loc) · 9.63 KB
/
postgresql.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package postgresql
import (
"database/sql"
"encoding/json"
"fmt"
"net/url"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/mitchellh/mapstructure"
// Postgres Driver
_ "github.com/lib/pq"
"github.com/amonapp/amonagent/plugins"
)
// Counters - XXX
var Counters = map[string]string{
"xact_commit": "xact.commits",
"xact_rollback": "xact.rollbacks",
"blks_read": "performance.disk_read",
"blks_hit": "performance.buffer_hit",
"tup_returned": "rows.returned",
"tup_fetched": "rows.fetched",
"tup_inserted": "rows.inserted",
"tup_updated": "rows.updated",
"tup_deleted": "rows.deleted",
}
// Gauges - XXX
var Gauges = map[string]string{
"numbackends": "connections",
}
// DatabaseStatsSQL - XXX
var DatabaseStatsSQL = `SELECT %s FROM pg_stat_database WHERE datname IN ('%s')`
// MissingIndexesSQL - XXX
var MissingIndexesSQL = `SELECT
relname AS table,
CASE idx_scan
WHEN 0 THEN 'Insufficient data'
ELSE (100 * idx_scan / (seq_scan + idx_scan))::text
END percent_of_times_index_used,
n_live_tup rows_in_table
FROM
pg_stat_user_tables
WHERE
idx_scan > 0
AND (100 * idx_scan / (seq_scan + idx_scan)) < 95
AND n_live_tup >= 10000
ORDER BY
n_live_tup DESC,
relname ASC
`
// SlowQueriesSQL - XXX
var SlowQueriesSQL = `SELECT * FROM
(SELECT
calls,
round(total_time :: NUMERIC, 1) AS total,
round(
(total_time / calls) :: NUMERIC,
3
) AS per_call,
regexp_replace(query, '[ \t\n]+', ' ', 'g') AS query
FROM
pg_stat_statements
WHERE
calls > 100
ORDER BY
total_time / calls DESC
LIMIT 15
) AS inner_table
WHERE
per_call > 5
`
// https://gist.github.com/mattsoldo/3853455
var IndexCacheHitRateSQL = `
-- Index hit rate
WITH idx_hit_rate as (
SELECT
relname as table_name,
n_live_tup,
round(100.0 * idx_scan / (seq_scan + idx_scan + 0.000001),2) as idx_hit_rate
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC
),
-- Cache hit rate
cache_hit_rate as (
SELECT
relname as table_name,
heap_blks_read + heap_blks_hit as reads,
round(100.0 * sum (heap_blks_read + heap_blks_hit) over (ORDER BY heap_blks_read + heap_blks_hit DESC) / sum(heap_blks_read + heap_blks_hit + 0.000001) over (),4) as cumulative_pct_reads,
round(100.0 * heap_blks_hit / (heap_blks_hit + heap_blks_read + 0.000001),2) as cache_hit_rate
FROM pg_statio_user_tables
WHERE heap_blks_hit + heap_blks_read > 0
ORDER BY 2 DESC
)
SELECT
idx_hit_rate.table_name,
idx_hit_rate.n_live_tup as size,
cache_hit_rate.reads,
cache_hit_rate.cumulative_pct_reads,
idx_hit_rate.idx_hit_rate,
cache_hit_rate.cache_hit_rate
FROM idx_hit_rate, cache_hit_rate
WHERE idx_hit_rate.table_name = cache_hit_rate.table_name
AND cumulative_pct_reads < 100.0
ORDER BY reads DESC;
`
// TableSizeSQL - XXX
var TableSizeSQL = `
SELECT
C .relname AS NAME,
CASE
WHEN C .relkind = 'r' THEN
'table'
ELSE
'index'
END AS TYPE,
pg_table_size(C .oid) AS SIZE
FROM
pg_class C
LEFT JOIN pg_namespace n ON (n.oid = C .relnamespace)
WHERE
n.nspname NOT IN (
'pg_catalog',
'information_schema'
)
AND n.nspname !~ '^pg_toast'
AND C .relkind IN ('r', 'i')
ORDER BY
pg_table_size (C .oid) DESC,
NAME ASC
`
// IndexHitRateData - XXX
type IndexHitRateData struct {
Headers []string `json:"headers"`
Data []interface{} `json:"data"`
}
// TableSizeData - XXX
type TableSizeData struct {
Headers []string `json:"headers"`
Data []interface{} `json:"data"`
}
// SlowQueriesData - XXX
type SlowQueriesData struct {
Headers []string `json:"headers"`
Data []interface{} `json:"data"`
}
func (p PerformanceStruct) String() string {
s, _ := json.Marshal(p)
return string(s)
}
// Config - XXX
type Config struct {
Host string
DB string
}
// Start - XXX
func (p *PostgreSQL) Start() error {
return nil
}
// Stop - XXX
func (p *PostgreSQL) Stop() {
}
var sampleConfig = `
# Available config options:
#
# {"host": "postgres://user:password@localhost:port/dbname"}
#
# Config location: /etc/opt/amonagent/plugins-enabled/postgresql.conf
`
// SampleConfig - XXX
func (p *PostgreSQL) SampleConfig() string {
return sampleConfig
}
// SetConfigDefaults - XXX
func (p *PostgreSQL) SetConfigDefaults() error {
configFile, err := plugins.UmarshalPluginConfig("postgresql")
if err != nil {
log.WithFields(log.Fields{"plugin": "postgresql", "error": err.Error()}).Error("Can't read config file")
}
var config Config
decodeError := mapstructure.Decode(configFile, &config)
if decodeError != nil {
log.WithFields(log.Fields{"plugin": "postgresql", "error": decodeError.Error()}).Error("Can't decode config file")
}
u, _ := url.Parse(config.Host)
config.DB = strings.Trim(u.Path, "/")
p.Config = config
return nil
}
// PostgreSQL - XXX
type PostgreSQL struct {
Config Config
}
// PerformanceStruct - XXX
type PerformanceStruct struct {
TableSizeData `json:"tables_size"`
IndexHitRateData `json:"index_hit_rate"`
SlowQueriesData `json:"slow_queries"`
Gauges map[string]interface{} `json:"gauges"`
Counters map[string]interface{} `json:"counters"`
}
// Description - XXX
func (p *PostgreSQL) Description() string {
return "Read metrics from a PostgreSQL server"
}
// Collect - XXX
func (p *PostgreSQL) Collect() (interface{}, error) {
PerformanceStruct := PerformanceStruct{}
p.SetConfigDefaults()
db, err := sql.Open("postgres", p.Config.Host)
if err != nil {
log.Errorf("Can't connect to database': %v", err)
return PerformanceStruct, err
}
defer db.Close()
rawResult := make([][]byte, len(Counters))
counters := make(map[string]interface{})
dest := make([]interface{}, len(Counters)) // A temporary interface{} slice
for i := range rawResult {
dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
var counterColumns []string
for key := range Counters {
counterColumns = append(counterColumns, key)
}
CountersQuery := fmt.Sprintf(DatabaseStatsSQL, strings.Join(counterColumns, ", "), p.Config.DB)
CounterRows, errCounterRows := db.Query(CountersQuery)
if errCounterRows == nil {
defer CounterRows.Close()
for CounterRows.Next() {
err = CounterRows.Scan(dest...)
if err != nil {
log.Errorf("Can't get Counter stats': %v", err)
}
for i, val := range rawResult {
key := counterColumns[i]
counters[key] = string(val)
}
}
}
gauges := make(map[string]interface{})
GaugesQuery := fmt.Sprintf(DatabaseStatsSQL, "numbackends", "amon")
GaugeRows, errGaugeRows := db.Query(GaugesQuery)
if errGaugeRows == nil {
defer GaugeRows.Close()
for GaugeRows.Next() {
var connections int
err = GaugeRows.Scan(&connections)
if err != nil {
log.Errorf("Can't get Gauges': %v", err)
}
gauges["connections"] = connections
}
}
TableSizeRows, errTableSizeRows := db.Query(TableSizeSQL)
TableSizeHeaders := []string{"name", "type", "size"}
TableSizeData := TableSizeData{Headers: TableSizeHeaders}
if errTableSizeRows == nil {
defer TableSizeRows.Close()
for TableSizeRows.Next() {
// TABLES_SIZE_ROWS = ['name','type','size']
var name string
var Type string
var size int64
err = TableSizeRows.Scan(&name, &Type, &size)
if err != nil {
log.Errorf("Can't get Table size rows': %v", err)
}
fields := []interface{}{}
fields = append(fields, name)
fields = append(fields, Type)
fields = append(fields, size)
TableSizeData.Data = append(TableSizeData.Data, fields)
}
PerformanceStruct.TableSizeData = TableSizeData
}
IndexHitRows, errIndexHitRows := db.Query(IndexCacheHitRateSQL)
IndexHitHeaders := []string{"table_name", "size", "reads",
"cumulative_pct_reads", "index_hit_rate", "cache_hit_rate"}
IndexHitData := IndexHitRateData{Headers: IndexHitHeaders}
if errIndexHitRows == nil {
defer IndexHitRows.Close()
for IndexHitRows.Next() {
// INDEX_CACHE_HIT_RATE_ROWS = ['table_name','size','reads',
// 'cumulative_pct_reads', 'index_hit_rate', 'cache_hit_rate']
var TableName string
var Size string
var Read int64
var CumulativeReads float64
var IndexHitRate float64
var CacheHitRate float64
err = IndexHitRows.Scan(&TableName, &Size, &Read, &CumulativeReads, &IndexHitRate, &CacheHitRate)
if err != nil {
log.Errorf("Can't get Index Hit Rate tables': %v", err)
}
fields := []interface{}{}
fields = append(fields, TableName)
fields = append(fields, Size)
fields = append(fields, Read)
fields = append(fields, CumulativeReads)
fields = append(fields, IndexHitRate)
fields = append(fields, CacheHitRate)
IndexHitData.Data = append(IndexHitData.Data, fields)
}
PerformanceStruct.IndexHitRateData = IndexHitData
}
SlowQueriesRows, errSlowQueriesRows := db.Query(SlowQueriesSQL)
SlowQueriesHeaders := []string{"calls", "total", "per_call", "query"}
SlowQueriesData := SlowQueriesData{Headers: SlowQueriesHeaders}
if errSlowQueriesRows == nil {
defer SlowQueriesRows.Close()
for SlowQueriesRows.Next() {
var Calls int64
var Total float64
var PerCall float64
var Query string
err = SlowQueriesRows.Scan(&Calls, &Total, &PerCall, &Query)
if err != nil {
log.Errorf("Can't get Slow Queries': %v", err)
}
fields := []interface{}{}
fields = append(fields, Calls)
fields = append(fields, Total)
fields = append(fields, PerCall)
fields = append(fields, Query)
SlowQueriesData.Data = append(SlowQueriesData.Data, fields)
}
PerformanceStruct.SlowQueriesData = SlowQueriesData
}
PerformanceStruct.Counters = counters
PerformanceStruct.Gauges = gauges
return PerformanceStruct, nil
}
func init() {
plugins.Add("postgresql", func() plugins.Plugin {
return &PostgreSQL{}
})
}