postgres_monitor 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 29ff454384341fa953a1ad421cd4f721fb91dd05
4
+ data.tar.gz: a81b7f4ff4e01d1f09cb192aa043c158a44caf32
5
+ SHA512:
6
+ metadata.gz: 1ad9882350ef1698530d23e473f5ff08b6a83b3a7826279ceaad27469444bae602f6d6995382b25a01be553d86b5ed43cbb91d495b5df72b0efbe423eff853d4
7
+ data.tar.gz: fcec22dcca7f3eb0f8beb6c9a345f7fca7e49e33afc5e5da702124bdf66ce5e0b3a8e7a85a1caf0b484a6e7f2b9c6c5f1fa626ded3a35894e6f860accc692419
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.2
4
+ before_install: gem install bundler -v 1.10.5
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in postgres_monitor.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Scott Shea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # PostgresMonitor
2
+
3
+ This gem is designed to expose a number of internal metrics and statistics for Postgres installations to the calling application. It borrows heavily from [Heroku's PG Extras](https://github.com/heroku/heroku-pg-extras) and [Boundless's plugin for New Relic](http://newrelic.com/plugins/boundless-production/109)-- [source](https://github.com/GoBoundless/newrelic_postgres_plugin).
4
+
5
+ In each case there were drawbacks that led me to create this gem. Heroku PG Extra's only works on Heroku installations. The New Relic plugin only accepts numerical values; I wanted to see the actual queries in some cases.
6
+
7
+ It uses the [PG gem](https://bitbucket.org/ged/ruby-pg/wiki/Home) for its connections to Postgres
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'postgres_monitor'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install postgres_monitor
24
+
25
+ ## Usage
26
+
27
+ ### Connection to the Database
28
+ To create a connection you will need to supply the host name, user, password (can be nil), and dbname. Port will default to 5432 if it is not provided. sslmode will default to required if it is not supplied.
29
+
30
+ #### Example
31
+
32
+ ```ruby
33
+ @connection_params = {
34
+ host: 'localhost',
35
+ port: nil, # defaults to 5432
36
+ user: 'postgres',
37
+ password: 'password',
38
+ sslmode: 'allow',
39
+ dbname: 'postrges'
40
+ }
41
+
42
+ @monitor = PostgresMonitor::Monitor.new(@connection_params)
43
+ ```
44
+
45
+ ### Results from methods
46
+ The methods return the raw [PG::Result](http://deveiate.org/code/pg/PG/Result.html) for interpretation. This is a collection of hashes, well sometimes just one hash, with the results and keys in them.
47
+
48
+ #### Example
49
+ ```ruby
50
+ results = @monitor.list_databases
51
+ databases = []
52
+ results.each do |row|
53
+ databases << row['datname']
54
+ end
55
+ ```
56
+
57
+ ## Development
58
+
59
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
60
+
61
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
62
+
63
+ ## Contributing
64
+
65
+ Bug reports and pull requests are welcome on GitHub at https://github.com/scottshea/postgres_monitor. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
66
+
67
+
68
+ ## License
69
+
70
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "postgres_monitor"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,524 @@
1
+ module PostgresMonitor
2
+ class Monitor
3
+ def initialize(connection_params)
4
+ @host = connection_params[:host]
5
+ @port = connection_params[:port] ? connection_params[:port] : self.port
6
+ @user = connection_params[:user]
7
+ @password = connection_params[:password]
8
+ @sslmode = connection_params[:sslmode] ? connection_params[:sslmode] : 'require'
9
+ @dbname = connection_params[:dbname]
10
+
11
+ @connection = self.connect
12
+ end
13
+
14
+ # returns database version in SQL form
15
+ def get_database_version
16
+ execute_sql 'SELECT version();'
17
+ end
18
+
19
+ # returns database tranasction and row activity for the DB
20
+ def database_query
21
+ execute_sql "SELECT * FROM pg_stat_database WHERE datname='#{@dbname}';"
22
+ end
23
+
24
+ # returns Scheduled and Requested Checkpoints
25
+ def bgwriter_query
26
+ execute_sql 'SELECT * FROM pg_stat_bgwriter;'
27
+ end
28
+
29
+ # count of indexes in the database
30
+ def index_count_query
31
+ execute_sql "SELECT count(1) as indexes FROM pg_class WHERE relkind = 'i';"
32
+ end
33
+
34
+ def index_size_query
35
+ execute_sql 'SELECT sum(relpages::bigint*8192) AS size FROM pg_class WHERE reltype = 0;'
36
+ end
37
+
38
+ # show the count of sequential scans by table descending by order
39
+ def seq_scans
40
+ execute_sql 'SELECT relname AS name, seq_scan as count FROM pg_stat_user_tables ORDER BY seq_scan DESC;'
41
+ end
42
+
43
+ # show all tables and the number of rows in each ordered by number of rows descending
44
+ def records_rank
45
+ execute_sql 'SELECT relname AS name, n_live_tup AS estimated_count FROM pg_stat_user_tables ORDER BY n_live_tup DESC;'
46
+ end
47
+
48
+ # list all non-template DBs known
49
+ def list_databases
50
+ execute_sql 'SELECT datname FROM pg_database WHERE datistemplate = false;'
51
+ end
52
+
53
+ # returns Active and Idle connections from DB
54
+ def backend_query
55
+ sql = %Q(
56
+ SELECT ( SELECT count(*) FROM pg_stat_activity WHERE
57
+ #{
58
+ if nine_two?
59
+ "state <> 'idle'"
60
+ else
61
+ "current_query <> '<IDLE>'"
62
+ end
63
+ }
64
+ ) AS backends_active, ( SELECT count(*) FROM pg_stat_activity WHERE
65
+ #{
66
+ if nine_two?
67
+ "state = 'idle'"
68
+ else
69
+ "current_query = '<IDLE>'"
70
+ end
71
+ }
72
+ ) AS backends_idle FROM pg_stat_activity;
73
+ )
74
+
75
+ execute_sql(sql)
76
+ end
77
+
78
+ # calculates your cache hit rate (effective databases are at 99% and up)
79
+ def cache_hit
80
+ sql = %q(
81
+ SELECT
82
+ 'index hit rate' AS name,
83
+ (sum(idx_blks_hit)) / nullif(sum(idx_blks_hit + idx_blks_read),0) AS ratio
84
+ FROM
85
+ pg_statio_user_indexes
86
+ UNION ALL
87
+ SELECT
88
+ 'table hit rate' AS name,
89
+ sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read),0) AS ratio
90
+ FROM
91
+ pg_statio_user_tables;
92
+ )
93
+
94
+ execute_sql(sql)
95
+ end
96
+
97
+ # show table and index bloat in your database ordered by most wasteful
98
+ def database_bloat
99
+ sql = %q(
100
+ WITH constants AS (
101
+ SELECT current_setting('block_size')::numeric AS bs, 23 AS hdr, 4 AS ma
102
+ ), bloat_info AS (
103
+ SELECT
104
+ ma,bs,schemaname,tablename,
105
+ (datawidth+(hdr+ma-(case when hdr%ma=0 THEN ma ELSE hdr%ma END)))::numeric AS datahdr,
106
+ (maxfracsum*(nullhdr+ma-(case when nullhdr%ma=0 THEN ma ELSE nullhdr%ma END))) AS nullhdr2
107
+ FROM (
108
+ SELECT
109
+ schemaname, tablename, hdr, ma, bs,
110
+ SUM((1-null_frac)*avg_width) AS datawidth,
111
+ MAX(null_frac) AS maxfracsum,
112
+ hdr+(
113
+ SELECT 1+count(*)/8
114
+ FROM pg_stats s2
115
+ WHERE null_frac<>0 AND s2.schemaname = s.schemaname AND s2.tablename = s.tablename
116
+ ) AS nullhdr
117
+ FROM pg_stats s, constants
118
+ GROUP BY 1,2,3,4,5
119
+ ) AS foo
120
+ ), table_bloat AS (
121
+ SELECT
122
+ schemaname, tablename, cc.relpages, bs,
123
+ CEIL((cc.reltuples*((datahdr+ma-
124
+ (CASE WHEN datahdr%ma=0 THEN ma ELSE datahdr%ma END))+nullhdr2+4))/(bs-20::float)) AS otta
125
+ FROM bloat_info
126
+ JOIN pg_class cc ON cc.relname = bloat_info.tablename
127
+ JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = bloat_info.schemaname AND nn.nspname <> 'information_schema'
128
+ ), index_bloat AS (
129
+ SELECT
130
+ schemaname, tablename, bs,
131
+ COALESCE(c2.relname,'?') AS iname, COALESCE(c2.reltuples,0) AS ituples, COALESCE(c2.relpages,0) AS ipages,
132
+ COALESCE(CEIL((c2.reltuples*(datahdr-12))/(bs-20::float)),0) AS iotta -- very rough approximation, assumes all cols
133
+ FROM bloat_info
134
+ JOIN pg_class cc ON cc.relname = bloat_info.tablename
135
+ JOIN pg_namespace nn ON cc.relnamespace = nn.oid AND nn.nspname = bloat_info.schemaname AND nn.nspname <> 'information_schema'
136
+ JOIN pg_index i ON indrelid = cc.oid
137
+ JOIN pg_class c2 ON c2.oid = i.indexrelid
138
+ )
139
+ SELECT
140
+ type, schemaname, object_name, bloat, pg_size_pretty(raw_waste) as waste
141
+ FROM
142
+ (SELECT
143
+ 'table' as type,
144
+ schemaname,
145
+ tablename as object_name,
146
+ ROUND(CASE WHEN otta=0 THEN 0.0 ELSE table_bloat.relpages/otta::numeric END,1) AS bloat,
147
+ CASE WHEN relpages < otta THEN '0' ELSE (bs*(table_bloat.relpages-otta)::bigint)::bigint END AS raw_waste
148
+ FROM
149
+ table_bloat
150
+ UNION
151
+ SELECT
152
+ 'index' as type,
153
+ schemaname,
154
+ tablename || '::' || iname as object_name,
155
+ ROUND(CASE WHEN iotta=0 OR ipages=0 THEN 0.0 ELSE ipages/iotta::numeric END,1) AS bloat,
156
+ CASE WHEN ipages < iotta THEN '0' ELSE (bs*(ipages-iotta))::bigint END AS raw_waste
157
+ FROM
158
+ index_bloat) bloat_summary
159
+ ORDER BY raw_waste DESC, bloat DESC
160
+ )
161
+
162
+ execute_sql(sql)
163
+ end
164
+
165
+ # show dead rows and whether an automatic vacuum is expected to be triggered
166
+ def vacuum_stats
167
+ sql = %q(
168
+ WITH table_opts AS (
169
+ SELECT
170
+ pg_class.oid, relname, nspname, array_to_string(reloptions, '') AS relopts
171
+ FROM
172
+ pg_class INNER JOIN pg_namespace ns ON relnamespace = ns.oid
173
+ ), vacuum_settings AS (
174
+ SELECT
175
+ oid, relname, nspname,
176
+ CASE
177
+ WHEN relopts LIKE '%autovacuum_vacuum_threshold%'
178
+ THEN regexp_replace(relopts, '.*autovacuum_vacuum_threshold=([0-9.]+).*', E'\\\\\\1')::integer
179
+ ELSE current_setting('autovacuum_vacuum_threshold')::integer
180
+ END AS autovacuum_vacuum_threshold,
181
+ CASE
182
+ WHEN relopts LIKE '%autovacuum_vacuum_scale_factor%'
183
+ THEN regexp_replace(relopts, '.*autovacuum_vacuum_scale_factor=([0-9.]+).*', E'\\\\\\1')::real
184
+ ELSE current_setting('autovacuum_vacuum_scale_factor')::real
185
+ END AS autovacuum_vacuum_scale_factor
186
+ FROM
187
+ table_opts
188
+ )
189
+ SELECT
190
+ vacuum_settings.nspname AS schema,
191
+ vacuum_settings.relname AS table,
192
+ to_char(psut.last_vacuum, 'YYYY-MM-DD HH24:MI') AS last_vacuum,
193
+ to_char(psut.last_autovacuum, 'YYYY-MM-DD HH24:MI') AS last_autovacuum,
194
+ to_char(pg_class.reltuples, '9G999G999G999') AS rowcount,
195
+ to_char(psut.n_dead_tup, '9G999G999G999') AS dead_rowcount,
196
+ to_char(autovacuum_vacuum_threshold
197
+ + (autovacuum_vacuum_scale_factor::numeric * pg_class.reltuples), '9G999G999G999') AS autovacuum_threshold,
198
+ CASE
199
+ WHEN autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor::numeric * pg_class.reltuples) < psut.n_dead_tup
200
+ THEN 'yes'
201
+ END AS expect_autovacuum
202
+ FROM
203
+ pg_stat_user_tables psut INNER JOIN pg_class ON psut.relid = pg_class.oid
204
+ INNER JOIN vacuum_settings ON pg_class.oid = vacuum_settings.oid
205
+ ORDER BY 1
206
+ )
207
+
208
+ execute_sql(sql)
209
+ end
210
+
211
+ ## INDEX queries
212
+ # calculates your index hit rate
213
+ def index_usage
214
+ sql = %q(
215
+ SELECT
216
+ relname,
217
+ CASE idx_scan
218
+ WHEN 0 THEN 'Insufficient data'
219
+ ELSE (100 * idx_scan / (seq_scan + idx_scan))::text
220
+ END percent_of_times_index_used,
221
+ n_live_tup rows_in_table
222
+ FROM
223
+ pg_stat_user_tables
224
+ ORDER BY
225
+ n_live_tup DESC;
226
+ )
227
+
228
+ execute_sql(sql)
229
+ end
230
+
231
+ # show the total size of all indexes in MB
232
+ def total_index_size
233
+ sql = %q(
234
+ SELECT
235
+ pg_size_pretty(sum(c.relpages::bigint*8192)::bigint) AS size
236
+ FROM
237
+ pg_class c
238
+ LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
239
+ WHERE
240
+ n.nspname NOT IN ('pg_catalog', 'information_schema')
241
+ AND n.nspname !~ '^pg_toast'
242
+ AND c.relkind='i';
243
+ )
244
+
245
+ self.execute(sql)
246
+ end
247
+
248
+ # show the size of indexes, descending by size
249
+ def index_size
250
+ sql = %q(
251
+ SELECT
252
+ c.relname AS name,
253
+ pg_size_pretty(sum(c.relpages::bigint*8192)::bigint) AS size
254
+ FROM
255
+ pg_class c
256
+ LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
257
+ WHERE
258
+ n.nspname NOT IN ('pg_catalog', 'information_schema')
259
+ AND n.nspname !~ '^pg_toast'
260
+ AND c.relkind='i'
261
+ GROUP BY
262
+ c.relname
263
+ ORDER BY
264
+ sum(c.relpages) DESC;
265
+ )
266
+ execute_sql(sql)
267
+ end
268
+
269
+ # show unused and almost unused indexes, ordered by their size relative to
270
+ # the number of index scans. Exclude indexes of very small tables (less than
271
+ # 5 pages), where the planner will almost invariably select a sequential
272
+ # scan, but may not in the future as the table grows.
273
+ def unused_indexes
274
+ sql = %q(
275
+ SELECT
276
+ schemaname || '.' || relname AS table,
277
+ indexrelname AS index,
278
+ pg_size_pretty(pg_relation_size(i.indexrelid)) AS index_size,
279
+ idx_scan as index_scans
280
+ FROM
281
+ pg_stat_user_indexes ui
282
+ JOIN
283
+ pg_index i ON ui.indexrelid = i.indexrelid
284
+ WHERE NOT
285
+ indisunique
286
+ AND idx_scan < 50
287
+ AND pg_relation_size(relid) > 5 * 8192
288
+ ORDER BY
289
+ pg_relation_size(i.indexrelid) / nullif(idx_scan, 0) DESC NULLS FIRST,
290
+ pg_relation_size(i.indexrelid) DESC;
291
+ )
292
+
293
+ execute_sql(sql)
294
+ end
295
+
296
+ ## TABLE QUERIES
297
+ # show the size of the tables (excluding indexes), descending by size
298
+ def table_size
299
+ sql = %q(
300
+ SELECT
301
+ c.relname AS name,
302
+ pg_size_pretty(pg_table_size(c.oid)) AS size
303
+ FROM
304
+ pg_class c
305
+ LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
306
+ WHERE
307
+ n.nspname NOT IN ('pg_catalog', 'information_schema')
308
+ AND n.nspname !~ '^pg_toast'
309
+ AND c.relkind='r'
310
+ ORDER BY
311
+ pg_table_size(c.oid) DESC;
312
+ )
313
+
314
+ execute_sql(sql)
315
+ end
316
+
317
+ # show the total size of all the indexes on each table, descending by size
318
+ def table_indexes_size
319
+ sql = %q(
320
+ SELECT
321
+ c.relname AS table,
322
+ pg_size_pretty(pg_indexes_size(c.oid)) AS index_size
323
+ FROM
324
+ pg_class c
325
+ LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
326
+ WHERE
327
+ n.nspname NOT IN ('pg_catalog', 'information_schema')
328
+ AND n.nspname !~ '^pg_toast'
329
+ AND c.relkind='r'
330
+ ORDER BY
331
+ pg_indexes_size(c.oid) DESC;
332
+ )
333
+
334
+ execute_sql(sql)
335
+ end
336
+
337
+ # show the size of the tables (including indexes), descending by size
338
+ def total_table_size
339
+ sql = %q(
340
+ SELECT
341
+ c.relname AS name,
342
+ pg_size_pretty(pg_total_relation_size(c.oid)) AS size
343
+ FROM
344
+ pg_class c
345
+ LEFT JOIN pg_namespace n ON (n.oid = c.relnamespace)
346
+ WHERE
347
+ n.nspname NOT IN ('pg_catalog', 'information_schema')
348
+ AND n.nspname !~ '^pg_toast'
349
+ AND c.relkind='r'
350
+ ORDER BY
351
+ pg_total_relation_size(c.oid) DESC;
352
+ )
353
+
354
+ execute_sql(sql)
355
+ end
356
+
357
+ ## QUERY QUERIES [that feels wrong...]
358
+ # display queries holding locks other queries are waiting to be released
359
+ def blocking
360
+ query_column = self.query_column
361
+ pid_column = self.pid_column
362
+ sql = %Q(
363
+ SELECT
364
+ bl.pid AS blocked_pid,
365
+ ka.#{query_column} AS blocking_statement,
366
+ now() - ka.query_start AS blocking_duration,
367
+ kl.pid AS blocking_pid,
368
+ a.#{query_column} AS blocked_statement,
369
+ now() - a.query_start AS blocked_duration
370
+ FROM
371
+ pg_catalog.pg_locks bl
372
+ JOIN
373
+ pg_catalog.pg_stat_activity a ON bl.pid = a.#{pid_column}
374
+ JOIN
375
+ pg_catalog.pg_locks kl
376
+ JOIN
377
+ pg_catalog.pg_stat_activity ka
378
+ ON kl.pid = ka.#{pid_column}
379
+ ON bl.transactionid = kl.transactionid AND bl.pid != kl.pid
380
+ WHERE NOT
381
+ bl.granted
382
+ )
383
+
384
+ execute_sql(sql)
385
+ end
386
+
387
+ # display queries with active locks
388
+ def locks
389
+ query_column = self.query_column
390
+ pid_column = self.pid_column
391
+ sql = %Q(
392
+ SELECT
393
+ pg_stat_activity.#{pid_column},
394
+ pg_class.relname,
395
+ pg_locks.transactionid,
396
+ pg_locks.granted,
397
+ pg_stat_activity.#{query_column},
398
+ age(now(),pg_stat_activity.query_start) AS "age"
399
+ FROM
400
+ pg_stat_activity,pg_locks left
401
+ OUTER JOIN pg_class ON (pg_locks.relation = pg_class.oid)
402
+ WHERE
403
+ pg_stat_activity.#{query_column} <> '<insufficient privilege>'
404
+ AND pg_locks.pid = pg_stat_activity.#{pid_column}
405
+ AND pg_locks.mode = 'ExclusiveLock'
406
+ AND pg_stat_activity.#{pid_column} <> pg_backend_pid() order by query_start;
407
+ )
408
+
409
+ execute_sql(sql)
410
+ end
411
+
412
+ # show all queries longer than five minutes by descending duration
413
+ def long_running_queries
414
+ query_column = self.query_column
415
+ pid_column = self.pid_column
416
+ sql = %Q(
417
+ SELECT
418
+ #{pid_column},
419
+ now() - pg_stat_activity.query_start AS duration,
420
+ #{query_column} AS query
421
+ FROM
422
+ pg_stat_activity
423
+ WHERE
424
+ pg_stat_activity.#{query_column} <> ''::text
425
+ #{
426
+ if nine_two?
427
+ "AND state <> 'idle'"
428
+ else
429
+ "AND current_query <> '<IDLE>'"
430
+ end
431
+ }
432
+ AND now() - pg_stat_activity.query_start > interval '5 minutes'
433
+ ORDER BY
434
+ now() - pg_stat_activity.query_start DESC;
435
+ )
436
+
437
+ execute_sql(sql)
438
+ end
439
+
440
+ ##PG_STATS_STATEMENTS QUERIES
441
+ # reset pg_stats
442
+ def reset_pg_stats_statements
443
+ return unless extension_loaded? 'pg_stat_statements'
444
+ execute_sql 'SELECT pg_stat_statements_reset();'
445
+ end
446
+ # show 10 queries that have longest execution time in aggregate.
447
+ # needs pg_stat_statements extension
448
+ def outliers
449
+ return unless extension_loaded? 'pg_stat_statements'
450
+
451
+ sql = %q(
452
+ SELECT
453
+ query AS qry,
454
+ interval '1 millisecond' * total_time AS total_exec_time,
455
+ to_char((total_time/sum(total_time) OVER()) * 100, 'FM90D0') || '%' AS prop_exec_time,
456
+ to_char(calls, 'FM999G999G999G990') AS ncalls,
457
+ interval '1 millisecond' * (blk_read_time + blk_write_time) AS sync_io_time
458
+ FROM
459
+ pg_stat_statements WHERE userid = (SELECT usesysid FROM pg_user WHERE usename = current_user LIMIT 1)
460
+ ORDER BY
461
+ total_time DESC LIMIT 10
462
+ )
463
+
464
+ execute_sql(sql)
465
+ end
466
+
467
+ # show 10 most frequently called queries
468
+ # This is dependent on the pg_stat_statements being loaded
469
+ def calls
470
+ return unless extension_loaded? 'pg_stat_statements'
471
+ sql = %Q(
472
+ SELECT
473
+ query AS qry,
474
+ interval '1 millisecond' * total_time AS exec_time,
475
+ to_char((total_time/sum(total_time) OVER()) * 100, 'FM90D0') || '%' AS prop_exec_time,
476
+ to_char(calls, 'FM999G999G990') AS ncalls,
477
+ interval '1 millisecond' * (blk_read_time + blk_write_time) AS sync_io_time
478
+ FROM
479
+ pg_stat_statements WHERE userid = (SELECT usesysid FROM pg_user WHERE usename = current_user LIMIT 1)
480
+ ORDER BY
481
+ calls DESC LIMIT 10
482
+ )
483
+
484
+ execute_sql(sql)
485
+ end
486
+
487
+ ## GENERAL METHODS
488
+ def connect
489
+ PG::Connection.new(:host => @host, :port => @port, :user => @user, :password => @password, :sslmode => @sslmode, :dbname => @dbname)
490
+ end
491
+
492
+ def port
493
+ @port || 5432
494
+ end
495
+
496
+ # Certain queries are dependent on the Postgres version
497
+ def nine_two?
498
+ @connection.server_version >= 90200
499
+ end
500
+
501
+ def query_column
502
+ nine_two? ? 'query' : 'current_query'
503
+ end
504
+
505
+ def pid_column
506
+ nine_two? ? 'pid' : 'procpid'
507
+ end
508
+
509
+ def extension_loaded?(extname)
510
+ @connection.exec("SELECT count(*) FROM pg_extension WHERE extname = '#{extname}'") do |result|
511
+ result[0]['count'] == '1'
512
+ end
513
+ end
514
+
515
+ def close_connection
516
+ @connection.close
517
+ end
518
+
519
+ private
520
+ def execute_sql(query)
521
+ @connection.exec(query)
522
+ end
523
+ end
524
+ end
@@ -0,0 +1,3 @@
1
+ module PostgresMonitor
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,7 @@
1
+ require 'postgres_monitor/version'
2
+ require 'postgres_monitor/monitor'
3
+ require 'pg'
4
+
5
+ module PostgresMonitor
6
+
7
+ end
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'postgres_monitor/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'postgres_monitor'
8
+ spec.version = PostgresMonitor::VERSION
9
+ spec.authors = ['Scott Shea']
10
+ spec.email = ['scott.j.shea@gmail.com']
11
+
12
+ spec.summary = %q{Gem to help monitor Postgres Instances}
13
+ spec.description = %q{This gem is designed to open up SQL queries programatically so that Postgres Databases can be easily monitored}
14
+ spec.homepage = 'https://github.com/scottshea/postgres_monitor'
15
+ spec.license = 'MIT'
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = 'exe'
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ['lib']
21
+
22
+ spec.add_dependency('pg', '~> 0.17', '>= 0.17.0')
23
+
24
+ spec.add_development_dependency 'bundler', '~> 1.10'
25
+ spec.add_development_dependency 'rake', '~> 10.0'
26
+ spec.add_development_dependency 'rspec'
27
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: postgres_monitor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Scott Shea
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-07-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: pg
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.17'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 0.17.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '0.17'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 0.17.0
33
+ - !ruby/object:Gem::Dependency
34
+ name: bundler
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.10'
40
+ type: :development
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1.10'
47
+ - !ruby/object:Gem::Dependency
48
+ name: rake
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '10.0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '10.0'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rspec
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ description: This gem is designed to open up SQL queries programatically so that Postgres
76
+ Databases can be easily monitored
77
+ email:
78
+ - scott.j.shea@gmail.com
79
+ executables: []
80
+ extensions: []
81
+ extra_rdoc_files: []
82
+ files:
83
+ - ".gitignore"
84
+ - ".rspec"
85
+ - ".travis.yml"
86
+ - CODE_OF_CONDUCT.md
87
+ - Gemfile
88
+ - LICENSE.txt
89
+ - README.md
90
+ - Rakefile
91
+ - bin/console
92
+ - bin/setup
93
+ - lib/postgres_monitor.rb
94
+ - lib/postgres_monitor/monitor.rb
95
+ - lib/postgres_monitor/version.rb
96
+ - postgres_monitor.gemspec
97
+ homepage: https://github.com/scottshea/postgres_monitor
98
+ licenses:
99
+ - MIT
100
+ metadata: {}
101
+ post_install_message:
102
+ rdoc_options: []
103
+ require_paths:
104
+ - lib
105
+ required_ruby_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - ">="
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ required_rubygems_version: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - ">="
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ requirements: []
116
+ rubyforge_project:
117
+ rubygems_version: 2.4.6
118
+ signing_key:
119
+ specification_version: 4
120
+ summary: Gem to help monitor Postgres Instances
121
+ test_files: []
122
+ has_rdoc: